#[cfg(feature = "secure-hash")]
use super::hash::SecureHasher;
use super::hash::{FastHasher, KeyHasher};
use super::simd::{LANES, tag_masks};
use core::mem::MaybeUninit;
pub type EntryStorage<const K: usize, const V: usize> = MaybeUninit<([u8; K], [u8; V])>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StorageError {
CapacityOverflow,
NotEnoughEntries { required: usize, available: usize },
NotEnoughTags { required: usize, available: usize },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InsertError<const K: usize, const V: usize> {
pub key: [u8; K],
pub value: [u8; V],
}
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> {
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,
})
}
pub const fn capacity(&self) -> usize {
N
}
pub const fn len(&self) -> usize {
self.len
}
pub const fn is_empty(&self) -> bool {
self.len == 0
}
pub const fn is_full(&self) -> bool {
self.len == N
}
#[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) => {
let (_, value) = unsafe { self.entries.get_unchecked(index).assume_init_ref() };
Some(value)
}
SlotSearch::Vacant(_) | SlotSearch::Full => None,
}
}
#[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) => {
let (_, value) = unsafe { self.entries.get_unchecked_mut(index).assume_init_mut() };
Some(value)
}
SlotSearch::Vacant(_) | SlotSearch::Full => None,
}
}
#[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) => {
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 });
}
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> {
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> {
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"))]
{
let stored_tag = unsafe { *tags.add(index) };
if stored_tag == sought {
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) {
let stored_tag = unsafe { *tags.add(index) };
if stored_tag == 0 {
return SlotSearch::Vacant(index);
}
if stored_tag == sought {
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 {
let stored_tag = unsafe { *tags.add(index) };
if stored_tag == 0 {
return SlotSearch::Vacant(index);
}
if stored_tag == sought {
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> {
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;
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)
);
}
}