fixed-hashmap 0.1.0

A fixed-capacity, allocation-free hashmap for fixed-size byte keys and values
Documentation
  • Coverage
  • 76.47%
    13 out of 17 items documented1 out of 1 items with examples
  • Size
  • Source code size: 83.7 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 362.7 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 1s Average build duration of successful builds.
  • all releases: 1s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • tusmah/fixed_hashmap
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • tusmah

fixed-hashmap

A no_std Rust fixed-capacity hashmap for fixed-size byte keys and values. Storage is supplied by the caller, so the map itself does not allocate and its value remains small even for very large capacities.

This is an initial implementation and benchmark baseline, not a claim that it is faster than every hashmap. Results depend on key distributions, occupancy, and hardware.

Examples

The examples/ directory contains runnable programs for these patterns. Run them with:

cargo run --example basic
cargo run --example heap_backed
cargo run --example full_capacity
cargo run --example custom_hasher

Stack-backed map

use core::mem::MaybeUninit;
use fixed_hashmap::{EntryStorage, FixedMap};

const CAPACITY: usize = 4;
let mut entries: [EntryStorage<4, 8>; CAPACITY * 2] =
    core::array::from_fn(|_| MaybeUninit::uninit());
let mut tags = [0_u8; CAPACITY * 2];
let mut map = FixedMap::<CAPACITY, 4, 8>::new(&mut entries, &mut tags)
    .expect("backing storage has twice the entry capacity");
map.insert(*b"key1", *b"value001")
    .expect("the map has free capacity");
assert_eq!(map.get(b"key1"), Some(b"value001"));

FixedMap<N, K, V> treats N as the maximum number of entries and requires at least 2 * N entry slots and tag bytes. This keeps physical occupancy at or below 50%. Backing buffers can be placed wherever the application manages memory. It stores [u8; K] keys and [u8; V] values using open addressing with linear probing. Replacing an existing key returns its old value; inserting a new key at the maximum returns the uninserted key and value. Deletion is not supported in this initial version.

The benchmark targets 1,000,000 entries at 50% FixedMap load. With 8-byte keys and values, that configuration uses 2,000,000 slots and 34 MB (32.4 MiB) for entry storage and tags, supplied by the caller.

Heap-backed storage

For larger capacities, allocate the caller-owned buffers on the heap. The map itself still does not allocate or resize:

use core::mem::MaybeUninit;
use fixed_hashmap::{EntryStorage, FixedMap};

const CAPACITY: usize = 1_024;
let mut entries: Vec<EntryStorage<8, 8>> =
    vec![MaybeUninit::uninit(); CAPACITY * 2];
let mut tags = vec![0_u8; CAPACITY * 2];
let mut map = FixedMap::<CAPACITY, 8, 8>::new(&mut entries, &mut tags)
    .expect("backing storage has twice the entry capacity");

for index in 0..CAPACITY {
    let key = (index as u64).to_le_bytes();
    map.insert(key, key).expect("capacity is available");
}
assert_eq!(map.len(), CAPACITY);

Updating and full-capacity behavior

Updating an existing key still works when the map is full. A new key is returned in InsertError without being stored:

use core::mem::MaybeUninit;
use fixed_hashmap::{EntryStorage, FixedMap};

let mut entries: [EntryStorage<4, 1>; 2] =
    core::array::from_fn(|_| MaybeUninit::uninit());
let mut tags = [0_u8; 2];
let mut map = FixedMap::<1, 4, 1>::new(&mut entries, &mut tags)
    .expect("backing storage has twice the entry capacity");

map.insert(*b"key1", [1]).expect("capacity is available");
assert!(map.is_full());
assert_eq!(map.insert(*b"key1", [2]), Ok(Some([1])));

let rejected = map.insert(*b"key2", [3]).unwrap_err();
assert_eq!(rejected.key, *b"key2");
assert_eq!(rejected.value, [3]);

Custom hasher

Implement KeyHasher<K> when the application needs a different, non-cryptographic hashing policy. This example namespaces four-byte keys before applying the built-in fast hash:

use fixed_hashmap::{FastHasher, KeyHasher};

struct RecordsHasher;

impl KeyHasher<4> for RecordsHasher {
    fn hash(&self, key: &[u8; 4]) -> u64 {
        let mut namespaced_key = [0; 12];
        namespaced_key[..8].copy_from_slice(b"records:");
        namespaced_key[8..].copy_from_slice(key);
        FastHasher.hash(&namespaced_key)
    }
}

Pass RecordsHasher to FixedMap::<N, 4, V, RecordsHasher>::with_hasher. Custom hashers do not automatically provide collision-attack resistance.

The implementation uses a fast, non-cryptographic hash. It is not suitable where attackers can choose keys to cause collisions.

Hashing modes

The default hasher is fast and non-cryptographic. For maps exposed to attacker-controlled keys, enable the optional secure-hash Cargo feature and select SecureHasher explicitly:

fixed-hashmap = { version = "0.1", features = ["secure-hash"] }

The secure constructor takes a secret key from the application's cryptographically secure RNG:

use fixed_hashmap::{EntryStorage, FixedMap, SecureHasher, StorageError};

