#map #lazy-evaluation #once

no-std once_map

Single assignment and lazy maps

20 releases

new 0.4.17 Apr 15, 2024
0.4.15 Feb 13, 2024
0.4.13 Nov 23, 2023
0.4.6 Jun 6, 2023
0.3.1 Jul 10, 2022

#31 in Caching

Download history 689/week @ 2023-12-23 490/week @ 2023-12-30 696/week @ 2024-01-06 730/week @ 2024-01-13 848/week @ 2024-01-20 602/week @ 2024-01-27 985/week @ 2024-02-03 481/week @ 2024-02-10 814/week @ 2024-02-17 964/week @ 2024-02-24 803/week @ 2024-03-02 400/week @ 2024-03-09 908/week @ 2024-03-16 499/week @ 2024-03-23 630/week @ 2024-03-30 698/week @ 2024-04-06

2,776 downloads per month
Used in 15 crates (4 directly)

MIT/Apache

60KB
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–8.5MB
~31K SLoC