fixed_map/map/
entry.rs

1use crate::map::{MapStorage, OccupiedEntry, VacantEntry};
2
3/// A view into a single entry in a map, which may either be vacant or occupied.
4///
5/// This enum is constructed from the [`entry`][crate::Map::entry] method on [`Map`][crate::Map].
6pub enum Entry<'a, S: 'a, K, V>
7where
8    S: MapStorage<K, V>,
9{
10    /// An occupied entry.
11    Occupied(S::Occupied<'a>),
12    /// A vacant entry.
13    Vacant(S::Vacant<'a>),
14}
15
16impl<'a, S: 'a, K, V> Entry<'a, S, K, V>
17where
18    S: MapStorage<K, V>,
19{
20    /// Ensures a value is in the entry by inserting the default if empty,
21    /// and returns a mutable reference to the value in the entry.
22    ///
23    /// # Examples
24    ///
25    /// ```
26    /// use fixed_map::{Key, Map};
27    ///
28    /// #[derive(Clone, Copy, Key)]
29    /// enum MyKey {
30    ///     First,
31    ///     Second,
32    /// }
33    ///
34    /// let mut map: Map<MyKey, i32> = Map::new();
35    ///
36    /// map.entry(MyKey::First).or_insert(3);
37    /// assert_eq!(map.get(MyKey::First), Some(&3));
38    ///
39    /// *map.entry(MyKey::First).or_insert(10) *= 2;
40    /// assert_eq!(map.get(MyKey::First), Some(&6));
41    /// ```
42    ///
43    /// Using a composite key:
44    ///
45    /// ```
46    /// use fixed_map::{Key, Map};
47    ///
48    /// #[derive(Clone, Copy, Key)]
49    /// enum MyKey {
50    ///     First(bool),
51    ///     Second,
52    /// }
53    ///
54    /// let mut map: Map<MyKey, i32> = Map::new();
55    ///
56    /// map.entry(MyKey::First(false)).or_insert(3);
57    /// assert_eq!(map.get(MyKey::First(false)), Some(&3));
58    ///
59    /// *map.entry(MyKey::First(false)).or_insert(10) *= 2;
60    /// assert_eq!(map.get(MyKey::First(false)), Some(&6));
61    /// ```
62    #[inline]
63    pub fn or_insert(self, default: V) -> &'a mut V {
64        match self {
65            Entry::Occupied(entry) => entry.into_mut(),
66            Entry::Vacant(entry) => entry.insert(default),
67        }
68    }
69
70    /// Ensures a value is in the entry by inserting the result of the default function if empty,
71    /// and returns a mutable reference to the value in the entry.
72    ///
73    /// # Examples
74    ///
75    /// ```
76    /// use fixed_map::{Key, Map};
77    ///
78    /// #[derive(Clone, Copy, Key)]
79    /// enum MyKey {
80    ///     First,
81    ///     Second,
82    /// }
83    ///
84    /// let mut map: Map<MyKey, String> = Map::new();
85    ///
86    /// map.entry(MyKey::First).or_insert_with(|| format!("{}", 3));
87    /// assert_eq!(map.get(MyKey::First), Some(&"3".to_string()));
88    /// ```
89    ///
90    /// Using a composite key:
91    ///
92    /// ```
93    /// use fixed_map::{Key, Map};
94    ///
95    /// #[derive(Clone, Copy, Key)]
96    /// enum MyKey {
97    ///     First(bool),
98    ///     Second,
99    /// }
100    ///
101    /// let mut map: Map<MyKey, String> = Map::new();
102    ///
103    /// map.entry(MyKey::First(false)).or_insert_with(|| format!("{}", 3));
104    /// assert_eq!(map.get(MyKey::First(false)), Some(&"3".to_string()));
105    /// ```
106    #[inline]
107    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
108    where
109        F: FnOnce() -> V,
110    {
111        match self {
112            Entry::Occupied(entry) => entry.into_mut(),
113            Entry::Vacant(entry) => entry.insert(default()),
114        }
115    }
116
117    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
118    /// This method allows for generating key-derived values for insertion by providing the default
119    /// function a copy of the key that was passed to the `.entry(key)` method call.
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use fixed_map::{Key, Map};
125    ///
126    /// #[derive(Clone, Copy, Key, Debug)]
127    /// enum MyKey {
128    ///     First,
129    ///     Second,
130    /// }
131    ///
132    /// let mut map: Map<MyKey, String> = Map::new();
133    ///
134    /// map.entry(MyKey::First).or_insert_with_key(|k| format!("{:?} = {}", k, 3));
135    /// assert_eq!(map.get(MyKey::First), Some(&"First = 3".to_string()));
136    /// ```
137    ///
138    /// Using a composite key:
139    ///
140    /// ```
141    /// use fixed_map::{Key, Map};
142    ///
143    /// #[derive(Clone, Copy, Key, Debug)]
144    /// enum MyKey {
145    ///     First(bool),
146    ///     Second,
147    /// }
148    ///
149    /// let mut map: Map<MyKey, String> = Map::new();
150    ///
151    /// map.entry(MyKey::First(false)).or_insert_with_key(|k| format!("{:?} = {}", k, 3));
152    /// assert_eq!(map.get(MyKey::First(false)), Some(&"First(false) = 3".to_string()));
153    /// ```
154    #[inline]
155    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
156    where
157        F: FnOnce(K) -> V,
158    {
159        match self {
160            Entry::Occupied(entry) => entry.into_mut(),
161            Entry::Vacant(entry) => {
162                let value = default(entry.key());
163                entry.insert(value)
164            }
165        }
166    }
167
168    /// Returns a copy of this entry's key.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// use fixed_map::{Key, Map};
174    ///
175    /// #[derive(Clone, Copy, Key, Debug, PartialEq)]
176    /// enum MyKey {
177    ///     First,
178    ///     Second,
179    /// }
180    ///
181    /// let mut map: Map<MyKey, i32> = Map::new();
182    /// assert_eq!(map.entry(MyKey::First).key(), MyKey::First);
183    /// ```
184    ///
185    /// Using a composite key:
186    ///
187    /// ```
188    /// use fixed_map::{Key, Map};
189    ///
190    /// #[derive(Clone, Copy, Key, Debug, PartialEq)]
191    /// enum MyKey {
192    ///     First(bool),
193    ///     Second,
194    /// }
195    ///
196    /// let mut map: Map<MyKey, i32> = Map::new();
197    /// assert_eq!(map.entry(MyKey::First(false)).key(), MyKey::First(false));
198    /// ```
199    #[inline]
200    pub fn key(&self) -> K {
201        match self {
202            Entry::Occupied(entry) => entry.key(),
203            Entry::Vacant(entry) => entry.key(),
204        }
205    }
206
207    /// Provides in-place mutable access to an occupied entry before any
208    /// potential inserts into the map.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use fixed_map::{Key, Map};
214    ///
215    /// #[derive(Clone, Copy, Key)]
216    /// enum MyKey {
217    ///     First,
218    ///     Second,
219    /// }
220    ///
221    /// let mut map: Map<MyKey, i32> = Map::new();
222    ///
223    /// map.entry(MyKey::First)
224    ///    .and_modify(|e| { *e += 1 })
225    ///    .or_insert(42);
226    /// assert_eq!(map.get(MyKey::First), Some(&42));
227    ///
228    /// map.entry(MyKey::First)
229    ///    .and_modify(|e| { *e += 1 })
230    ///    .or_insert(42);
231    /// assert_eq!(map.get(MyKey::First), Some(&43));
232    /// ```
233    ///
234    /// Using a composite key:
235    ///
236    /// ```
237    /// use fixed_map::{Key, Map};
238    ///
239    /// #[derive(Clone, Copy, Key)]
240    /// enum MyKey {
241    ///     First(bool),
242    ///     Second,
243    /// }
244    ///
245    /// let mut map: Map<MyKey, i32> = Map::new();
246    ///
247    /// map.entry(MyKey::First(true))
248    ///    .and_modify(|e| { *e += 1 })
249    ///    .or_insert(42);
250    /// assert_eq!(map.get(MyKey::First(true)), Some(&42));
251    ///
252    /// map.entry(MyKey::First(true))
253    ///    .and_modify(|e| { *e += 1 })
254    ///    .or_insert(42);
255    /// assert_eq!(map.get(MyKey::First(true)), Some(&43));
256    /// ```
257    #[inline]
258    #[must_use]
259    pub fn and_modify<F>(self, f: F) -> Self
260    where
261        F: FnOnce(&mut V),
262    {
263        match self {
264            Entry::Occupied(mut entry) => {
265                f(entry.get_mut());
266                Entry::Occupied(entry)
267            }
268            Entry::Vacant(entry) => Entry::Vacant(entry),
269        }
270    }
271
272    /// Ensures a value is in the entry by inserting the default value if empty,
273    /// and returns a mutable reference to the value in the entry.
274    ///
275    /// # Examples
276    ///
277    /// ```
278    /// use fixed_map::{Key, Map};
279    ///
280    /// #[derive(Clone, Copy, Key)]
281    /// enum MyKey {
282    ///     First,
283    ///     Second,
284    /// }
285    ///
286    /// let mut map: Map<MyKey, i32> = Map::new();
287    ///
288    /// map.entry(MyKey::First).or_default();
289    /// assert_eq!(map.get(MyKey::First), Some(&0));
290    /// ```
291    ///
292    /// Using a composite key:
293    ///
294    /// ```
295    /// use fixed_map::{Key, Map};
296    ///
297    /// #[derive(Clone, Copy, Key)]
298    /// enum MyKey {
299    ///     First(bool),
300    ///     Second,
301    /// }
302    ///
303    /// let mut map: Map<MyKey, i32> = Map::new();
304    ///
305    /// map.entry(MyKey::First(false)).or_default();
306    /// assert_eq!(map.get(MyKey::First(false)), Some(&0));
307    /// ```
308    #[inline]
309    pub fn or_default(self) -> &'a mut V
310    where
311        V: Default,
312    {
313        match self {
314            Entry::Occupied(entry) => entry.into_mut(),
315            Entry::Vacant(entry) => entry.insert(Default::default()),
316        }
317    }
318}