chibihash 0.6.0

Rust implementation of the ChibiHash hash function
Documentation
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! ChibiHash: A small, fast 64-bit hash function implementation in Rust
//!
//! This crate provides a fast, non-cryptographic 64-bit hash function implementation
//! based on the [ChibiHash algorithm](https://github.com/N-R-K/ChibiHash).
//!
//! This is version `v2` of the algorithm. Notes from the original author:
//!
//! - Faster performance on short string (42 cycles/hash vs 34 cycles/hash).
//!   The tail end handling has been reworked entirely with some inspiration
//!   from wyhash's short input reading.
//! - Better seeding. v1 seed only affected 64 bits of the initial state.
//!   v2 seed affects the full 256 bits. This allows it to pass smhasher3's
//!   SeedBlockLen and SeedBlockOffset tests.
//! - Slightly better mixing in bulk handling.
//! - Passes all 252 tests in smhasher3 (commit 34093a3), v1 failed 3.
//!
//! # Examples
//!
//! Basic usage:
//! ```rust
//! use chibihash::v2::{chibi_hash64, ChibiHasher, ChibiHashMap, ChibiHashSet, StreamingChibiHasher};
//! use std::hash::Hasher;
//!
//! // Direct hashing
//! let key = b"Hello, World!";
//! let seed = 1337;
//! let hash = chibi_hash64(key, seed);
//! println!("Hash of '{}' is: {:016x}", String::from_utf8_lossy(key), hash);
//!
//! // Using the Hasher trait
//! let mut hasher = ChibiHasher::new(seed);
//! hasher.write(key);
//! println!("{:016x}", hasher.finish());
//!
//! // Streaming hashing
//! let mut hasher1 = StreamingChibiHasher::new(0);
//! hasher1.update(b"Hello, ");
//! hasher1.update(b"World!");
//! println!("{:016x}", hasher1.finalize());
//!
//! // Using BuildHasher as HashMap
//! let mut map: ChibiHashMap<String, i32> = ChibiHashMap::default();
//! map.insert("hello".to_string(), 42);
//! println!("{:?}", map.get("hello"));
//!
//! // Using BuildHasher as HashSet
//! let mut set: ChibiHashSet<String> = ChibiHashSet::default();
//! set.insert("hello".to_string());
//! println!("{}", set.contains("hello"));
//!
//! // Using BuildHasher as HashMap with custom seed
//! let builder = ChibiHasher::new(42);
//! let mut map: ChibiHashMap<String, i32> = ChibiHashMap::with_hasher(builder);
//! map.insert("hello".to_string(), 42);
//! println!("{:?}", map.get("hello"));
//! ```

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(feature = "hashbrown")]
use hashbrown::{HashMap as BaseHashMap, HashSet as BaseHashSet};
#[cfg(all(feature = "std", not(feature = "hashbrown")))]
use std::collections::{HashMap as BaseHashMap, HashSet as BaseHashSet};

#[cfg(all(not(feature = "std"), not(feature = "hashbrown")))]
use core::hash::Hasher;
#[cfg(all(not(feature = "std"), feature = "hashbrown"))]
use core::hash::{BuildHasher, Hash, Hasher};
#[cfg(feature = "std")]
use std::hash::{BuildHasher, Hash, Hasher};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[cfg(not(feature = "std"))]
use core::convert::TryInto;
#[cfg(feature = "std")]
use std::convert::TryInto;

const K: u64 = 0x2B7E151628AED2A7; // digits of e

