Skip to main content

ordinal_map/map/total/
map.rs

1use std::convert::Infallible;
2use std::fmt::Debug;
3use std::fmt::Formatter;
4use std::marker::PhantomData;
5use std::mem;
6use std::ops::Index;
7use std::ops::IndexMut;
8use std::slice;
9
10use crate::map::total::iter::Iter;
11use crate::map::total::IntoIter;
12use crate::map::total::IterMut;
13use crate::Ordinal;
14
15/// Map implementation where all values must be initialized at creation.
16///
17/// This version of map allocates values on the heap in a single contiguous block.
18/// For a version that doesn't require heap allocation,
19/// see [`InitArrayMap`](crate::map::total::OrdinalTotalArrayMap).
20pub struct OrdinalTotalMap<T, V> {
21    map: Box<[V]>,
22    _phantom: PhantomData<T>,
23}
24
25impl<K: Ordinal, V> OrdinalTotalMap<K, V> {
26    /// Create a new map by initializing each value with a function.
27    pub fn try_new<E>(mut init: impl FnMut(K) -> Result<V, E>) -> Result<Self, E> {
28        let mut map = Vec::with_capacity(K::ORDINAL_SIZE);
29        for v in K::all_values() {
30            map.push(init(v)?);
31        }
32        Ok(OrdinalTotalMap {
33            map: map.into_boxed_slice(),
34            _phantom: PhantomData,
35        })
36    }
37
38    /// Create a new map by initializing each value with a function.
39    pub fn new(mut init: impl FnMut(K) -> V) -> Self {
40        match Self::try_new(move |k| Ok::<_, Infallible>(init(k))) {
41            Ok(map) => map,
42            Err(infallible) => match infallible {},
43        }
44    }
45
46    /// Returns the number of elements in the map, which is
47    /// always equal to [`K::ORDINAL_SIZE`](Ordinal::ORDINAL_SIZE).
48    pub const fn len(&self) -> usize {
49        K::ORDINAL_SIZE
50    }
51
52    /// Return true if the map container no elements.
53    /// This is only if `<K>` is empty.
54    pub const fn is_empty(&self) -> bool {
55        self.len() == 0
56    }
57
58    /// Returns a reference to the value corresponding to the key.
59    pub fn get<'a>(&'a self, key: &K) -> &'a V {
60        &self.map[key.ordinal()]
61    }
62
63    /// Returns a mutable reference to the value corresponding to the key.
64    pub fn get_mut<'a>(&'a mut self, key: &K) -> &'a mut V {
65        &mut self.map[key.ordinal()]
66    }
67
68    /// Iterate keys of the map, which is equivalent to iterating all possible values of `K`.
69    pub fn keys(&self) -> crate::OrdinalValues<K> {
70        K::all_values()
71    }
72
73    /// Iterate values of the map, which is equivalent to iterating all possible values of `K`.
74    pub fn into_keys(self) -> crate::OrdinalValues<K> {
75        K::all_values()
76    }
77
78    /// Iterate values of the map.
79    pub fn values<'a>(&'a self) -> slice::Iter<'a, V> {
80        self.map.iter()
81    }
82
83    /// Iterate mutable references to values of the map.
84    pub fn values_mut<'a>(&'a mut self) -> slice::IterMut<'a, V> {
85        self.map.iter_mut()
86    }
87
88    /// Obtain the values from the map.
89    pub fn into_values(self) -> Box<[V]> {
90        self.map
91    }
92
93    /// Iterate over the map.
94    #[inline]
95    pub fn iter<'a>(&'a self) -> Iter<'a, K, V> {
96        Iter::new(self.map.iter(), 0)
97    }
98
99    /// Iterate over the map mutably.
100    #[inline]
101    pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, K, V> {
102        IterMut::new(self.map.iter_mut())
103    }
104
105    /// Insert a value into the map, returning the previous value.
106    #[inline]
107    pub fn insert(&mut self, key: K, value: V) -> V {
108        mem::replace(&mut self.map[key.ordinal()], value)
109    }
110}
111
112impl<K: Ordinal, V: Default> Default for OrdinalTotalMap<K, V> {
113    fn default() -> Self {
114        OrdinalTotalMap::new(|_| V::default())
115    }
116}
117
118impl<'a, K: Ordinal, V> Index<&'a K> for OrdinalTotalMap<K, V> {
119    type Output = V;
120
121    fn index(&self, key: &'a K) -> &Self::Output {
122        self.get(key)
123    }
124}
125
126impl<'a, K: Ordinal, V> IndexMut<&'a K> for OrdinalTotalMap<K, V> {
127    fn index_mut(&mut self, key: &'a K) -> &mut Self::Output {
128        self.get_mut(key)
129    }
130}
131
132impl<K, V: Clone> Clone for OrdinalTotalMap<K, V> {
133    fn clone(&self) -> Self {
134        OrdinalTotalMap {
135            map: self.map.clone(),
136            _phantom: PhantomData,
137        }
138    }
139}
140
141impl<K: Ordinal + Debug, V: Debug> Debug for OrdinalTotalMap<K, V> {
142    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
143        f.debug_map().entries(self.iter()).finish()
144    }
145}
146
147impl<K: Ordinal, V> IntoIterator for OrdinalTotalMap<K, V> {
148    type Item = (K, V);
149    type IntoIter = IntoIter<K, V>;
150
151    fn into_iter(self) -> Self::IntoIter {
152        IntoIter::new(self.map.into_vec().into_iter())
153    }
154}
155
156impl<'a, K: Ordinal, V> IntoIterator for &'a OrdinalTotalMap<K, V> {
157    type Item = (K, &'a V);
158    type IntoIter = Iter<'a, K, V>;
159
160    fn into_iter(self) -> Self::IntoIter {
161        self.iter()
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    #[test]
168    fn test() {}
169}