postgres_protocol/
hex.rs

1use std::fmt::{self, Formatter, LowerHex, Write};
2
3const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
4
5pub(crate) struct LowerHexWrapper<T>(pub T);
6
7impl<T: AsRef<[u8]>> LowerHex for LowerHexWrapper<T> {
8    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
9        for &b in self.0.as_ref() {
10            let [a, b] = encode_byte(b);
11            f.write_char(char::from(a))?;
12            f.write_char(char::from(b))?;
13        }
14
15        Ok(())
16    }
17}
18
19const fn encode_byte(byte: u8) -> [u8; 2] {
20    [lower_nibble_to_hex(byte >> 4), lower_nibble_to_hex(byte)]
21}
22
23const fn lower_nibble_to_hex(half_byte: u8) -> u8 {
24    HEX_CHARS[(half_byte & 0x0F) as usize]
25}