1#[cfg(feature = "secure-hash")]
4use super::hash::SecureHasher;
5use super::hash::{FastHasher, KeyHasher};
6use super::simd::{LANES, tag_masks};
7use core::mem::MaybeUninit;
8
9pub type EntryStorage<const K: usize, const V: usize> = MaybeUninit<([u8; K], [u8; V])>;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum StorageError {
15 CapacityOverflow,
17 NotEnoughEntries { required: usize, available: usize },
19 NotEnoughTags { required: usize, available: usize },
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub struct InsertError<const K: usize, const V: usize> {
26 pub key: [u8; K],
28 pub value: [u8; V],
30}
31
32pub struct FixedMap<'a, const N: usize, const K: usize, const V: usize, H = FastHasher> {
38 entries: &'a mut [EntryStorage<K, V>],
39 tags: &'a mut [u8],
40 len: usize,
41 hasher: H,
42}
43
44enum SlotSearch {
45 Found(usize),
46 Vacant(usize),
47 Full,
48}
49
50const SIMD_AFTER_PROBES: usize = 8;
51
52impl<'a, const N: usize, const K: usize, const V: usize, H: KeyHasher<K>> FixedMap<'a, N, K, V, H> {
53 pub fn with_hasher(
58 entries: &'a mut [EntryStorage<K, V>],
59 tags: &'a mut [u8],
60 hasher: H,
61 ) -> Result<Self, StorageError> {
62 let slots = N.checked_mul(2).ok_or(StorageError::CapacityOverflow)?;
63
64 if entries.len() < slots {
65 return Err(StorageError::NotEnoughEntries {
66 required: slots,
67 available: entries.len(),
68 });
69 }
70
71 if tags.len() < slots {
72 return Err(StorageError::NotEnoughTags {
73 required: slots,
74 available: tags.len(),
75 });
76 }
77
78 let entries = &mut entries[..slots];
79 let tags = &mut tags[..slots];
80 tags.fill(0);
81 Ok(Self {
82 entries,
83 tags,
84 len: 0,
85 hasher,
86 })
87 }
88
89 pub const fn capacity(&self) -> usize {
91 N
92 }
93
94 pub const fn len(&self) -> usize {
96 self.len
97 }
98
99 pub const fn is_empty(&self) -> bool {
101 self.len == 0
102 }
103
104 pub const fn is_full(&self) -> bool {
106 self.len == N
107 }
108
109 #[inline]
111 pub fn get(&self, key: &[u8; K]) -> Option<&[u8; V]> {
112 match find_slot::<N, K, V>(
113 self.entries.as_ptr(),
114 self.tags.as_ptr(),
115 key,
116 self.hasher.hash(key),
117 ) {
118 SlotSearch::Found(index) => {
119 let (_, value) = unsafe { self.entries.get_unchecked(index).assume_init_ref() };
122 Some(value)
123 }
124 SlotSearch::Vacant(_) | SlotSearch::Full => None,
125 }
126 }
127
128 #[inline]
130 pub fn get_mut(&mut self, key: &[u8; K]) -> Option<&mut [u8; V]> {
131 match find_slot::<N, K, V>(
132 self.entries.as_ptr(),
133 self.tags.as_ptr(),
134 key,
135 self.hasher.hash(key),
136 ) {
137 SlotSearch::Found(index) => {
138 let (_, value) = unsafe { self.entries.get_unchecked_mut(index).assume_init_mut() };
141 Some(value)
142 }
143 SlotSearch::Vacant(_) | SlotSearch::Full => None,
144 }
145 }
146
147 #[inline]
152 pub fn insert(
153 &mut self,
154 key: [u8; K],
155 value: [u8; V],
156 ) -> Result<Option<[u8; V]>, InsertError<K, V>> {
157 let hash = self.hasher.hash(&key);
158 match find_slot::<N, K, V>(self.entries.as_ptr(), self.tags.as_ptr(), &key, hash) {
159 SlotSearch::Found(index) => {
160 let (_, stored_value) =
163 unsafe { self.entries.get_unchecked_mut(index).assume_init_mut() };
164 Ok(Some(core::mem::replace(stored_value, value)))
165 }
166 SlotSearch::Vacant(index) => {
167 if self.len == N {
168 return Err(InsertError { key, value });
169 }
170 unsafe {
172 self.entries.get_unchecked_mut(index).write((key, value));
173 *self.tags.get_unchecked_mut(index) = fingerprint(hash);
174 }
175 self.len += 1;
176 Ok(None)
177 }
178 SlotSearch::Full => Err(InsertError { key, value }),
179 }
180 }
181}
182
183impl<'a, const N: usize, const K: usize, const V: usize> FixedMap<'a, N, K, V, FastHasher> {
184 pub fn new(
186 entries: &'a mut [EntryStorage<K, V>],
187 tags: &'a mut [u8],
188 ) -> Result<Self, StorageError> {
189 Self::with_hasher(entries, tags, FastHasher)
190 }
191}
192
193#[cfg(feature = "secure-hash")]
194impl<'a, const N: usize, const K: usize, const V: usize> FixedMap<'a, N, K, V, SecureHasher> {
195 pub fn new_secure(
200 entries: &'a mut [EntryStorage<K, V>],
201 tags: &'a mut [u8],
202 key: [u8; 16],
203 ) -> Result<Self, StorageError> {
204 Self::with_hasher(entries, tags, SecureHasher::new(key))
205 }
206}
207
208#[inline]
209fn find_slot<const N: usize, const K: usize, const V: usize>(
210 entries: *const EntryStorage<K, V>,
211 tags: *const u8,
212 key: &[u8; K],
213 hash: u64,
214) -> SlotSearch {
215 if N == 0 {
216 return SlotSearch::Full;
217 }
218
219 let slots = N.saturating_mul(2);
220 let sought = fingerprint(hash);
221 let mut index = bucket::<N>(hash);
222 let mut remaining = slots;
223
224 #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
225 {
226 let stored_tag = unsafe { *tags.add(index) };
228 if stored_tag == sought {
229 let (stored_key, _) = unsafe { (&*entries.add(index)).assume_init_ref() };
231 if stored_key == key {
232 return SlotSearch::Found(index);
233 }
234 }
235
236 let block_len = core::cmp::min(remaining, slots - index);
237 if block_len >= LANES {
238 if let Some(result) = scan_group(entries, tags, key, sought, index) {
239 return result;
240 }
241 index += LANES;
242 remaining -= LANES;
243 if index == slots {
244 index = 0;
245 }
246 if remaining == 0 {
247 return SlotSearch::Full;
248 }
249 return find_slot_after_scalar_probes(
250 entries, tags, key, sought, index, remaining, slots,
251 );
252 }
253 }
254
255 for _ in 0..core::cmp::min(slots, SIMD_AFTER_PROBES) {
256 let stored_tag = unsafe { *tags.add(index) };
258 if stored_tag == 0 {
259 return SlotSearch::Vacant(index);
260 }
261 if stored_tag == sought {
262 let (stored_key, _) = unsafe { (&*entries.add(index)).assume_init_ref() };
265 if stored_key == key {
266 return SlotSearch::Found(index);
267 }
268 }
269 index += 1;
270 if index == slots {
271 index = 0;
272 }
273 remaining -= 1;
274 }
275
276 if remaining == 0 {
277 SlotSearch::Full
278 } else {
279 find_slot_after_scalar_probes(entries, tags, key, sought, index, remaining, slots)
280 }
281}
282
283#[cold]
284#[inline(never)]
285fn find_slot_after_scalar_probes<const K: usize, const V: usize>(
286 entries: *const EntryStorage<K, V>,
287 tags: *const u8,
288 key: &[u8; K],
289 sought: u8,
290 mut index: usize,
291 mut remaining: usize,
292 slots: usize,
293) -> SlotSearch {
294 while remaining > 0 {
295 let block_len = core::cmp::min(remaining, slots - index);
296 if block_len >= LANES {
297 if let Some(result) = scan_group(entries, tags, key, sought, index) {
298 return result;
299 }
300 index += LANES;
301 remaining -= LANES;
302 } else {
303 let stored_tag = unsafe { *tags.add(index) };
305 if stored_tag == 0 {
306 return SlotSearch::Vacant(index);
307 }
308 if stored_tag == sought {
309 let (stored_key, _) = unsafe { (&*entries.add(index)).assume_init_ref() };
312 if stored_key == key {
313 return SlotSearch::Found(index);
314 }
315 }
316 index += 1;
317 remaining -= 1;
318 }
319
320 if index == slots {
321 index = 0;
322 }
323 }
324
325 SlotSearch::Full
326}
327
328#[inline]
329fn scan_group<const K: usize, const V: usize>(
330 entries: *const EntryStorage<K, V>,
331 tags: *const u8,
332 key: &[u8; K],
333 sought: u8,
334 index: usize,
335) -> Option<SlotSearch> {
336 let group = unsafe { core::slice::from_raw_parts(tags.add(index), LANES) };
338 let (matches, vacancies) = tag_masks(group, sought);
339 let first_vacancy = if vacancies == 0 {
340 LANES
341 } else {
342 vacancies.trailing_zeros() as usize
343 };
344 let mut candidates = matches & ((1_u32 << first_vacancy) - 1);
345
346 while candidates != 0 {
347 let lane = candidates.trailing_zeros() as usize;
348 let candidate = index + lane;
349 let (stored_key, _) = unsafe { (&*entries.add(candidate)).assume_init_ref() };
351 if stored_key == key {
352 return Some(SlotSearch::Found(candidate));
353 }
354 candidates &= candidates - 1;
355 }
356
357 (first_vacancy < LANES).then_some(SlotSearch::Vacant(index + first_vacancy))
358}
359
360#[inline]
361fn bucket<const N: usize>(hash: u64) -> usize {
362 ((u128::from(hash) * N.saturating_mul(2) as u128) >> u64::BITS) as usize
363}
364
365#[inline]
366fn fingerprint(hash: u64) -> u8 {
367 (hash as u8).max(1)
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 macro_rules! with_map {
375 ($capacity:literal, $key_size:literal, $value_size:literal, |$map:ident| $body:block) => {{
376 let mut entries: [MaybeUninit<([u8; $key_size], [u8; $value_size])>; 2 * $capacity] =
377 core::array::from_fn(|_| MaybeUninit::uninit());
378 let mut tags = [0_u8; 2 * $capacity];
379 let mut $map =
380 FixedMap::<$capacity, $key_size, $value_size>::new(&mut entries, &mut tags)
381 .unwrap();
382 $body
383 }};
384 }
385
386 #[test]
387 fn inserts_and_retrieves_entries() {
388 with_map!(4, 2, 3, |map| {
389 assert_eq!(map.capacity(), 4);
390 assert_eq!(map.insert([1, 2], [3, 4, 5]), Ok(None));
391 assert_eq!(map.get(&[1, 2]), Some(&[3, 4, 5]));
392 assert_eq!(map.get(&[9, 9]), None);
393 assert_eq!(map.len(), 1);
394 });
395 }
396
397 #[test]
398 fn updates_existing_entries_without_increasing_length() {
399 with_map!(2, 1, 2, |map| {
400 assert_eq!(map.insert([7], [1, 2]), Ok(None));
401 assert_eq!(map.insert([7], [3, 4]), Ok(Some([1, 2])));
402 assert_eq!(map.get(&[7]), Some(&[3, 4]));
403 assert_eq!(map.len(), 1);
404 });
405 }
406
407 #[test]
408 fn resolves_collisions_with_linear_probing() {
409 with_map!(8, 4, 1, |map| {
410 let first = [0, 0, 0, 0];
411 let first_hash = FastHasher.hash(&first);
412 let first_bucket = bucket::<8>(first_hash);
413 let second = (1_u32..)
414 .map(u32::to_le_bytes)
415 .find(|key| {
416 let hash = FastHasher.hash(key);
417 bucket::<8>(hash) == first_bucket
418 && fingerprint(hash) == fingerprint(first_hash)
419 })
420 .expect("a collision should be found");
421
422 assert_eq!(map.insert(first, [10]), Ok(None));
423 assert_eq!(map.insert(second, [20]), Ok(None));
424 assert_eq!(map.get(&first), Some(&[10]));
425 assert_eq!(map.get(&second), Some(&[20]));
426 });
427 }
428
429 #[test]
430 fn simd_first_group_checks_collisions_and_stops_at_vacancy() {
431 with_map!(16, 4, 1, |map| {
432 let first = (0_u32..)
433 .map(u32::to_le_bytes)
434 .find(|key| bucket::<16>(FastHasher.hash(key)) < 16)
435 .expect("a key with a non-wrapping SIMD group should be found");
436 let first_hash = FastHasher.hash(&first);
437 let first_bucket = bucket::<16>(first_hash);
438 let first_fingerprint = fingerprint(first_hash);
439 let mut keys = [[0_u8; 4]; 3];
440 keys[0] = first;
441 let mut found = 1;
442
443 for value in 0_u32.. {
444 let key = value.to_le_bytes();
445 let hash = FastHasher.hash(&key);
446 if key != first
447 && bucket::<16>(hash) == first_bucket
448 && fingerprint(hash) == first_fingerprint
449 {
450 keys[found] = key;
451 found += 1;
452 if found == keys.len() {
453 break;
454 }
455 }
456 }
457
458 for (index, key) in keys.iter().enumerate() {
459 assert_eq!(map.insert(*key, [index as u8]), Ok(None));
460 }
461 for (index, key) in keys.iter().enumerate() {
462 assert_eq!(map.get(key), Some(&[index as u8]));
463 }
464
465 let absent = (0_u32..)
466 .map(u32::to_le_bytes)
467 .find(|key| {
468 let hash = FastHasher.hash(key);
469 bucket::<16>(hash) == first_bucket
470 && fingerprint(hash) == first_fingerprint
471 && !keys.contains(key)
472 })
473 .expect("an absent colliding key should be found");
474 assert_eq!(map.get(&absent), None);
475 });
476 }
477
478 #[test]
479 fn simd_probe_handles_fingerprint_collisions_and_wraparound() {
480 with_map!(32, 4, 1, |map| {
481 let first = (0_u32..)
482 .map(u32::to_le_bytes)
483 .find(|key| bucket::<32>(FastHasher.hash(key)) >= 60)
484 .expect("a key near the end of the table should be found");
485 let first_hash = FastHasher.hash(&first);
486 let first_bucket = bucket::<32>(first_hash);
487 let first_fingerprint = fingerprint(first_hash);
488 let mut keys = [[0_u8; 4]; 9];
489 keys[0] = first;
490 let mut found = 1;
491
492 for value in 0_u32.. {
493 let key = value.to_le_bytes();
494 let hash = FastHasher.hash(&key);
495 if key != first
496 && bucket::<32>(hash) == first_bucket
497 && fingerprint(hash) == first_fingerprint
498 {
499 keys[found] = key;
500 found += 1;
501 if found == keys.len() {
502 break;
503 }
504 }
505 }
506
507 for (index, key) in keys.iter().enumerate() {
508 assert_eq!(map.insert(*key, [index as u8]), Ok(None));
509 }
510 for (index, key) in keys.iter().enumerate() {
511 assert_eq!(map.get(key), Some(&[index as u8]));
512 }
513
514 let absent = (0_u32..)
515 .map(u32::to_le_bytes)
516 .find(|key| {
517 let hash = FastHasher.hash(key);
518 bucket::<32>(hash) == first_bucket
519 && fingerprint(hash) == first_fingerprint
520 && !keys.contains(key)
521 })
522 .expect("an absent colliding key should be found");
523 assert_eq!(map.get(&absent), None);
524 });
525 }
526
527 #[test]
528 fn spreads_sequential_integer_keys_across_buckets() {
529 let mut buckets = [false; 2048];
530 for value in 0_u64..1024 {
531 let index = bucket::<1024>(FastHasher.hash(&value.to_le_bytes()));
532 buckets[index] = true;
533 }
534
535 assert!(buckets.into_iter().filter(|used| *used).count() > 600);
536 }
537
538 #[test]
539 fn full_map_returns_uninserted_pair_and_allows_updates() {
540 with_map!(1, 1, 1, |map| {
541 assert_eq!(map.insert([1], [10]), Ok(None));
542 assert_eq!(
543 map.insert([2], [20]),
544 Err(InsertError {
545 key: [2],
546 value: [20]
547 })
548 );
549 assert_eq!(map.insert([1], [11]), Ok(Some([10])));
550 assert!(map.is_full());
551 assert_eq!(map.len(), 1);
552 });
553 }
554
555 #[test]
556 fn zero_capacity_map_is_empty_and_rejects_inserts() {
557 with_map!(0, 1, 1, |map| {
558 assert!(map.is_empty());
559 assert!(map.is_full());
560 assert_eq!(map.get(&[1]), None);
561 assert_eq!(
562 map.insert([1], [2]),
563 Err(InsertError {
564 key: [1],
565 value: [2]
566 })
567 );
568 });
569 }
570
571 #[test]
572 fn mutable_lookup_changes_the_stored_value() {
573 with_map!(1, 1, 2, |map| {
574 map.insert([5], [6, 7]).unwrap();
575 map.get_mut(&[5]).unwrap()[1] = 9;
576 assert_eq!(map.get(&[5]), Some(&[6, 9]));
577 });
578 }
579
580 #[test]
581 fn rejects_insufficient_backing_storage() {
582 let mut entries = [MaybeUninit::<([u8; 1], [u8; 1])>::uninit(); 1];
583 let mut tags = [];
584 assert_eq!(
585 FixedMap::<2, 1, 1>::new(&mut entries, &mut tags).err(),
586 Some(StorageError::NotEnoughEntries {
587 required: 4,
588 available: 1
589 })
590 );
591
592 let mut entries = [MaybeUninit::<([u8; 1], [u8; 1])>::uninit(); 4];
593 let mut tags = [0];
594 assert_eq!(
595 FixedMap::<2, 1, 1>::new(&mut entries, &mut tags).err(),
596 Some(StorageError::NotEnoughTags {
597 required: 4,
598 available: 1
599 })
600 );
601 }
602
603 #[cfg(feature = "secure-hash")]
604 #[test]
605 fn secure_hasher_map_inserts_and_retrieves_entries() {
606 let hasher_a = SecureHasher::new([42; 16]);
607 let hasher_b = SecureHasher::new([24; 16]);
608 assert_ne!(hasher_a.hash(b"key1"), hasher_b.hash(b"key1"));
609
610 let mut entries = [MaybeUninit::<([u8; 4], [u8; 2])>::uninit(); 32];
611 let mut tags = [0_u8; 32];
612 let mut map =
613 FixedMap::<16, 4, 2, SecureHasher>::new_secure(&mut entries, &mut tags, [42; 16])
614 .unwrap();
615
616 assert_eq!(map.insert(*b"key1", *b"v1"), Ok(None));
617 assert_eq!(map.insert(*b"key1", *b"v2"), Ok(Some(*b"v1")));
618 assert_eq!(map.get(b"key1"), Some(b"v2"));
619 assert_eq!(map.get(b"nope"), None);
620 }
621
622 #[test]
623 fn large_capacity_is_not_embedded_in_the_map_value() {
624 let mut entries: [EntryStorage<8, 8>; 0] = [];
625 let mut tags = [];
626 assert_eq!(
627 FixedMap::<2_000_000_000, 8, 8>::new(&mut entries, &mut tags).err(),
628 Some(StorageError::NotEnoughEntries {
629 required: 4_000_000_000,
630 available: 0
631 })
632 );
633 }
634
635 #[test]
636 fn rejects_entry_capacity_that_overflows_physical_slots() {
637 let mut entries: [EntryStorage<1, 1>; 0] = [];
638 let mut tags: [u8; 0] = [];
639 assert_eq!(
640 FixedMap::<{ usize::MAX }, 1, 1>::new(&mut entries, &mut tags).err(),
641 Some(StorageError::CapacityOverflow)
642 );
643 }
644}