1use core::fmt;
4
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7
8pub fn fnv1a_64(data: &[u8]) -> u64 {
13 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
14 for &byte in data {
15 hash ^= u64::from(byte);
16 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
17 }
18 hash
19}
20
21#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
27#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
28#[cfg_attr(feature = "serde", serde(transparent))]
29pub struct Hash32([u8; 32]);
30
31impl Hash32 {
32 pub const ZERO: Self = Self([0u8; 32]);
34
35 #[inline]
37 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
38 Self(bytes)
39 }
40
41 #[inline]
43 pub const fn as_bytes(&self) -> &[u8; 32] {
44 &self.0
45 }
46
47 #[cfg(feature = "blake3")]
51 #[inline]
52 pub fn from_blake3(data: &[u8]) -> Self {
53 let hash = blake3::hash(data);
54 Self(*hash.as_bytes())
55 }
56
57 #[inline(never)]
65 pub fn eq_ct(&self, other: &Self) -> bool {
66 let diff = self
67 .0
68 .iter()
69 .zip(other.0.iter())
70 .fold(0u8, |acc, (a, b)| acc | (a ^ b));
71 diff == 0
72 }
73}
74
75impl From<[u8; 32]> for Hash32 {
76 #[inline]
77 fn from(bytes: [u8; 32]) -> Self {
78 Self(bytes)
79 }
80}
81
82impl fmt::Debug for Hash32 {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "Hash32(")?;
85 for b in &self.0 {
86 write!(f, "{b:02x}")?;
87 }
88 write!(f, ")")
89 }
90}
91
92impl fmt::Display for Hash32 {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 for b in &self.0 {
95 write!(f, "{b:02x}")?;
96 }
97 Ok(())
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 #[test]
104 fn fnv1a_64_matches_published_vectors() {
105 let cases: &[(&[u8], u64)] = &[
107 (b"", 0xcbf2_9ce4_8422_2325),
108 (b"a", 0xaf63_dc4c_8601_ec8c),
109 (b"foobar", 0x8594_4171_f739_67e8),
110 (b"\0", 0xaf63_bd4c_8601_b7df),
111 (b"a\0", 0x089b_e207_b544_f1e4),
112 (b"foobar\0", 0x3453_1ca7_168b_8f38),
113 ];
114 for &(bytes, expected) in cases {
115 assert_eq!(crate::fnv1a_64(bytes), expected);
116 }
117 }
118}