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#[cfg(feature = "sha2")]
31pub fn framed_text_sha256(text: Option<&str>, raw: &str) -> Hash32 {
32 use sha2::{Digest, Sha256};
33
34 let mut hash = Sha256::new();
35 match text {
36 Some(value) => {
37 hash.update([1]);
38 hash.update((value.len() as u64).to_be_bytes());
39 hash.update(value.as_bytes());
40 }
41 None => hash.update([0]),
42 }
43 hash.update((raw.len() as u64).to_be_bytes());
44 hash.update(raw.as_bytes());
45 Hash32::from_bytes(hash.finalize().into())
46}
47
48#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
54#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
55#[cfg_attr(feature = "serde", serde(transparent))]
56pub struct Hash32([u8; 32]);
57
58impl Hash32 {
59 pub const ZERO: Self = Self([0u8; 32]);
61
62 #[inline]
64 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
65 Self(bytes)
66 }
67
68 #[inline]
70 pub const fn as_bytes(&self) -> &[u8; 32] {
71 &self.0
72 }
73
74 #[cfg(feature = "blake3")]
78 #[inline]
79 pub fn from_blake3(data: &[u8]) -> Self {
80 let hash = blake3::hash(data);
81 Self(*hash.as_bytes())
82 }
83
84 #[inline(never)]
92 pub fn eq_ct(&self, other: &Self) -> bool {
93 let diff = self
94 .0
95 .iter()
96 .zip(other.0.iter())
97 .fold(0u8, |acc, (a, b)| acc | (a ^ b));
98 diff == 0
99 }
100}
101
102impl From<[u8; 32]> for Hash32 {
103 #[inline]
104 fn from(bytes: [u8; 32]) -> Self {
105 Self(bytes)
106 }
107}
108
109impl fmt::Debug for Hash32 {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 write!(f, "Hash32(")?;
112 for b in &self.0 {
113 write!(f, "{b:02x}")?;
114 }
115 write!(f, ")")
116 }
117}
118
119impl fmt::Display for Hash32 {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 for b in &self.0 {
122 write!(f, "{b:02x}")?;
123 }
124 Ok(())
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 #[test]
131 fn fnv1a_64_matches_published_vectors() {
132 let cases: &[(&[u8], u64)] = &[
134 (b"", 0xcbf2_9ce4_8422_2325),
135 (b"a", 0xaf63_dc4c_8601_ec8c),
136 (b"foobar", 0x8594_4171_f739_67e8),
137 (b"\0", 0xaf63_bd4c_8601_b7df),
138 (b"a\0", 0x089b_e207_b544_f1e4),
139 (b"foobar\0", 0x3453_1ca7_168b_8f38),
140 ];
141 for &(bytes, expected) in cases {
142 assert_eq!(crate::fnv1a_64(bytes), expected);
143 }
144 }
145}