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/// 256-bit (32-byte) content hash.
22///
23/// Used as a content-addressed identifier for HNSW checkpoints and other
24/// snapshot artifacts. The underlying algorithm is caller-defined; the type
25/// carries the raw bytes without encoding assumptions.
26#[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    /// Zero hash (nil value).
33    pub const ZERO: Self = Self([0u8; 32]);
34
35    /// Construct from raw bytes.
36    #[inline]
37    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
38        Self(bytes)
39    }
40
41    /// Return the raw byte representation.
42    #[inline]
43    pub const fn as_bytes(&self) -> &[u8; 32] {
44        &self.0
45    }
46
47    /// Compute a BLAKE3 hash over the given byte slice.
48    ///
49    /// Requires the `blake3` feature.
50    #[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    /// Constant-time equality check.
58    ///
59    /// Accumulates XOR over all 32 bytes without early exit so the comparison
60    /// takes the same number of iterations regardless of where bytes differ.
61    /// Suitable for integrity comparisons where timing side-channels are a
62    /// concern.  The `#[inline(never)]` attribute discourages the compiler from
63    /// inlining and optimising away the full-loop traversal.
64    #[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        // draft-eastlake-fnv-19, Appendix C: strings with and without NUL.
106        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}