Skip to main content

lean_ctx/core/
hasher.rs

1//! Central hashing utility using BLAKE3.
2//!
3//! Replaces scattered MD5 helpers with a single, fast, non-cryptographic
4//! hash function. BLAKE3 runs at 8+ GB/s (vs MD5 ~3 GB/s) and produces
5//! collision-resistant 256-bit digests.
6
7/// Return a hex-encoded BLAKE3 hash of the input bytes.
8#[inline]
9pub fn hash_hex(data: &[u8]) -> String {
10    blake3::hash(data).to_hex().to_string()
11}
12
13/// Convenience: hash a string slice and return hex digest.
14#[inline]
15pub fn hash_str(s: &str) -> String {
16    hash_hex(s.as_bytes())
17}
18
19/// Short hash (first 16 hex chars = 64 bits) for cache keys and fingerprints.
20#[inline]
21pub fn hash_short(s: &str) -> String {
22    let full = blake3::hash(s.as_bytes()).to_hex();
23    full[..16].to_string()
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn deterministic() {
32        let a = hash_hex(b"hello");
33        let b = hash_hex(b"hello");
34        assert_eq!(a, b);
35        assert_eq!(a.len(), 64);
36    }
37
38    #[test]
39    fn short_hash_length() {
40        let s = hash_short("test");
41        assert_eq!(s.len(), 16);
42    }
43
44    #[test]
45    fn different_inputs_differ() {
46        assert_ne!(hash_str("foo"), hash_str("bar"));
47    }
48}