indexed_map/
lib.rs

1//! # indexed_map
2//! HashMap wrapper where each value corresponds to a uniquely generated `usize` key
3
4use std::collections::HashMap;
5
6/// An indexed map
7///
8/// TODO: replace `inner` methods with full copy of `HashMap` API
9#[derive(Debug, Clone)]
10pub struct IndexedMap<T> {
11    next_key: usize,
12    items: HashMap<usize, T>,
13}
14
15impl<T> IndexedMap<T> {
16    /// Create a new `IndexedMap'
17    ///
18    /// # Examples
19    ///
20    /// ```
21    /// use indexed_map::IndexedMap;
22    /// let mut foo = IndexedMap::new();
23    /// let bar = foo.insert("bar");
24    /// println!("{:?}", foo);
25    /// ```
26    pub fn new() -> IndexedMap<T> {
27        IndexedMap {
28            next_key: 0,
29            items: HashMap::new(),
30        }
31    }
32
33    fn next_key(&mut self) -> usize {
34        let key = self.next_key;
35        self.next_key += 1;
36        key
37    }
38
39    /// Insert an item, creating a new unique key, and return the key
40    ///
41    /// # Examples
42    ///
43    /// ```
44    /// use indexed_map::IndexedMap;
45    ///
46    /// // create an empty `IndexedMap`, just like `HashMap`
47    /// let mut fruits = IndexedMap::new();
48    ///
49    /// // insert some values and store their keys for later use
50    /// let apple = fruits.insert("Apple");
51    /// let orange = fruits.insert("Orange");
52    /// let pear = fruits.insert("Pear");
53    ///
54    /// // list the values we've inserted
55    /// for fruit in fruits.inner().values() {
56    ///     println!("{}", fruit);
57    /// }
58    ///
59    /// // access using unique keys
60    /// assert_eq!("Apple", *fruits.inner().get(&apple).unwrap());
61    /// assert_eq!("Orange", *fruits.inner().get(&orange).unwrap());
62    /// assert_eq!("Pear", *fruits.inner().get(&pear).unwrap());
63    pub fn insert(&mut self, value: T) -> usize {
64        let key = self.next_key();
65        self.items.insert(key, value);
66        key
67    }
68
69    /// Access the underlying `HashMap`
70    pub fn inner(&self) -> &HashMap<usize, T> {
71        &self.items
72    }
73
74    /// Mutably access the underlying `HashMap`
75    pub fn inner_mut(&mut self) -> &mut HashMap<usize, T> {
76        &mut self.items
77    }
78
79    /// Unwrap the `IndexedMap` to return the underlying `HashMap`
80    pub fn into_inner(self) -> HashMap<usize, T> {
81        self.items
82    }
83}