pub fn chibi_hash64(key: &[u8], seed: u64) -> u64 {
    let seed2 = seed
        .wrapping_sub(K)
        .rotate_left(15)
        .wrapping_add(seed.wrapping_sub(K).rotate_left(47));

    let mut h = [
        seed,
        seed.wrapping_add(K),
        seed2,
        seed2.wrapping_add(K.wrapping_mul(K) ^ K),
    ];

    let mut p = key;
    let mut l = key.len();

    // Process 32-byte chunks
    while l >= 32 {
        for i in 0..4 {
            let stripe = load_u64_le(&p[i * 8..]);
            h[i] = stripe.wrapping_add(h[i]).wrapping_mul(K);
            h[(i + 1) & 3] = h[(i + 1) & 3].wrapping_add(stripe.rotate_left(27));
        }
        p = &p[32..];
        l -= 32;
    }

    // Process 8-byte chunks
    while l >= 8 {
        h[0] ^= load_u32_le(&p[0..]);
        h[0] = h[0].wrapping_mul(K);
        h[1] ^= load_u32_le(&p[4..]);
        h[1] = h[1].wrapping_mul(K);
        p = &p[8..];
        l -= 8;
    }

    // Handle remaining bytes
    if l >= 4 {
        h[2] ^= load_u32_le(&p[0..]);
        h[3] ^= load_u32_le(&p[l - 4..]);
    } else if l > 0 {
        h[2] ^= u64::from(p[0]);
        h[3] ^= u64::from(p[l / 2]) | (u64::from(p[l - 1]) << 8);
    }

    h[0] = h[0].wrapping_add((h[2].wrapping_mul(K)).rotate_left(31) ^ (h[2] >> 31));
    h[1] = h[1].wrapping_add((h[3].wrapping_mul(K)).rotate_left(31) ^ (h[3] >> 31));
    h[0] = h[0].wrapping_mul(K);
    h[0] ^= h[0] >> 31;
    h[1] = h[1].wrapping_add(h[0]);

    let mut x = (key.len() as u64).wrapping_mul(K);
    x ^= x.rotate_left(29);
    x = x.wrapping_add(seed);
    x ^= h[1];

    x ^= x.rotate_left(15) ^ x.rotate_left(42);
    x = x.wrapping_mul(K);
    x ^= x.rotate_left(13) ^ x.rotate_left(31);

    x
}

#[inline(always)]
fn load_u64_le(bytes: &[u8]) -> u64 {
    u64::from_le_bytes(bytes[..8].try_into().unwrap())
}

/// Configuration for the hash function
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct ChibiHasher {
    seed: u64,
    buffer: Vec<u8>,
}

impl ChibiHasher {
    pub fn new(seed: u64) -> Self {
        Self {
            seed,
            buffer: Vec::new(),
        }
    }

    pub fn hash(&self, input: &[u8]) -> u64 {
        chibi_hash64(input, self.seed)
    }
}

impl Hasher for ChibiHasher {
    fn finish(&self) -> u64 {
        // Hash the accumulated bytes with our chibi_hash64 function
        chibi_hash64(&self.buffer, self.seed)
    }

    fn write(&mut self, bytes: &[u8]) {
        // Append the new bytes to our buffer
        self.buffer.extend_from_slice(bytes);
    }
}

#[cfg(any(feature = "std", feature = "hashbrown"))]
impl BuildHasher for ChibiHasher {
    type Hasher = ChibiHasher;

    fn build_hasher(&self) -> Self::Hasher {
        ChibiHasher::new(self.seed)
    }
}

/// A HashMap that uses ChibiHash by default
#[cfg(any(feature = "std", feature = "hashbrown"))]
pub type ChibiHashMap<K, V> = BaseHashMap<K, V, ChibiHasher>;

/// A HashSet that uses ChibiHash by default
#[cfg(any(feature = "std", feature = "hashbrown"))]
pub type ChibiHashSet<T> = BaseHashSet<T, ChibiHasher>;

/// Streaming ChibiHasher that processes data incrementally
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StreamingChibiHasher {
    h: [u64; 4],
    total_len: u64,
    seed: u64,
    buf: [u8; 32],
    buf_len: usize,
}

