bitcoin_private/hex/
mod.rs

1//! Helpers for encoding bytes as hex strings.
2
3pub mod buf_encoder;
4pub mod display;
5
6pub use buf_encoder::BufEncoder;
7
8/// Reexports of extension traits.
9pub mod exts {
10    pub use super::display::DisplayHex;
11}
12
13/// Possible case of hex.
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
15pub enum Case {
16    /// Produce lower-case chars (`[0-9a-f]`).
17    ///
18    /// This is the default.
19    Lower,
20
21    /// Produce upper-case chars (`[0-9A-F]`).
22    Upper,
23}
24
25impl Default for Case {
26    fn default() -> Self { Case::Lower }
27}
28
29impl Case {
30    /// Returns the encoding table.
31    ///
32    /// The returned table may only contain displayable ASCII chars.
33    #[inline]
34    #[rustfmt::skip]
35    pub(crate) fn table(self) -> &'static [u8; 16] {
36        static LOWER: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f'];
37        static UPPER: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'A', b'B', b'C', b'D', b'E', b'F'];
38
39        match self {
40            Case::Lower => &LOWER,
41            Case::Upper => &UPPER,
42        }
43    }
44}
45
46/// Encodes single byte as two ASCII chars using the given table.
47///
48/// The function guarantees only returning values from the provided table.
49#[inline]
50pub(crate) fn byte_to_hex(byte: u8, table: &[u8; 16]) -> [u8; 2] {
51    [table[usize::from(byte.wrapping_shr(4))], table[usize::from(byte & 0x0F)]]
52}