#value #hash-map #collecting #key #multiple-values #store #vec

collecting-hashmap

A hashmap that will store multiple values for a key

2 unstable releases

Uses old Rust 2015

0.2.0 Oct 29, 2018
0.1.0 Oct 27, 2018

#252 in Database implementations

24 downloads per month
Used in mihoyo-api

MIT/Apache

14KB
221 lines

Collecting HashMap

This is a HashMap that stores all values as a Vec of values instead of a single value. So a CollectingHashMap<K, V> is pretty much the same as a HashMap<K, Vec<V>> with some tweaks to the API to make this a bit easier to work with


lib.rs:

Collecting HashMap

This is a HashMap that allows the user to store multiple V values for each K key. Currently it is implemented by internally keeping a HashMap<K, Vec<V>> and forwarding most operations to that HashMap. There area few calls where it does more than just forward, in order to keep the API as functionally similar to a regular HashMap<K, V> as possible. The main difference is with the insert method. Since it won't replace the original value if you insert another value for the same K, this insert returns nothing.

The get and get_mut methods have the same signature as a regular HashMap<K, V>. Instead of returning the whole underlying Vec for a key, get and get_mut both return a reference to the first item in the Vec. In order to get a reference to the whole Vec for a key, use get_all and get_all_mut.

The Entry API operates on the entire underlying Vec for a key.

Examples

use collecting_hashmap::CollectingHashMap;

let mut map = CollectingHashMap::new();
map.insert("voltron", "black");
map.insert("voltron", "red");
map.insert("voltron", "green");
map.insert("voltron", "blue");
map.insert("voltron", "yellow");
assert_eq!(map.get_all("voltron"), Some(&vec!["black", "red", "green", "blue", "yellow"]));
use collecting_hashmap::CollectingHashMap;

let query_string = vec![
    ("q", "query1"),
    ("t", "0m2s"),
    ("q", "query2"),
    ("q", "query3"),
];
let map = query_string.into_iter().collect::<CollectingHashMap<_, _>>();
assert_eq!(map.get_all("q"), Some(&vec!["query1", "query2", "query3"]));

No runtime deps