Skip to main content

quai_primitives/
hash.rs

1use core::{fmt, str::FromStr};
2
3/// Exactly 32 bytes, used for RPC hashes and storage words; no ledger is implied.
4#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
5pub struct Hash32([u8; 32]);
6
7/// A hash must contain exactly 64 hexadecimal digits after lowercase `0x`.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct Hash32Error;
10
11impl fmt::Display for Hash32Error {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        f.write_str("expected 0x-prefixed 32-byte hexadecimal value")
14    }
15}
16impl std::error::Error for Hash32Error {}
17
18impl Hash32 {
19    /// The all-zero value.
20    pub const ZERO: Self = Self([0; 32]);
21    /// Construct from an exact-size byte array.
22    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
23        Self(bytes)
24    }
25    /// Borrow all 32 bytes.
26    pub const fn bytes(&self) -> &[u8; 32] {
27        &self.0
28    }
29    /// Consume into the exact-size byte array.
30    pub const fn into_bytes(self) -> [u8; 32] {
31        self.0
32    }
33}
34
35impl From<[u8; 32]> for Hash32 {
36    fn from(bytes: [u8; 32]) -> Self {
37        Self(bytes)
38    }
39}
40impl From<Hash32> for [u8; 32] {
41    fn from(hash: Hash32) -> Self {
42        hash.0
43    }
44}
45impl AsRef<[u8]> for Hash32 {
46    fn as_ref(&self) -> &[u8] {
47        &self.0
48    }
49}
50impl FromStr for Hash32 {
51    type Err = Hash32Error;
52    fn from_str(input: &str) -> Result<Self, Self::Err> {
53        if input.len() != 66 || !input.starts_with("0x") {
54            return Err(Hash32Error);
55        }
56        fn nibble(byte: u8) -> Result<u8, Hash32Error> {
57            match byte {
58                b'0'..=b'9' => Ok(byte - b'0'),
59                b'a'..=b'f' => Ok(byte - b'a' + 10),
60                b'A'..=b'F' => Ok(byte - b'A' + 10),
61                _ => Err(Hash32Error),
62            }
63        }
64        let mut bytes = [0; 32];
65        for (byte, pair) in bytes.iter_mut().zip(input.as_bytes()[2..].chunks_exact(2)) {
66            *byte = nibble(pair[0])? * 16 + nibble(pair[1])?;
67        }
68        Ok(Self(bytes))
69    }
70}
71impl fmt::Display for Hash32 {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str("0x")?;
74        for byte in self.0 {
75            write!(f, "{byte:02x}")?;
76        }
77        Ok(())
78    }
79}
80impl fmt::Debug for Hash32 {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        fmt::Display::fmt(self, f)
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    #[test]
90    fn exact_width_roundtrip_and_rejection() {
91        let hash = Hash32::from_bytes(core::array::from_fn(|i| i as u8));
92        assert_eq!(hash.to_string().parse(), Ok(hash));
93        assert_eq!(
94            format!("0x{}", "AB".repeat(32)).parse(),
95            Ok(Hash32::from_bytes([0xab; 32]))
96        );
97        for input in [
98            "0x".into(),
99            "00".repeat(32),
100            format!("0X{}", "00".repeat(32)),
101            format!("0x{}", "00".repeat(31)),
102            format!("0x{}", "00".repeat(33)),
103            format!("0x{}", "gg".repeat(32)),
104            format!("0x{}", "é".repeat(32)),
105        ] {
106            assert!(input.parse::<Hash32>().is_err());
107        }
108    }
109}