r/rust • u/nightcracker • Jan 04 '21
slotmap 1.0 has been released! Copy restriction removed, no_std support, and more
With the stabilization of ManuallyDrop<T> in unions (without T needing to be Copy) I could finally improveslotmap to no longer require Copy types for any of its data structures, the main gripe people had with the library.
I also implemented the remaining main requested features:
no_stdsupport.get_disjoint_mut([K; N]) -> Option<[&mut V; N]>which allows you to get multiple mutable references into a slot map at the same time (assuming the keys are disjoint). Requiresmin-const-genericsso will be only available in nightly until Rust 1.51 comes out.- Added an
EntryAPI to the secondary maps.
This, and realizing the API is stable and works, made me realize that the next release should be 1.0. So here we are.
For those unfamiliar with slotmap, it is a crate that provides a data structure - the slot map - which allows you to get stable, unique handles (which it calls Keys) to the values you put into it. The keys can be thought of as indices to a vector owning the data, except are much safer in their usage, because unlike an index you can delete data, reuse the memory, and still be secure that your key will not point to the new data. Finally it also contains 'secondary maps' which allow you to associate further data with keys. Under the hood the a Key is simply a (idx, version) pair, so SlotMap lookups are almost as fast as Vec<T> lookups - and the same holds for SecondaryMap. Unsafe code is used where necessary to ensure that memory and runtime overhead is as minimal as possible.
It has many applications, for example in games (see https://www.youtube.com/watch?v=P9u8x13W7UE) through entity-component systems, in traditionally pointer-based data structures such as (self-referential) graphs and trees (see the examples: https://github.com/orlp/slotmap/tree/master/examples), generally whenever you have unclear ownership, and much more. There is serde support baked in, so you can serialize an entire graph, deserialize it, and be secure in that all your references still work. Finally, I've implemented slotmap as a proper crate of data structures, and each has all the bells and whistles you might expect: capacity, iterators, index traits, drain/retain/get(_unchecked)?(_mut)?/entry/..., etc. The documentation is extensive and complete (every public item is documented with what it does and has a short example).
A very brief example:
use slotmap::{SlotMap, SecondaryMap};
let mut sm = SlotMap::new();
let foo = sm.insert("foo"); // Key generated on insert.
let bar = sm.insert("bar");
assert_eq!(sm[foo], "foo");
assert_eq!(sm[bar], "bar");
sm.remove(bar);
let reuse = sm.insert("reuse"); // Space from bar reused.
assert_eq!(sm.contains_key(bar), false); // After deletion a key stays invalid.
let mut sec = SecondaryMap::new();
sec.insert(foo, "noun"); // We provide the key for secondary maps.
sec.insert(reuse, "verb");
for (key, val) in sm {
println!("{} is a {}", val, sec[key]);
}
38
u/Programmurr Jan 04 '21 edited Jan 04 '21
Congratulations! I've been thinking about slotmaps for directed graphs -- tradeoffs, strengths, weaknesses, contrasts with adj lists, etc. Is there anyone out there who is familiar and will comment? In what situations would you choose a slotmap-backed graph?
That doubly linked list example turned a really challenging data structure for Rust into something straightforward. Interesting.
8
u/Icarium-Lifestealer Jan 04 '21
get_disjoint_mutin the documentation of 1.0.1uncheckedfunctions8
u/C5H5N5O Jan 04 '21
Is there any reason your not using a CI for automatic testing?
4
u/dpc_pw Jan 04 '21
Can someone compare this with https://docs.rs/slab? I've been using
slabfor this purpose for a long while now.Oh, I think I know - the
versionon the key?2
u/RoyAwesome Jan 04 '21
How large are the keys? Is it possible to use smaller key sizes if the amount of data stored in a slotmap is small?
14
u/mmstick Jan 04 '21
This is big news and exactly what I've waited for.
9
u/mardabx Jan 04 '21
Thanks for listing use cases in repo
4
u/[deleted] Jan 04 '21
Finally! I have been excited about this crate since I watched that very video. Congratulations!
4
u/mamcx Jan 04 '21
Amazing.
The first time I read about this it feels to me like a possible nice way to do relational/DB-in-memory programming. It sounds like SlotMap is a "table" and SecondaryMap is an "index".
1
u/[deleted] Jan 04 '21
Slotmap exposes insertion-order operations, doesn't it? It could replace linked-hash-map? I haven't come across mentions of insertion order, yet, in slotmap docs.
1
u/CouteauBleu Jan 10 '21 edited Jan 10 '21
Does this slotmap implementation offer a way to iterate through entries in "storage" order instead of key order?
One drawback of slotmaps is that it adds an extra layer of indirection when accessing items, and can shuffle the order the data is stored in, which isn't ideal for CPU cache efficiency.
A workaround is to iterate on entries in the order they're stored in, which more efficient especially for cases where you only need to access the data itself and don't care about its index.
1
u/azure1992 Jan 04 '21
So the minimum supported Rust version is Rust 1.49.0?
I would prefer if crate authors wrote the MSRV of their crate somewhere.
2
u/flaghacker_ Jan 05 '21
Ah this is great, Ive been using a crappy handrolled version of this for a while now with a little todo comment saying to look for a proper replacement, and it looks like this is exactly it.
Is there a way to automatically deduplicate values in the slotmap? Like if I push the same value twice the same key should be returned twice as well. I'm not too sure about the internals of this data structure so maybe it's not possible at all.
3
u/CommunismDoesntWork Jan 04 '21
The syntax is super clean. Almost pythonic! I'll have to check it out
1
u/homa_rano Jan 05 '21
I didn't grok what this was for at first, but I now understand it to be a kind of arena allocator with the bonus feature of dynamic checks for use-after-free. Neat!