Crate multi_map [] [src]

multi-map

MultiMap is like a std::collection::HashMap, but allows you to use either of two different keys to retrieve items.

The keys have two distinct types - K1 and K2 - which may be the same. Accessing on the primary K1 key is via the usual get, get_mut and remove_alt methods, while accessing via the secondary K2 key is via new get_alt, get_mut_alt and remove_alt methods. The value is of type V.

Internally, two HashMaps are created - a main one on <K1, (K2, V)> and a second one on <K2, K1>. The (K2, V) tuple is so that when an item is removed using the K1 key, the appropriate K2 value is available so the K2->K1 map can be removed from the second HashMap, to keep them in sync.

Using two HashMaps instead of one naturally brings a slight performance and memory penalty. Notably, indexing by K2 requires two HashMap lookups.

use multi_map::MultiMap;
#[derive(Hash,Clone,PartialEq,Eq)]
enum ThingIndex {
    IndexOne,
    IndexTwo,
    IndexThree,
};
let mut map = MultiMap::new();
map.insert("One", ThingIndex::IndexOne, 1);
map.insert("Two", ThingIndex::IndexTwo, 2);
assert!(*map.get_alt(&ThingIndex::IndexOne).unwrap() == 1);
assert!(*map.get(&"Two").unwrap() == 2);
assert!(map.remove_alt(&ThingIndex::IndexTwo).unwrap() == 2);

Structs

MultiMap