av_core/hash.rs
1//! Non-cryptographic hash helpers.
2//!
3//! For SHA-256 and other cryptographic digests use [`crate::digest`].
4
5/// FNV-1a 64-bit hash of `bytes`.
6///
7/// Deterministic across processes and platforms; used for partition
8/// assignment (`av-bridge`) and hashed embeddings (`av-loopdetect`).
9/// A single implementation prevents silent drift between producers and
10/// consumers of the same hash.
11pub fn fnv1a(bytes: &[u8]) -> u64 {
12 const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
13 const PRIME: u64 = 0x0000_0100_0000_01b3;
14 let mut h = OFFSET;
15 for b in bytes {
16 h ^= u64::from(*b);
17 h = h.wrapping_mul(PRIME);
18 }
19 h
20}
21
22#[cfg(test)]
23mod tests {
24 use super::*;
25
26 // Reference vectors from http://www.isthe.com/chongo/tech/comp/fnv/#FNV-test-vectors
27 #[test]
28 fn empty_matches_offset_basis() {
29 assert_eq!(fnv1a(b""), 0xcbf2_9ce4_8422_2325);
30 }
31
32 #[test]
33 fn known_vector_a() {
34 assert_eq!(fnv1a(b"a"), 0xaf63_dc4c_8601_ec8c);
35 }
36
37 #[test]
38 fn known_vector_foobar() {
39 assert_eq!(fnv1a(b"foobar"), 0x8594_4171_f739_67e8);
40 }
41}