1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! FNV-1a hash function for NCS field name lookups
/// FNV-1a 64-bit offset basis
pub const FNV1A_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
/// FNV-1a 64-bit prime
pub const FNV1A_PRIME: u64 = 0x100000001b3;
/// Compute FNV-1a 64-bit hash of a byte slice
///
/// This is the hash function used by NCS for field name lookups.
///
/// # Example
///
/// ```
/// use bl4_ncs::fnv1a_hash;
///
/// let hash = fnv1a_hash(b"children|map");
/// ```
pub fn fnv1a_hash(data: &[u8]) -> u64 {
let mut hash = FNV1A_OFFSET_BASIS;
for &byte in data {
hash ^= byte as u64;
hash = hash.wrapping_mul(FNV1A_PRIME);
}
hash
}
/// Compute FNV-1a hash of a string
#[allow(dead_code)]
pub fn fnv1a_hash_str(s: &str) -> u64 {
fnv1a_hash(s.as_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fnv1a_empty() {
assert_eq!(fnv1a_hash(b""), FNV1A_OFFSET_BASIS);
}
#[test]
fn test_fnv1a_basic() {
// Known test vectors for FNV-1a
// "a" should hash to a specific value
let hash = fnv1a_hash(b"a");
assert_ne!(hash, FNV1A_OFFSET_BASIS);
}
#[test]
fn test_fnv1a_field_names() {
// Hash some NCS field names - these should be deterministic
let h1 = fnv1a_hash(b"children|map");
let h2 = fnv1a_hash(b"children|map");
assert_eq!(h1, h2);
// Different names should have different hashes
let h3 = fnv1a_hash(b"sections|map");
assert_ne!(h1, h3);
}
#[test]
fn test_fnv1a_hash_str() {
// String wrapper should match byte slice version
assert_eq!(fnv1a_hash_str("test"), fnv1a_hash(b"test"));
assert_eq!(fnv1a_hash_str(""), fnv1a_hash(b""));
assert_eq!(fnv1a_hash_str("children|map"), fnv1a_hash(b"children|map"));
}
}