bitcoin_internals/hex/
mod.rs

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