datalog_structural_model/digest/
hex.rs1use std::fmt;
4
5const DIGEST_LEN: usize = 32;
6const HEX_LEN: usize = DIGEST_LEN * 2;
7const ALPHABET: &[u8; 16] = b"0123456789abcdef";
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum DigestParseError {
12 Length {
14 found: usize,
16 },
17 Digit {
19 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#[derive(
44 Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
45)]
46#[serde(transparent)]
47pub(super) struct DigestBytes(pub(super) [u8; DIGEST_LEN]);
48
49impl DigestBytes {
50 pub(super) fn parse(text: &str) -> Result<Self, DigestParseError> {
51 let bytes = text.as_bytes();
52 if bytes.len() != HEX_LEN {
53 return Err(DigestParseError::Length { found: bytes.len() });
54 }
55 let mut out = [0_u8; DIGEST_LEN];
56 for (index, slot) in out.iter_mut().enumerate() {
57 let high = Self::nibble(bytes, index * 2)?;
58 let low = Self::nibble(bytes, index * 2 + 1)?;
59 *slot = (high << 4) | low;
60 }
61 Ok(Self(out))
62 }
63
64 fn nibble(bytes: &[u8], offset: usize) -> Result<u8, DigestParseError> {
65 match bytes[offset] {
66 digit @ b'0'..=b'9' => Ok(digit - b'0'),
67 digit @ b'a'..=b'f' => Ok(digit - b'a' + 10),
68 _ => Err(DigestParseError::Digit { offset }),
69 }
70 }
71}
72
73impl fmt::Display for DigestBytes {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 for byte in self.0 {
76 let pair = [
77 ALPHABET[usize::from(byte >> 4)],
78 ALPHABET[usize::from(byte & 0x0f)],
79 ];
80 f.write_str(std::str::from_utf8(&pair).map_err(|_| fmt::Error)?)?;
81 }
82 Ok(())
83 }
84}