fixed-hashmap 0.1.0

A fixed-capacity, allocation-free hashmap for fixed-size byte keys and values
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Fixed-capacity map implementation.

#[cfg(feature = "secure-hash")]
use super::hash::SecureHasher;
use super::hash::{FastHasher, KeyHasher};
use super::simd::{LANES, tag_masks};
use core::mem::MaybeUninit;

/// Caller-provided, uninitialized storage for one key-value entry.
pub type EntryStorage<const K: usize, const V: usize> = MaybeUninit<([u8; K], [u8; V])>;

/// Error returned when the backing storage is too small for a map.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StorageError {
    /// Twice the requested entry capacity overflows `usize`.
    CapacityOverflow,
    /// The entry buffer has fewer than `required` physical slots.
    NotEnoughEntries { required: usize, available: usize },
    /// The tag buffer has fewer than `required` physical slots.
    NotEnoughTags { required: usize, available: usize },
}

/// A key-value pair rejected because the map was full.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InsertError<const K: usize, const V: usize> {
    /// The key that could not be inserted.
    pub key: [u8; K],
    /// The value that could not be inserted.
    pub value: [u8; V],
}

/// A fixed-capacity hashmap over caller-provided storage.
///
/// `N` is the maximum number of entries, and `K` and `V` are the fixed key and
/// value sizes. The map uses `2 * N` caller-provided slots, keeping occupancy
/// at or below 50%. The map itself does not allocate. Deletion is not supported.
pub struct FixedMap<'a, const N: usize, const K: usize, const V: usize, H = FastHasher> {
    entries: &'a mut [EntryStorage<K, V>],
    tags: &'a mut [u8],
    len: usize,
    hasher: H,
}

enum SlotSearch {
    Found(usize),
    Vacant(usize),
    Full,
}

const SIMD_AFTER_PROBES: usize = 8;

impl<'a, const N: usize, const K: usize, const V: usize, H: KeyHasher<K>> FixedMap<'a, N, K, V, H> {
    /// Creates an empty map with a custom key hasher and supplied storage.
    ///
    /// `entries` and `tags` must each contain at least `2 * N` elements.
    /// The required tags are cleared.
    pub fn with_hasher(
        entries: &'a mut [EntryStorage<K, V>],
        tags: &'a mut [u8],
        hasher: H,
    ) -> Result<Self, StorageError> {
        let slots = N.checked_mul(2).ok_or(StorageError::CapacityOverflow)?;

        if entries.len() < slots {
            return Err(StorageError::NotEnoughEntries {
                required: slots,
                available: entries.len(),
            });
        }

        if tags.len() < slots {
            return Err(StorageError::NotEnoughTags {
                required: slots,
                available: tags.len(),
            });
        }

        let entries = &mut entries[..slots];
        let tags = &mut tags[..slots];
        tags.fill(0);
        Ok(Self {
            entries,
            tags,
            len: 0,
            hasher,
        })
    }

    /// Returns the map's fixed capacity.
    pub const fn capacity(&self) -> usize {
        N
    }

    /// Returns the number of entries currently stored.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns whether the map contains no entries.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns whether the map has reached its capacity.
    pub const fn is_full(&self) -> bool {
        self.len == N
    }

    /// Gets a reference to the value for `key`, if present.
    #[inline]
    pub fn get(&self, key: &[u8; K]) -> Option<&[u8; V]> {
        match find_slot::<N, K, V>(
            self.entries.as_ptr(),
            self.tags.as_ptr(),
            key,
            self.hasher.hash(key),
        ) {
            SlotSearch::Found(index) => {
                // A nonzero tag is written only after the entry is initialized.
                // SAFETY: find_slot returns only indices in the 2N physical slots.
                let (_, value) = unsafe { self.entries.get_unchecked(index).assume_init_ref() };
                Some(value)
            }
            SlotSearch::Vacant(_) | SlotSearch::Full => None,
        }
    }

    /// Gets a mutable reference to the value for `key`, if present.
    #[inline]
    pub fn get_mut(&mut self, key: &[u8; K]) -> Option<&mut [u8; V]> {
        match find_slot::<N, K, V>(
            self.entries.as_ptr(),
            self.tags.as_ptr(),
            key,
            self.hasher.hash(key),
        ) {
            SlotSearch::Found(index) => {
                // A nonzero tag is written only after the entry is initialized.
                // SAFETY: find_slot returns only indices in the 2N physical slots.
                let (_, value) = unsafe { self.entries.get_unchecked_mut(index).assume_init_mut() };
                Some(value)
            }
            SlotSearch::Vacant(_) | SlotSearch::Full => None,
        }
    }

