Skip to main content

khive_types/
hash.rs

1//! Content hashes and non-cryptographic change-detection fingerprints.
2
3use core::fmt;
4
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7
8/// Compute the 64-bit FNV-1a fingerprint of every byte in `data`.
9///
10/// Uses the standard offset basis and wrapping multiplication. This is a
11/// non-cryptographic fingerprint; it is not an integrity or security boundary.
12pub 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/// SHA-256 of optional parsed text and an exact raw record.
22///
23/// The frame is a one-byte presence marker, followed, when text is present,
24/// by its big-endian `u64` UTF-8 byte length and bytes. The raw record always
25/// follows as its big-endian `u64` byte length and bytes. No normalization is
26/// performed. This is the persisted session-mirror content-hash format; absent
27/// text, empty text, and delimiter-containing values remain distinct.
28///
29/// Requires the `sha2` feature and does not allocate.
30#[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/// 256-bit (32-byte) content hash.
49///
50/// Used as a content-addressed identifier for HNSW checkpoints and other
51/// snapshot artifacts. The underlying algorithm is caller-defined; the type
52/// carries the raw bytes without encoding assumptions.
53#[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    /// Zero hash (nil value).
60    pub const ZERO: Self = Self([0u8; 32]);
61
62    /// Construct from raw bytes.
63    #[inline]
64    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
65        Self(bytes)
66    }
67
68    /// Return the raw byte representation.
69    #[inline]
70    pub const fn as_bytes(&self) -> &[u8; 32] {
71        &self.0
72    }
73
74    /// Compute a BLAKE3 hash over the given byte slice.
75    ///
76    /// Requires the `blake3` feature.
77    #[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    /// Constant-time equality check.
85    ///
86    /// Accumulates XOR over all 32 bytes without early exit so the comparison
87    /// takes the same number of iterations regardless of where bytes differ.
88    /// Suitable for integrity comparisons where timing side-channels are a
89    /// concern.  The `#[inline(never)]` attribute discourages the compiler from
90    /// inlining and optimising away the full-loop traversal.
91    #[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        // draft-eastlake-fnv-19, Appendix C: strings with and without NUL.
133        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}