#map #lazy-evaluation #once #cache

no-std once_map

Single assignment and lazy maps

24 releases

0.4.21 Oct 14, 2024
0.4.19 Aug 28, 2024
0.4.18 May 15, 2024
0.4.15 Feb 13, 2024
0.3.1 Jul 10, 2022

#22 in Caching

Download history 5404/week @ 2024-07-21 7997/week @ 2024-07-28 8102/week @ 2024-08-04 7800/week @ 2024-08-11 8249/week @ 2024-08-18 8054/week @ 2024-08-25 8153/week @ 2024-09-01 9239/week @ 2024-09-08 9233/week @ 2024-09-15 10492/week @ 2024-09-22 11228/week @ 2024-09-29 12310/week @ 2024-10-06 11167/week @ 2024-10-13 10975/week @ 2024-10-20 10639/week @ 2024-10-27 8455/week @ 2024-11-03

42,923 downloads per month
Used in 15 crates (5 directly)

MIT/Apache

65KB
2K SLoC

once_map

Crates.io Docs.rs Minimum rustc version

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.

Example

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");

Dependencies

~1.2–6.5MB
~33K SLoC