slotmap - jiemo2187/rust-crates GitHub Wiki
crate地址:slotmap
初次简单这个crate的项目:floem view_storage。
优点:
- 插入、删除、访问都只需O(1)的时间。
- 适合存储需要稳定、安全引用但没有明确所有权的对象集合,如游戏实体或图形节点。
- 可以创建多个二级映射,将 SlotMap 返回的 key 映射到其他 value, 从而将任意数据与存储在 SlotMap 中的对象关联起来。
use std::error::Error;
use slotmap::SecondaryMap;
use slotmap::SlotMap;
fn main() -> Result<(), Box<dyn Error>> {
let mut sm = SlotMap::new();
// insert 会自动生成一个唯一的 key, 用来访问这个值
// 在元素超过 2^32 - 2 个时会 panic
let foo = sm.insert("foo");
let bar = sm.insert("bar");
assert_eq!(sm[foo], "foo");
assert_eq!(sm[bar], "bar");
// remove 移除 key 指定的元素, 并返回 key 对应的值
// 再次 remove 将返回 None
assert_eq!(sm.remove(bar), Some("bar"));
assert_eq!(sm.remove(bar), None);
let reuse = sm.insert("reuse");
assert_eq!(sm.contains_key(bar), false);
// 建立辅助映射, 可以将数据与之前存入 SlotMap 的数据建立关联
let mut sec = SecondaryMap::new();
// 在给定 key 在辅助映射中插入一个值
// 如果 key 已经从 SlotMap 中移除, 会静默失败并且返回 None
// 如果 SlotMap 中没有这个 key, 则返回 None, 否则返回旧值
sec.insert(foo, "noun");
sec.insert(reuse, "verb");
for (key, val) in sm {
println!("{} is a {}", val, sec[key]);
}
Ok(())
}