    /// Inserts a key-value pair.
    ///
    /// If the key already exists, its value is replaced and the old value is
    /// returned. If the map is full, the key and value are returned unchanged.
    #[inline]
    pub fn insert(
        &mut self,
        key: [u8; K],
        value: [u8; V],
    ) -> Result<Option<[u8; V]>, InsertError<K, V>> {
        let hash = self.hasher.hash(&key);
        match find_slot::<N, K, V>(self.entries.as_ptr(), self.tags.as_ptr(), &key, hash) {
            SlotSearch::Found(index) => {
                // A nonzero tag is written only after the entry is initialized.
                // SAFETY: find_slot returns only indices in the 2N physical slots.
                let (_, stored_value) =
                    unsafe { self.entries.get_unchecked_mut(index).assume_init_mut() };
                Ok(Some(core::mem::replace(stored_value, value)))
            }
            SlotSearch::Vacant(index) => {
                if self.len == N {
                    return Err(InsertError { key, value });
                }
                // SAFETY: find_slot returns only indices in the 2N physical slots.
                unsafe {
                    self.entries.get_unchecked_mut(index).write((key, value));
                    *self.tags.get_unchecked_mut(index) = fingerprint(hash);
                }
                self.len += 1;
                Ok(None)
            }
            SlotSearch::Full => Err(InsertError { key, value }),
        }
    }
}

impl<'a, const N: usize, const K: usize, const V: usize> FixedMap<'a, N, K, V, FastHasher> {
    /// Creates an empty map using the default fast, non-cryptographic hasher.
    pub fn new(
        entries: &'a mut [EntryStorage<K, V>],
        tags: &'a mut [u8],
    ) -> Result<Self, StorageError> {
        Self::with_hasher(entries, tags, FastHasher)
    }
}

#[cfg(feature = "secure-hash")]
impl<'a, const N: usize, const K: usize, const V: usize> FixedMap<'a, N, K, V, SecureHasher> {
    /// Creates an empty map using SipHash-2-4 and a caller-provided secret key.
    ///
    /// Generate `key` with a cryptographically secure random source. A fixed
    /// or predictable key does not provide collision-attack resistance.
    pub fn new_secure(
        entries: &'a mut [EntryStorage<K, V>],
        tags: &'a mut [u8],
        key: [u8; 16],
    ) -> Result<Self, StorageError> {
        Self::with_hasher(entries, tags, SecureHasher::new(key))
    }
}

#[inline]
fn find_slot<const N: usize, const K: usize, const V: usize>(
    entries: *const EntryStorage<K, V>,
    tags: *const u8,
    key: &[u8; K],
    hash: u64,
) -> SlotSearch {
    if N == 0 {
        return SlotSearch::Full;
    }

    let slots = N.saturating_mul(2);
    let sought = fingerprint(hash);
    let mut index = bucket::<N>(hash);
    let mut remaining = slots;

    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
    {
        // SAFETY: index starts within the 2N slots guaranteed by the constructor.
        let stored_tag = unsafe { *tags.add(index) };
        if stored_tag == sought {
            // SAFETY: the nonzero tag marks initialized storage at this in-range index.
            let (stored_key, _) = unsafe { (&*entries.add(index)).assume_init_ref() };
            if stored_key == key {
                return SlotSearch::Found(index);
            }
        }

        let block_len = core::cmp::min(remaining, slots - index);
        if block_len >= LANES {
            if let Some(result) = scan_group(entries, tags, key, sought, index) {
                return result;
            }
            index += LANES;
            remaining -= LANES;
            if index == slots {
                index = 0;
            }
            if remaining == 0 {
                return SlotSearch::Full;
            }
            return find_slot_after_scalar_probes(
                entries, tags, key, sought, index, remaining, slots,
            );
        }
    }

    for _ in 0..core::cmp::min(slots, SIMD_AFTER_PROBES) {
        // SAFETY: the constructor guarantees 2N valid tags; index wraps within that range.
        let stored_tag = unsafe { *tags.add(index) };
        if stored_tag == 0 {
            return SlotSearch::Vacant(index);
        }
        if stored_tag == sought {
            // A nonzero tag is written only after the entry is initialized.
            // SAFETY: index is in range, and the nonzero tag marks initialized storage.
            let (stored_key, _) = unsafe { (&*entries.add(index)).assume_init_ref() };
            if stored_key == key {
                return SlotSearch::Found(index);
            }
        }
        index += 1;
        if index == slots {
            index = 0;
        }
        remaining -= 1;
    }

    if remaining == 0 {
        SlotSearch::Full
    } else {
        find_slot_after_scalar_probes(entries, tags, key, sought, index, remaining, slots)
    }
}

