Skip to main content

waratah_storage/encode/
str_hash.rs

1//! 128-bit SipHash-2-4 string identifiers (Oxigraph-compatible).
2
3use siphasher::sip128::{Hasher128, SipHasher24};
4use std::cmp::Ordering;
5use std::collections::{HashMap, HashSet};
6use std::fmt;
7use std::hash::{BuildHasher, Hash, Hasher};
8
9/// SipHash-2-4 digest of a UTF-8 string (big-endian on the wire).
10#[derive(Eq, PartialEq, Debug, Clone, Copy)]
11pub struct StrHash {
12    hash: [u8; 16],
13}
14
15impl StrHash {
16    /// Hash `value` with SipHasher24 (keys `k0 = 0`, `k1 = 0`).
17    pub fn new(value: &str) -> Self {
18        Self::from_bytes(value.as_bytes())
19    }
20
21    /// Hash raw bytes with SipHasher24 (keys `k0 = 0`, `k1 = 0`).
22    ///
23    /// `StrHash::new` is this over UTF-8 bytes; blob ids and other
24    /// content-addressed identifiers hash raw binary payloads with it.
25    pub fn from_bytes(bytes: &[u8]) -> Self {
26        let mut hasher = SipHasher24::new();
27        hasher.write(bytes);
28        Self {
29            hash: u128::from(hasher.finish128()).to_be_bytes(),
30        }
31    }
32
33    /// Construct from big-endian wire bytes.
34    #[inline]
35    pub const fn from_be_bytes(hash: [u8; 16]) -> Self {
36        Self { hash }
37    }
38
39    /// Serialize to big-endian wire bytes.
40    #[inline]
41    pub const fn to_be_bytes(self) -> [u8; 16] {
42        self.hash
43    }
44
45    /// View as `u128` (big-endian interpretation).
46    #[inline]
47    pub fn as_u128(self) -> u128 {
48        u128::from_be_bytes(self.hash)
49    }
50
51    /// High 64 bits of the big-endian 128-bit digest (identity hash for maps).
52    #[inline]
53    pub fn upper_u64(self) -> u64 {
54        (self.as_u128() >> 64) as u64
55    }
56}
57
58impl PartialOrd for StrHash {
59    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
60        Some(self.cmp(other))
61    }
62}
63
64impl Ord for StrHash {
65    fn cmp(&self, other: &Self) -> Ordering {
66        self.hash.cmp(&other.hash)
67    }
68}
69
70impl Hash for StrHash {
71    #[inline]
72    fn hash<H: Hasher>(&self, state: &mut H) {
73        // Big-endian wire value (same numeric view as [`Self::as_u128`]).
74        state.write_u128(self.as_u128());
75    }
76}
77
78/// [`BuildHasher`] that treats [`StrHash`] as pre-hashed via its upper 64 bits.
79///
80/// [`HashMap`] still stores the full [`StrHash`] key and uses [`Eq`] to finish
81/// the lookup; only bucket selection skips a second SipHash over the 16 bytes.
82#[derive(Debug, Clone, Default)]
83pub struct StrHashIdentityBuildHasher;
84
85impl BuildHasher for StrHashIdentityBuildHasher {
86    type Hasher = StrHashIdentityHasher;
87
88    #[inline]
89    fn build_hasher(&self) -> Self::Hasher {
90        StrHashIdentityHasher { hash: 0 }
91    }
92}
93
94/// Identity hasher paired with [`StrHashIdentityBuildHasher`].
95///
96/// Expects [`StrHash::hash`] to call [`Hasher::write_u128`] with [`StrHash::as_u128`]
97/// (big-endian on-wire integer); bucket hash is the high 64 bits.
98#[derive(Debug, Clone)]
99pub struct StrHashIdentityHasher {
100    hash: u64,
101}
102
103impl Hasher for StrHashIdentityHasher {
104    #[inline]
105    fn write(&mut self, bytes: &[u8]) {
106        // Fallback for non-StrHash keys (should not be used with this BuildHasher).
107        for &b in bytes {
108            self.hash = self.hash.rotate_left(8) ^ u64::from(b);
109        }
110    }
111
112    #[inline]
113    fn write_u128(&mut self, i: u128) {
114        self.hash = (i >> 64) as u64;
115    }
116
117    #[inline]
118    fn finish(&self) -> u64 {
119        self.hash
120    }
121}
122
123/// [`HashMap`] from [`StrHash`] → `String` using upper-64 identity hashing.
124pub type StrHashMap = HashMap<StrHash, String, StrHashIdentityBuildHasher>;
125
126/// Empty [`StrHashMap`].
127#[inline]
128pub fn new_str_hash_map() -> StrHashMap {
129    HashMap::with_hasher(StrHashIdentityBuildHasher)
130}
131
132/// [`HashSet`] of [`StrHash`] using upper-64 identity hashing.
133pub type StrHashSet = HashSet<StrHash, StrHashIdentityBuildHasher>;
134
135/// Empty [`StrHashSet`].
136#[inline]
137pub fn new_str_hash_set() -> StrHashSet {
138    HashSet::with_hasher(StrHashIdentityBuildHasher)
139}
140
141/// [`HashMap`] from [`StrHash`] → blob payload bytes using upper-64 identity
142/// hashing (the blob-payload mirror of [`StrHashMap`]).
143pub type StrBlobMap = HashMap<StrHash, Vec<u8>, StrHashIdentityBuildHasher>;
144
145/// Empty [`StrBlobMap`].
146#[inline]
147pub fn new_str_blob_map() -> StrBlobMap {
148    HashMap::with_hasher(StrHashIdentityBuildHasher)
149}
150
151impl fmt::Display for StrHash {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(f, "{:032x}", self.as_u128())
154    }
155}
156
157impl fmt::LowerHex for StrHash {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        fmt::LowerHex::fmt(&self.as_u128(), f)
160    }
161}
162
163impl fmt::UpperHex for StrHash {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        fmt::UpperHex::fmt(&self.as_u128(), f)
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn str_hash_stability() {
175        const EMPTY_HASH: [u8; 16] = [
176            244, 242, 206, 212, 71, 171, 2, 66, 125, 224, 163, 128, 71, 215, 73, 80,
177        ];
178        const FOO_HASH: [u8; 16] = [
179            177, 216, 59, 176, 7, 47, 87, 243, 76, 253, 150, 32, 126, 153, 216, 19,
180        ];
181
182        assert_eq!(StrHash::new("").to_be_bytes(), EMPTY_HASH);
183        assert_eq!(StrHash::from_be_bytes(EMPTY_HASH).to_be_bytes(), EMPTY_HASH);
184        assert_eq!(StrHash::new("foo").to_be_bytes(), FOO_HASH);
185        assert_eq!(StrHash::from_be_bytes(FOO_HASH).to_be_bytes(), FOO_HASH);
186    }
187
188    #[test]
189    fn str_hash_ordering_is_lexicographic_on_be_bytes() {
190        let a = StrHash::new("a");
191        let b = StrHash::new("b");
192        assert_ne!(a, b);
193        assert_eq!(a.cmp(&a), Ordering::Equal);
194    }
195
196    #[test]
197    fn identity_hasher_uses_upper_u64() {
198        let h = StrHash::new("foo");
199        assert_eq!(h.upper_u64(), (h.as_u128() >> 64) as u64);
200
201        let mut map = new_str_hash_map();
202        map.insert(h, "foo".into());
203        assert_eq!(map.get(&h).map(String::as_str), Some("foo"));
204        assert_eq!(map.get(&StrHash::new("bar")), None);
205
206        let mut set = new_str_hash_set();
207        assert!(set.insert(h));
208        assert!(!set.insert(h));
209    }
210}