impl StreamingChibiHasher {
    #[inline(always)]
    pub const fn new(seed: u64) -> Self {
        let seed2 = seed
            .wrapping_sub(K)
            .rotate_left(15)
            .wrapping_add(seed.wrapping_sub(K).rotate_left(47));

        Self {
            h: [
                seed,
                seed.wrapping_add(K),
                seed2,
                seed2.wrapping_add(K.wrapping_mul(K) ^ K),
            ],
            buf: [0; 32],
            buf_len: 0,
            total_len: 0,
            seed,
        }
    }

    pub fn update(&mut self, input: &[u8]) {
        let mut p = input;
        let mut l = p.len();

        // If there's data in buf, try to fill it up
        if self.buf_len > 0 {
            while l > 0 && self.buf_len < 32 {
                self.buf[self.buf_len] = p[0];
                self.buf_len += 1;
                p = &p[1..];
                l -= 1;
            }

            // Flush if filled
            if self.buf_len == 32 {
                for i in 0..4 {
                    let stripe = load_u64_le(&self.buf[i * 8..]);
                    self.h[i] = stripe.wrapping_add(self.h[i]).wrapping_mul(K);
                    self.h[(i + 1) & 3] = self.h[(i + 1) & 3].wrapping_add(stripe.rotate_left(27));
                }
                self.buf_len = 0;
            }
        }

        // Process 32-byte chunks
        while l >= 32 {
            for i in 0..4 {
                let stripe = load_u64_le(&p[i * 8..]);
                self.h[i] = stripe.wrapping_add(self.h[i]).wrapping_mul(K);
                self.h[(i + 1) & 3] = self.h[(i + 1) & 3].wrapping_add(stripe.rotate_left(27));
            }
            p = &p[32..];
            l -= 32;
        }

        // Store remaining bytes in buffer
        while l > 0 {
            self.buf[self.buf_len] = p[0];
            self.buf_len += 1;
            p = &p[1..];
            l -= 1;
        }

        self.total_len += input.len() as u64;
    }

    pub fn finalize(&self) -> u64 {
        let mut h = self.h;
        let mut p = &self.buf[..self.buf_len];
        let mut l = self.buf_len;

        // Process 8-byte chunks
        while l >= 8 {
            h[0] ^= load_u32_le(&p[0..]);
            h[0] = h[0].wrapping_mul(K);
            h[1] ^= load_u32_le(&p[4..]);
            h[1] = h[1].wrapping_mul(K);
            p = &p[8..];
            l -= 8;
        }

        // Handle remaining bytes
        if l >= 4 {
            h[2] ^= load_u32_le(&p[0..]);
            h[3] ^= load_u32_le(&p[l - 4..]);
        } else if l > 0 {
            h[2] ^= u64::from(p[0]);
            h[3] ^= u64::from(p[l / 2]) | (u64::from(p[l - 1]) << 8);
        }

        h[0] = h[0].wrapping_add((h[2].wrapping_mul(K)).rotate_left(31) ^ (h[2] >> 31));
        h[1] = h[1].wrapping_add((h[3].wrapping_mul(K)).rotate_left(31) ^ (h[3] >> 31));
        h[0] = h[0].wrapping_mul(K);
        h[0] ^= h[0] >> 31;
        h[1] = h[1].wrapping_add(h[0]);

        let mut x = (self.total_len).wrapping_mul(K);
        x ^= x.rotate_left(29);
        x = x.wrapping_add(self.seed);
        x ^= h[1];

        x ^= x.rotate_left(15) ^ x.rotate_left(42);
        x = x.wrapping_mul(K);
        x ^= x.rotate_left(13) ^ x.rotate_left(31);

        x
    }
}

impl Hasher for StreamingChibiHasher {
    fn finish(&self) -> u64 {
        self.finalize()
    }

    fn write(&mut self, bytes: &[u8]) {
        self.update(bytes);
    }
}

