Crates.io | once_map |
lib.rs | once_map |
version | 0.4.21 |
source | src |
created_at | 2022-06-22 13:05:15.295688 |
updated_at | 2024-10-14 09:12:25.05092 |
description | Single assignment and lazy maps |
homepage | |
repository | https://github.com/a1phyr/once_map |
max_upload_size | |
id | 610850 |
size | 67,270 |
once_map
This crate provides OnceMap
, a type of HashMap
where entries can be written with a shared reference,
but can be written ony once. This is similar to once_cell
, but with a map.
This enables to reference values inside the map for the lifetime of the map, without the need
of further locks.
This makes this type perfect for implementation of caches. A type LazyMap
is provided for such cases.
This crate provides such a map heavily optimized for concurrent use, but also a single-threaded version.
let map = OnceMap::new();
// All these are `&str` pointing directly in the map.
// Note that we don't need a mutable reference, so we can have several of
// them at the same time.
let roses = map.insert(String::from("rose"), |_| String::from("red"));
let violets = map.insert(String::from("violets"), |_| String::from("blue"));
let sugar = map.insert(String::from("sugar"), |_| String::from("sweet"));
assert_eq!(roses, "red");
assert_eq!(violets, "blue");
assert_eq!(sugar, "sweet");
// The closure is never run here, because we already have a value for "rose"
let roses = map.insert(String::from("rose"), |_| String::from("green"));
// The old value did not change
assert_eq!(roses, "red");