Crate memo_map

source ·
Expand description

A concurrent insert only hash map.

This crate implements a “memo map” which is in many ways similar to a HashMap with some crucial differences:

  • Unlike a regular hash map, a memo map is thread safe and synchronized.
  • Adding or retrieving keys works through a shared reference, removing only through a mutable reference.
  • Retrieving a value from a memo map returns a plain old reference.

Together these purposes allow one to use this type of structure to implement something similar to lazy loading in places where the API has been constrained to references before.

The values in the map are individually boxed up so that resizing of the map retains the previously issued references.

use memo_map::MemoMap;

let memo = MemoMap::new();
let one = memo.get_or_insert(&1, || "one".to_string());
let one2 = memo.get_or_insert(&1, || "not one".to_string());
assert_eq!(one, "one");
assert_eq!(one2, "one");

Notes on Iteration

Because the memo map internally uses a mutex it needs to be held during iteration. This is potentially dangerous as it means you can easily deadlock yourself when trying to use the memo map while iterating. The iteration functionality thus has to be used with great care.

Notes on Removal

Items can be removed from a memo map but this operation requires a mutable reference to the memo map. This is so that it can ensure that there are no borrows outstanding that would be invalidated through the removal of the item.

Structs