#[inline(always)]
fn load_u32_le(bytes: &[u8]) -> u64 {
    u32::from_le_bytes(bytes[..4].try_into().unwrap()) as u64
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(all(not(feature = "std"), feature = "hashbrown"))]
    use alloc::string::{String, ToString};

    // Keep only internal implementation tests here
    #[test]
    fn test_load_u64_le() {
        let bytes = [1, 2, 3, 4, 5, 6, 7, 8];
        assert_eq!(load_u64_le(&bytes), 0x0807060504030201);
    }

    #[test]
    fn test_load_u32_le() {
        let bytes = [1, 2, 3, 4];
        assert_eq!(load_u32_le(&bytes), 0x04030201);
    }

    #[test]
    #[cfg(all(not(feature = "std"), feature = "hashbrown"))]
    fn test_no_std() {
        let key = b"abcdefgh";
        let hash = chibi_hash64(key, 0);
        assert_eq!(hash, 0xA2E39BE0A0689B32);
    }

    #[test]
    fn test_known_hashes() {
        let test_cases = [
            ("", 55555, 0x58AEE94CA9FB5092),
            ("", 0, 0xD4F69E3ECCF128FC),
            ("hi", 0, 0x92C85CA994367DAC),
            ("123", 0, 0x788A224711FF6E25),
            ("abcdefgh", 0, 0xA2E39BE0A0689B32),
            ("Hello, world!", 0, 0xABF8EB3100B2FEC7),
            ("qwertyuiopasdfghjklzxcvbnm123456", 0, 0x90FC5DB7F56967FA),
            ("qwertyuiopasdfghjklzxcvbnm123456789", 0, 0x6DCDCE02882A4975),
        ];

        for (input, seed, expected) in test_cases {
            assert_eq!(chibi_hash64(input.as_bytes(), seed), expected);
        }
    }

    #[test]
    #[cfg(any(feature = "std", feature = "hashbrown"))]
    fn test_chibi_hash_map() {
        let mut map: ChibiHashMap<String, i32> = ChibiHashMap::default();
        map.insert("hello".to_string(), 42);
        assert_eq!(map.get("hello"), Some(&42));
    }

    #[test]
    #[cfg(any(feature = "std", feature = "hashbrown"))]
    fn test_chibi_hash_set() {
        let mut set: ChibiHashSet<String> = ChibiHashSet::default();
        set.insert("hello".to_string());
        assert!(set.contains("hello"));
    }

    #[test]
    fn test_streaming_matches_direct() {
        let test_cases = [
            ("", 55555, 0x58AEE94CA9FB5092),
            ("", 0, 0xD4F69E3ECCF128FC),
            ("hi", 0, 0x92C85CA994367DAC),
            ("123", 0, 0x788A224711FF6E25),
            ("abcdefgh", 0, 0xA2E39BE0A0689B32),
            ("Hello, world!", 0, 0xABF8EB3100B2FEC7),
            ("qwertyuiopasdfghjklzxcvbnm123456", 0, 0x90FC5DB7F56967FA),
            ("qwertyuiopasdfghjklzxcvbnm123456789", 0, 0x6DCDCE02882A4975),
        ];

        // Test direct matches
        for (input, seed, expected) in test_cases {
            let input_bytes = input.as_bytes();
            let direct = chibi_hash64(input_bytes, seed);
            assert_eq!(direct, expected, "Direct hash mismatch");

            let mut streaming = StreamingChibiHasher::new(seed);
            streaming.update(input_bytes);
            let streaming_result = streaming.finalize();

            assert_eq!(
                streaming_result, expected,
                "Streaming hash mismatch for input: {:?}, seed: {}, got: {:016X}, expected: {:016X}",
                input, seed, streaming_result, expected
            );
        }

        // Test split streaming
        let (seed, expected) = (0, 0xABF8EB3100B2FEC7);
        let mut streaming = StreamingChibiHasher::new(seed);
        streaming.update(b"Hello, ");
        streaming.update(b"world!");
        assert_eq!(
            streaming.finalize(),
            expected,
            "Split streaming should match expected hash"
        );
    }
}