#[cold]
#[inline(never)]
fn find_slot_after_scalar_probes<const K: usize, const V: usize>(
    entries: *const EntryStorage<K, V>,
    tags: *const u8,
    key: &[u8; K],
    sought: u8,
    mut index: usize,
    mut remaining: usize,
    slots: usize,
) -> SlotSearch {
    while remaining > 0 {
        let block_len = core::cmp::min(remaining, slots - index);
        if block_len >= LANES {
            if let Some(result) = scan_group(entries, tags, key, sought, index) {
                return result;
            }
            index += LANES;
            remaining -= LANES;
        } else {
            // SAFETY: index starts below slots and every probe wraps it back into range.
            let stored_tag = unsafe { *tags.add(index) };
            if stored_tag == 0 {
                return SlotSearch::Vacant(index);
            }
            if stored_tag == sought {
                // A nonzero tag is written only after the entry is initialized.
                // SAFETY: index is in range, and the nonzero tag marks initialized storage.
                let (stored_key, _) = unsafe { (&*entries.add(index)).assume_init_ref() };
                if stored_key == key {
                    return SlotSearch::Found(index);
                }
            }
            index += 1;
            remaining -= 1;
        }

        if index == slots {
            index = 0;
        }
    }

    SlotSearch::Full
}

#[inline]
fn scan_group<const K: usize, const V: usize>(
    entries: *const EntryStorage<K, V>,
    tags: *const u8,
    key: &[u8; K],
    sought: u8,
    index: usize,
) -> Option<SlotSearch> {
    // SAFETY: callers scan only when at least LANES tags remain before the table boundary.
    let group = unsafe { core::slice::from_raw_parts(tags.add(index), LANES) };
    let (matches, vacancies) = tag_masks(group, sought);
    let first_vacancy = if vacancies == 0 {
        LANES
    } else {
        vacancies.trailing_zeros() as usize
    };
    let mut candidates = matches & ((1_u32 << first_vacancy) - 1);

    while candidates != 0 {
        let lane = candidates.trailing_zeros() as usize;
        let candidate = index + lane;
        // SAFETY: candidate is within the scanned group, and its nonzero tag marks initialized storage.
        let (stored_key, _) = unsafe { (&*entries.add(candidate)).assume_init_ref() };
        if stored_key == key {
            return Some(SlotSearch::Found(candidate));
        }
        candidates &= candidates - 1;
    }

    (first_vacancy < LANES).then_some(SlotSearch::Vacant(index + first_vacancy))
}

#[inline]
fn bucket<const N: usize>(hash: u64) -> usize {
    ((u128::from(hash) * N.saturating_mul(2) as u128) >> u64::BITS) as usize
}

