libspecr/map/
func.rs

1use crate::*;
2
3impl<K: Obj, V: Obj> Map<K, V> {
4    /// Creates an empty Map.
5    pub fn new() -> Self {
6        Self(Default::default())
7    }
8
9    /// Returns the value to the key `k`.
10    /// Returns `None` if the key `k` is not in the Map.
11    pub fn get(&self, k: K) -> Option<V> {
12        self.0.call_ref_unchecked(|m| m.get(&k).cloned())
13    }
14
15    /// The indexing operator:
16    /// specr translates `a[b]` to `a.index_at(b)`.
17    pub fn index_at(&self, k: K) -> V {
18        self.get(k).unwrap()
19    }
20
21    /// Removes `k` from the map.
22    /// If the pair `(k, v)` was in the map, `Some(v)` is returned.
23    /// Otherwise, `None` is returned.
24    pub fn remove(&mut self, k: K) -> Option<V> {
25        self.0.mutate(|m| {
26            m.remove(&k)
27        })
28    }
29
30    /// Checks whether `self` contains `k`.
31    pub fn contains_key(&self, k: K) -> bool {
32        self.0.call_ref_unchecked(|m| {
33            m.contains_key(&k)
34        })
35    }
36
37    /// Insert a key/value mapping into a map.
38    /// If the map already has a mapping for the given key the previous value is overwritten.
39    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
40        self.0.mutate(|m| {
41            m.insert(k, v)
42        })
43    }
44
45    /// Like `insert`, but fails if `k` was already in the map.
46    pub fn try_insert(&mut self, k: K, v: V) -> Result<(), ()> {
47        if self.contains_key(k) {
48            return Err(());
49        }
50
51        self.insert(k, v);
52
53        Ok(())
54    }
55
56    /// An iterator over all keys.
57    pub fn keys(self) -> impl Iterator<Item=K> {
58        self.into_iter().map(|(k, _)| k)
59    }
60
61    /// An iterator over all values.
62    pub fn values(self) -> impl Iterator<Item=V> {
63        self.into_iter().map(|(_, v)| v)
64    }
65
66    /// Returns the number of elements in `self`.
67    pub fn len(self) -> Int {
68        Int::from(self.0.call_ref_unchecked(|m| m.len()))
69    }
70
71    /// Returns `true` if the map contains no elements.
72    pub fn is_empty(self) -> bool {
73        self.0.call_ref_unchecked(|m| m.is_empty())
74    }
75
76}