fixed-map
This crate provides a Map and Set container that can make use of a
pre-calculated backing storage. This enables the Rust compiler to heavily
optimize operations over them and avoid allocating.
See documentation for information on how to use this crate.
Usage
Add fixed-map to your Cargo.toml:
[dependencies]
fixed-map = "0.9.6"
Anything used as a key in either a Map or a Set needs to implement
the Key trait. This should be derived:
use fixed_map::{Key, Map};
#[derive(Clone, Copy, Key)]
enum MyKey {
North,
South,
East,
West,
}
After this you can use one of our containers:
use fixed_map::{Map, Set};
let mut map = Map::new();
map.insert(MyKey::North, 200);
map.insert(MyKey::South, 100);
assert_eq!(map.get(MyKey::North), Some(&200));
assert_eq!(map.get(MyKey::East), None);
let mut set = Set::new();
set.insert(MyKey::North);
set.insert(MyKey::South);
assert!(set.contains(MyKey::South));
assert!(!set.contains(MyKey::East));
Features
The following features are available:
std - Disabling this feature causes this crate to be no-std. This means
that dynamic types cannot be used in keys, like ones enabled by the map
feature (default).
hashbrown - Causes Storage to be implemented by dynamic types such
as &'static str or u32. These are backed by a hashbrown (default).
entry - Enables an entry API similar to that found on HashMap.
serde - Causes Map and Set to implement Serialize and
Deserialize if it's implemented by the key and value.
musli02 - Causes Map and Set to implement Encode and Decode
from musli 0.2 if it's implemented by the key and value. A map is
encoded as a map and a set as a sequence, including #[key(bitset)] sets.
musli-zerocopy01 - Causes Set to implement ZeroCopy from
musli-zerocopy 0.1 when the key uses #[key(bitset)], with the same
layout as its raw value.
The musli02 and musli-zerocopy01 features need Rust 1.85, the minimum
supported version of those crates.
Specialized storage through the Key trait
The Key derive is provided to instruct our containers on how to build
optimized storage for a given Key. We also require any key to be Copy.
use fixed_map::Key;
#[derive(Clone, Copy, Key)]
enum MyKey {
North,
South,
East,
West,
}
What happens behind the scenes is that a proc macro is used to build a
struct optimized for storing and indexing exactly 4 values - one for each
variant.
Something exactly like this:
struct Storage<V> {
data: [Option<V>; 4],
}
It becomes a bit more complicated once we start considering composite
keys. See the Key documentation for more information.
Why does this crate exist?
There are many cases where you want associate a value with a small, fixed
number of elements identified by an enum.
Let's say you have a game where each room has something in four directions.
We can model this relationship between the direction and the item using two
enums.
#[repr(usize)]
pub enum Dir {
North,
East,
South,
West,
}
pub enum Item {
Bow,
Sword,
Axe,
}
The goal is for the performance of fixed map to be identical to storing the
data linearly in memory like you could through an array like [Option<Item>; N] where each index corresponds to a variant in Dir.
Doing this manually could look like this:
let mut map: [Option<Item>; 4] = [None, None, None, None];
map[Dir::North as usize] = Some(Item::Bow);
if let Some(item) = &map[Dir::North as usize] {
println!("found item: {:?}", item);
}
But with a fixed Map you can do it idiomatically like this, without
incurring a drop in performance:
use fixed_map::{Key, Map};
#[derive(Clone, Copy, Key)]
pub enum Dir {
North,
East,
South,
West,
}
#[derive(Debug)]
pub enum Item {
Bow,
Sword,
Axe,
}
let mut map = Map::new();
map.insert(Dir::North, Item::Bow);
if let Some(item) = map.get(Dir::North) {
println!("found item: {:?}", item);
}
Unsafe use
The Entry API uses unwrap_unchecked to obtain mutable references to the
inner value of Somes, and to skip drop when overwriting Nones.
Benchmarks
We include benchmarks to ensure that we abide by the expectation that a
fixed map or set should perform roughly the same as an array with the same
number of elements.
In the following benchmarks fixed-map is compared to:
fixed - A Map with a derived Key with N variants.
hashbrown - A high performance hash map. This is only included for
reference.
- Note: Maps are created with
HashMap::with_capacity(N).
array - A simple [Option<Key>; N] array.
Note: for all insert benchmarks the underlying storage is cloned in each
iteration.