micromap_rawl/
index.rs

1use crate::Map;
2use core::borrow::Borrow;
3use core::ops::{Index, IndexMut};
4
5impl<K: PartialEq + Borrow<Q>, Q: PartialEq + ?Sized, V, const N: usize> Index<&Q>
6    for Map<K, V, N>
7{
8    type Output = V;
9
10    #[inline]
11    #[must_use]
12    fn index(
13        &self,
14        key: &Q,
15    ) -> &V {
16        self.get(key).expect("No entry found for the key")
17    }
18}
19
20impl<K: PartialEq + Borrow<Q>, Q: PartialEq + ?Sized, V, const N: usize> IndexMut<&Q>
21    for Map<K, V, N>
22{
23    #[inline]
24    #[must_use]
25    fn index_mut(
26        &mut self,
27        key: &Q,
28    ) -> &mut V {
29        self.get_mut(key).expect("No entry found for the key")
30    }
31}
32
33#[cfg(test)]
34mod test {
35    use super::*;
36
37    #[test]
38    fn index() {
39        let mut m: Map<String, i32, 10> = Map::new();
40        m.insert("first".to_string(), 42);
41        assert_eq!(m["first"], 42);
42    }
43
44    #[test]
45    fn index_mut() {
46        let mut m: Map<String, i32, 10> = Map::new();
47        m.insert("first".to_string(), 42);
48        m["first"] += 10;
49        assert_eq!(m["first"], 52);
50    }
51
52    #[test]
53    #[should_panic]
54    fn wrong_index() -> () {
55        let mut m: Map<String, i32, 10> = Map::new();
56        m.insert("first".to_string(), 42);
57        assert_eq!(m["second"], 42);
58    }
59
60    #[cfg(test)]
61    #[derive(PartialEq)]
62    struct Container {
63        pub t: i32,
64    }
65
66    #[cfg(test)]
67    impl Borrow<i32> for Container {
68        fn borrow(&self) -> &i32 {
69            &self.t
70        }
71    }
72
73    #[test]
74    fn index_by_borrow() {
75        let mut m: Map<Container, i32, 10> = Map::new();
76        m.insert(Container { t: 10 }, 42);
77        assert_eq!(m[&10], 42);
78    }
79}