Skip to main content

datalog_structural_model/digest/
hex.rs

1//! Lowercase hexadecimal text for 32-byte digests.
2
3use std::fmt;
4
5const DIGEST_LEN: usize = 32;
6const HEX_LEN: usize = DIGEST_LEN * 2;
7const ALPHABET: &[u8; 16] = b"0123456789abcdef";
8
9/// Why a digest text could not be parsed.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum DigestParseError {
12    /// The text is not exactly 64 characters long.
13    Length {
14        /// Number of bytes found.
15        found: usize,
16    },
17    /// A character is not a lowercase hexadecimal digit.
18    Digit {
19        /// Byte offset of the offending character.
20        offset: usize,
21    },
22}
23
24impl fmt::Display for DigestParseError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::Length { found } => {
28                write!(f, "digest must be {HEX_LEN} hex characters, found {found}")
29            }
30            Self::Digit { offset } => {
31                write!(
32                    f,
33                    "digest has a non-lowercase-hex character at offset {offset}"
34                )
35            }
36        }
37    }
38}
39
40impl std::error::Error for DigestParseError {}
41
42/// Raw digest bytes with hex text conversion.
43#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub(super) struct DigestBytes(pub(super) [u8; DIGEST_LEN]);
45
46impl DigestBytes {
47    pub(super) fn parse(text: &str) -> Result<Self, DigestParseError> {
48        let bytes = text.as_bytes();
49        if bytes.len() != HEX_LEN {
50            return Err(DigestParseError::Length { found: bytes.len() });
51        }
52        let mut out = [0_u8; DIGEST_LEN];
53        for (index, slot) in out.iter_mut().enumerate() {
54            let high = Self::nibble(bytes, index * 2)?;
55            let low = Self::nibble(bytes, index * 2 + 1)?;
56            *slot = (high << 4) | low;
57        }
58        Ok(Self(out))
59    }
60
61    fn nibble(bytes: &[u8], offset: usize) -> Result<u8, DigestParseError> {
62        match bytes[offset] {
63            digit @ b'0'..=b'9' => Ok(digit - b'0'),
64            digit @ b'a'..=b'f' => Ok(digit - b'a' + 10),
65            _ => Err(DigestParseError::Digit { offset }),
66        }
67    }
68}
69
70impl fmt::Display for DigestBytes {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        for byte in self.0 {
73            let pair = [
74                ALPHABET[usize::from(byte >> 4)],
75                ALPHABET[usize::from(byte & 0x0f)],
76            ];
77            f.write_str(std::str::from_utf8(&pair).map_err(|_| fmt::Error)?)?;
78        }
79        Ok(())
80    }
81}