#[inline]
fn fingerprint(hash: u64) -> u8 {
    (hash as u8).max(1)
}

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

    macro_rules! with_map {
        ($capacity:literal, $key_size:literal, $value_size:literal, |$map:ident| $body:block) => {{
            let mut entries: [MaybeUninit<([u8; $key_size], [u8; $value_size])>; 2 * $capacity] =
                core::array::from_fn(|_| MaybeUninit::uninit());
            let mut tags = [0_u8; 2 * $capacity];
            let mut $map =
                FixedMap::<$capacity, $key_size, $value_size>::new(&mut entries, &mut tags)
                    .unwrap();
            $body
        }};
    }

    #[test]
    fn inserts_and_retrieves_entries() {
        with_map!(4, 2, 3, |map| {
            assert_eq!(map.capacity(), 4);
            assert_eq!(map.insert([1, 2], [3, 4, 5]), Ok(None));
            assert_eq!(map.get(&[1, 2]), Some(&[3, 4, 5]));
            assert_eq!(map.get(&[9, 9]), None);
            assert_eq!(map.len(), 1);
        });
    }

    #[test]
    fn updates_existing_entries_without_increasing_length() {
        with_map!(2, 1, 2, |map| {
            assert_eq!(map.insert([7], [1, 2]), Ok(None));
            assert_eq!(map.insert([7], [3, 4]), Ok(Some([1, 2])));
            assert_eq!(map.get(&[7]), Some(&[3, 4]));
            assert_eq!(map.len(), 1);
        });
    }

    #[test]
    fn resolves_collisions_with_linear_probing() {
        with_map!(8, 4, 1, |map| {
            let first = [0, 0, 0, 0];
            let first_hash = FastHasher.hash(&first);
            let first_bucket = bucket::<8>(first_hash);
            let second = (1_u32..)
                .map(u32::to_le_bytes)
                .find(|key| {
                    let hash = FastHasher.hash(key);
                    bucket::<8>(hash) == first_bucket
                        && fingerprint(hash) == fingerprint(first_hash)
                })
                .expect("a collision should be found");

            assert_eq!(map.insert(first, [10]), Ok(None));
            assert_eq!(map.insert(second, [20]), Ok(None));
            assert_eq!(map.get(&first), Some(&[10]));
            assert_eq!(map.get(&second), Some(&[20]));
        });
    }

    #[test]
    fn simd_first_group_checks_collisions_and_stops_at_vacancy() {
        with_map!(16, 4, 1, |map| {
            let first = (0_u32..)
                .map(u32::to_le_bytes)
                .find(|key| bucket::<16>(FastHasher.hash(key)) < 16)
                .expect("a key with a non-wrapping SIMD group should be found");
            let first_hash = FastHasher.hash(&first);
            let first_bucket = bucket::<16>(first_hash);
            let first_fingerprint = fingerprint(first_hash);
            let mut keys = [[0_u8; 4]; 3];
            keys[0] = first;
            let mut found = 1;

            for value in 0_u32.. {
                let key = value.to_le_bytes();
                let hash = FastHasher.hash(&key);
                if key != first
                    && bucket::<16>(hash) == first_bucket
                    && fingerprint(hash) == first_fingerprint
                {
                    keys[found] = key;
                    found += 1;
                    if found == keys.len() {
                        break;
                    }
                }
            }

            for (index, key) in keys.iter().enumerate() {
                assert_eq!(map.insert(*key, [index as u8]), Ok(None));
            }
            for (index, key) in keys.iter().enumerate() {
                assert_eq!(map.get(key), Some(&[index as u8]));
            }

            let absent = (0_u32..)
                .map(u32::to_le_bytes)
                .find(|key| {
                    let hash = FastHasher.hash(key);
                    bucket::<16>(hash) == first_bucket
                        && fingerprint(hash) == first_fingerprint
                        && !keys.contains(key)
                })
                .expect("an absent colliding key should be found");
            assert_eq!(map.get(&absent), None);
        });
    }

    #[test]
    fn simd_probe_handles_fingerprint_collisions_and_wraparound() {
        with_map!(32, 4, 1, |map| {
            let first = (0_u32..)
                .map(u32::to_le_bytes)
                .find(|key| bucket::<32>(FastHasher.hash(key)) >= 60)
                .expect("a key near the end of the table should be found");
            let first_hash = FastHasher.hash(&first);
            let first_bucket = bucket::<32>(first_hash);
            let first_fingerprint = fingerprint(first_hash);
            let mut keys = [[0_u8; 4]; 9];
            keys[0] = first;
            let mut found = 1;

            for value in 0_u32.. {
                let key = value.to_le_bytes();
                let hash = FastHasher.hash(&key);
                if key != first
                    && bucket::<32>(hash) == first_bucket
                    && fingerprint(hash) == first_fingerprint
                {
                    keys[found] = key;
                    found += 1;
                    if found == keys.len() {
                        break;
                    }
                }
            }

            for (index, key) in keys.iter().enumerate() {
                assert_eq!(map.insert(*key, [index as u8]), Ok(None));
            }
            for (index, key) in keys.iter().enumerate() {
                assert_eq!(map.get(key), Some(&[index as u8]));
            }

            let absent = (0_u32..)
                .map(u32::to_le_bytes)
                .find(|key| {
                    let hash = FastHasher.hash(key);
                    bucket::<32>(hash) == first_bucket
                        && fingerprint(hash) == first_fingerprint
                        && !keys.contains(key)
                })
                .expect("an absent colliding key should be found");
            assert_eq!(map.get(&absent), None);
        });
    }

    #[test]
    fn spreads_sequential_integer_keys_across_buckets() {
        let mut buckets = [false; 2048];
        for value in 0_u64..1024 {
            let index = bucket::<1024>(FastHasher.hash(&value.to_le_bytes()));
            buckets[index] = true;
        }

        assert!(buckets.into_iter().filter(|used| *used).count() > 600);
    }

    #[test]
    fn full_map_returns_uninserted_pair_and_allows_updates() {
        with_map!(1, 1, 1, |map| {
            assert_eq!(map.insert([1], [10]), Ok(None));
            assert_eq!(
                map.insert([2], [20]),
                Err(InsertError {
                    key: [2],
                    value: [20]
                })
            );
            assert_eq!(map.insert([1], [11]), Ok(Some([10])));
            assert!(map.is_full());
            assert_eq!(map.len(), 1);
        });
    }

    #[test]
    fn zero_capacity_map_is_empty_and_rejects_inserts() {
        with_map!(0, 1, 1, |map| {
            assert!(map.is_empty());
            assert!(map.is_full());
            assert_eq!(map.get(&[1]), None);
            assert_eq!(
                map.insert([1], [2]),
                Err(InsertError {
                    key: [1],
                    value: [2]
                })
            );
        });
    }

    #[test]
    fn mutable_lookup_changes_the_stored_value() {
        with_map!(1, 1, 2, |map| {
            map.insert([5], [6, 7]).unwrap();
            map.get_mut(&[5]).unwrap()[1] = 9;
            assert_eq!(map.get(&[5]), Some(&[6, 9]));
        });
    }

    #[test]
    fn rejects_insufficient_backing_storage() {
        let mut entries = [MaybeUninit::<([u8; 1], [u8; 1])>::uninit(); 1];
        let mut tags = [];
        assert_eq!(
            FixedMap::<2, 1, 1>::new(&mut entries, &mut tags).err(),
            Some(StorageError::NotEnoughEntries {
                required: 4,
                available: 1
            })
        );

        let mut entries = [MaybeUninit::<([u8; 1], [u8; 1])>::uninit(); 4];
        let mut tags = [0];
        assert_eq!(
            FixedMap::<2, 1, 1>::new(&mut entries, &mut tags).err(),
            Some(StorageError::NotEnoughTags {
                required: 4,
                available: 1
            })
        );
    }

    #[cfg(feature = "secure-hash")]
    #[test]
    fn secure_hasher_map_inserts_and_retrieves_entries() {
        let hasher_a = SecureHasher::new([42; 16]);
        let hasher_b = SecureHasher::new([24; 16]);
        assert_ne!(hasher_a.hash(b"key1"), hasher_b.hash(b"key1"));

        let mut entries = [MaybeUninit::<([u8; 4], [u8; 2])>::uninit(); 32];
        let mut tags = [0_u8; 32];
        let mut map =
            FixedMap::<16, 4, 2, SecureHasher>::new_secure(&mut entries, &mut tags, [42; 16])
                .unwrap();

        assert_eq!(map.insert(*b"key1", *b"v1"), Ok(None));
        assert_eq!(map.insert(*b"key1", *b"v2"), Ok(Some(*b"v1")));
        assert_eq!(map.get(b"key1"), Some(b"v2"));
        assert_eq!(map.get(b"nope"), None);
    }

    #[test]
    fn large_capacity_is_not_embedded_in_the_map_value() {
        let mut entries: [EntryStorage<8, 8>; 0] = [];
        let mut tags = [];
        assert_eq!(
            FixedMap::<2_000_000_000, 8, 8>::new(&mut entries, &mut tags).err(),
            Some(StorageError::NotEnoughEntries {
                required: 4_000_000_000,
                available: 0
            })
        );
    }

    #[test]
    fn rejects_entry_capacity_that_overflows_physical_slots() {
        let mut entries: [EntryStorage<1, 1>; 0] = [];
        let mut tags: [u8; 0] = [];
        assert_eq!(
            FixedMap::<{ usize::MAX }, 1, 1>::new(&mut entries, &mut tags).err(),
            Some(StorageError::CapacityOverflow)
        );
    }
}