1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::ops::{Index, IndexMut};
use crate::{EnumMap, Enumerated};
impl<'a, K, V> Index<K> for EnumMap<'a, K, V>
where
K: Enumerated,
V: Default,
{
type Output = Option<V>;
fn index(&self, key: K) -> &Self::Output {
&self.values[key.position()]
}
}
impl<'a, K, V> IndexMut<K> for EnumMap<'a, K, V>
where
K: Enumerated,
V: Default,
{
fn index_mut(&mut self, key: K) -> &mut Self::Output {
&mut self.values[key.position()]
}
}
#[cfg(test)]
mod tests {
use super::EnumMap;
use crate::enummap::tests::Letter;
#[test]
fn get_insert_index_trait() {
let mut enum_map = EnumMap::<Letter, i32>::new();
enum_map[Letter::A] = Some(42);
assert_eq!(Some(42), enum_map[Letter::A]);
assert_eq!(Some(&42), enum_map[Letter::A].as_ref());
assert_eq!(None, enum_map[Letter::B]);
}
}