fn create_secure_map<'a, const N: usize, const K: usize, const V: usize>(
    entries: &'a mut [EntryStorage<K, V>],
    tags: &'a mut [u8],
    key_from_csprng: [u8; 16],
) -> Result<FixedMap<'a, N, K, V, SecureHasher>, StorageError> {
    FixedMap::new_secure(entries, tags, key_from_csprng)
}

Secure mode uses keyed SipHash-2-4. The crate does not provide entropy because it is no_std; the application must supply a fresh, unpredictable key. Do not hardcode a key or reuse a predictable value. The hasher choice is a type parameter, so the fast default does not pay a runtime mode-switch cost. The optional siphasher dependency is enabled only with secure-hash.

Portability

The library works on Rust targets without SIMD. Tag scans use x86-64 SSE2 or AArch64 Advanced SIMD where available; all other targets use the scalar fallback. These instruction sets are part of the respective architecture baselines, so the optimized paths do not require extra CPU feature flags.

Benchmark results

Results from a release-mode run with SIMD enabled where supported, at 1,000,000 entries and 50% FixedMap load (2,000,000 slots; 8-byte keys and values). Values are medians from seven samples:

Operation FixedMap std::HashMap FxHashMap
Construction 42.88 us 1,307.34 us 1,309.92 us
Get hit 54.41 ns 252.99 ns 47.47 ns
Get miss 9.69 ns 40.47 ns 5.64 ns
Get_mut hit 56.46 ns 248.41 ns 50.05 ns
Get_mut miss 11.04 ns 38.57 ns 5.77 ns
Update existing via insert 60.56 ns 249.50 ns 55.57 ns
New inserts (empty to max) 25.31 ns 82.85 ns 43.56 ns
len 0.60 ns 0.59 ns 0.60 ns
capacity 0.57 ns 0.56 ns 0.56 ns
is_empty 0.56 ns 0.56 ns 0.56 ns
is_full / len == capacity 0.56 ns 0.56 ns 0.56 ns
Insert rejection at max 20.10 ns Not comparable Not comparable

Lookup/update results use 500,000 operations per sample. New-insert timing fills each map from empty to 1,000,000 entries; the standard maps reserve storage before timing. Full-map rejection is measured separately over 10 attempts per sample. Both std::HashMap and FxHashMap reported capacity 1,835,008 because the standard map rounds its allocation to a different size. FixedMap::capacity() reports the logical entry maximum (1,000,000), while its physical slot count is 2,000,000. Thus the is_full comparison is at different logical and physical capacities for the standard maps. FxHashMap is Rust's standard HashMap using the Fx hasher, so this comparison isolates the effect of using a faster, non-cryptographic hasher while retaining the standard table implementation.

Construction is not an apples-to-apples allocation comparison: FixedMap's caller-owned buffers are already allocated, and its constructor only clears the tags; HashMap::with_capacity allocates its backing storage. The full-map insert has no direct HashMap equivalent because the standard map grows instead of rejecting the insertion. Metadata timings are near the benchmark's measurement floor. FxHash is non-cryptographic and is not appropriate for untrusted keys. These are local microbenchmark results, not a claim that FixedMap is faster for every workload or than every hashmap implementation.

Cuckoo prototype

The separate cuckoo benchmark uses two tables with four slots per bucket and two candidate buckets per key. It uses the same FastHasher as FixedMap, while FxHashMap uses Fx hashing. The allocating prototype is benchmark-only and is not part of the no_std library.

Operation FixedMap CuckooMap FxHashMap
Get hit 50.42 ns 51.97 ns 38.37 ns
Get miss 10.36 ns 12.62 ns 5.36 ns
Get_mut hit 45.72 ns 52.39 ns 40.84 ns
Get_mut miss 10.26 ns 13.01 ns 5.04 ns
Update existing 51.06 ns 54.99 ns 42.06 ns
New inserts (empty to max) 23.83 ns 31.54 ns 39.79 ns

In this run cuckoo was slower than FixedMap on every listed operation, while FxHashMap remained faster on lookups and updates. FixedMap's insertion timing varied between the two benchmark runs, so compare insertion values cautiously. These results are preliminary; the benchmark reports wide timing ranges on this host.

SIMD impact

Tag scans check the home slot for a direct hit, then compare the initial 16-tag group with SIMD where the target architecture provides it. This reduced the operation benchmark's get-miss median from 27.94 ns to 9.69 ns and get_mut-miss from 28.13 ns to 11.04 ns. Hit and update timings remained close to the previous snapshot. Other targets retain the scalar fallback.

Test and benchmark

cargo test
cargo bench --bench operations
cargo bench --bench cuckoo

The benchmark compares construction, new inserts, updates, hit/miss reads, mutable hit/miss reads, and metadata accessors with std::collections::HashMap and fxhash::FxHashMap at the 1-million-entry target. The separate cuckoo benchmark compares lookup and insertion operations at 50% occupancy. Both use over one million precomputed queries and report medians and ranges from repeated runs. Caller-managed backing-buffer allocation is excluded from FixedMap construction time; both hash map allocations are included. Run the benchmark on an otherwise idle machine before drawing conclusions. The standard library and fxhash are used only by the benchmark; the library itself has no std dependency. The optional siphasher dependency also supports no_std and is compiled only when secure-hash is enabled.