simple_vec_collections/
vec_map.rs

1//! Associative maps, backed by a [`Vec`].
2
3use std::{borrow::Borrow, fmt::Debug, iter::FusedIterator};
4
5/// An associative map.
6/// It is a logic error for any key to change such that its equality
7/// under the [`Eq`] trait changes while it is in the map.
8/// To determine if two keys are “the same”, [`Eq`] is used.
9#[derive(Clone)]
10pub struct VecMap<K, V>(Vec<(K, V)>);
11
12impl<K, V> VecMap<K, V> {
13    /// Create a new [`VecMap`].
14    pub fn new() -> VecMap<K, V> {
15        VecMap(Vec::new())
16    }
17
18    /// Create a new [`VecMap`] with a given pre-allocated capacity.
19    /// May allocate more than requested.
20    pub fn with_capacity(capacity: usize) -> VecMap<K, V> {
21        VecMap(Vec::with_capacity(capacity))
22    }
23
24    /// Get the allocated capacity of the map.
25    pub fn capacity(&self) -> usize {
26        self.0.capacity()
27    }
28
29    /// Get an iterator over the keys as references.
30    pub fn keys(&self) -> Keys<'_, K, V> {
31        Keys(self.iter())
32    }
33
34    /// Get an iterator over the keys.
35    pub fn into_keys(self) -> IntoKeys<K, V> {
36        IntoKeys(self.into_iter())
37    }
38
39    /// Get an iterator over the values as references.
40    pub fn values(&self) -> Values<'_, K, V> {
41        Values(self.iter())
42    }
43
44    /// Get an iterator over the values as mutable references.
45    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
46        ValuesMut(self.iter_mut())
47    }
48
49    /// Get an iterator over the values.
50    pub fn into_values(self) -> IntoValues<K, V> {
51        IntoValues(self.into_iter())
52    }
53
54    /// Get an iterator over the key-value pairs as tuples of reference.
55    pub fn iter(&self) -> Iter<'_, K, V> {
56        Iter(self.0.iter())
57    }
58
59    /// Get an iterator over the key-value pairs as tuples of a reference and a mutable reference.
60    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
61        IterMut(self.0.iter_mut())
62    }
63
64    /// Get the amount of key-value pairs in the map.
65    pub fn len(&self) -> usize {
66        self.0.len()
67    }
68
69    /// Check if the map is empty.
70    pub fn is_empty(&self) -> bool {
71        self.0.is_empty()
72    }
73
74    /// Empty the map and return an iterator over the cleared key-value pairs.
75    pub fn drain(&mut self) -> Drain<'_, K, V> {
76        Drain(self.0.drain(..))
77    }
78
79    /// Remove all key-value pairs that don’t satisfy a given predicate.
80    pub fn retain<F>(&mut self, mut f: F)
81    where
82        F: FnMut(&K, &mut V) -> bool,
83    {
84        let g = |(key, value): &mut (K, V)| f(key, value);
85        self.0.retain_mut(g)
86    }
87
88    /// Remove all key-value pairs.
89    pub fn clear(&mut self) {
90        self.0.clear()
91    }
92
93    /// Reserve additional space. May allocate more than requested.
94    ///
95    /// # Panics
96    ///
97    /// Panics if the new allocation fails.
98    pub fn reserve(&mut self, additional: usize) {
99        self.0.reserve(additional)
100    }
101
102    /// Like [`reserve`], but returns a [`Result`] instead of panicking.
103    ///
104    /// [`reserve`]: VecMap::reserve
105    pub fn try_reserve(
106        &mut self,
107        additional: usize,
108    ) -> Result<(), std::collections::TryReserveError> {
109        self.0.try_reserve(additional)
110    }
111
112    /// Shrink the capacity of the map as much as possible.
113    /// May keep more than precisely needed.
114    pub fn shrink_to_fit(&mut self) {
115        self.0.shrink_to_fit()
116    }
117
118    /// Shrink the capacity of the map with a lower limit.
119    /// May keep more than precisely needed.
120    pub fn shrink_to(&mut self, min_capacity: usize) {
121        self.0.shrink_to(min_capacity)
122    }
123}
124
125impl<K: Eq, V> VecMap<K, V> {
126    /// Returns an [`Entry`] for the given key.
127    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
128        match self.keys().position(|k| *k == key) {
129            Some(index) => Entry::Occupied(OccupiedEntry {
130                index,
131                key,
132                map: self,
133            }),
134            None => Entry::Vacant(VacantEntry { key, map: self }),
135        }
136    }
137
138    /// Get the given key’s value, if it exists.
139    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
140    where
141        K: Borrow<Q>,
142        Q: Eq,
143    {
144        let mut result = None;
145        for (key, value) in self {
146            if k == key.borrow() {
147                result = Some(value);
148                break;
149            }
150        }
151        result
152    }
153
154    /// Get the given key’s key-value pair, if it exists.
155    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
156    where
157        K: Borrow<Q>,
158        Q: Eq,
159    {
160        let mut result = None;
161        for (key, value) in self {
162            if k == key.borrow() {
163                result = Some((key, value));
164                break;
165            }
166        }
167        result
168    }
169
170    /// Check if the map contains a given key.
171    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
172    where
173        K: Borrow<Q>,
174        Q: Eq,
175    {
176        let mut present = false;
177        for (key, _) in self {
178            if k == key.borrow() {
179                present = true;
180                break;
181            }
182        }
183        present
184    }
185
186    /// Get a mutable reference to the given key’s value, if it exists.
187    pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
188    where
189        K: Borrow<Q>,
190        Q: Eq,
191    {
192        let mut result = None;
193        for (key, value) in self {
194            if k == key.borrow() {
195                result = Some(value);
196                break;
197            }
198        }
199        result
200    }
201
202    /// Insert a key-value pair into the map.
203    /// If the key already exists, the old value is returned.
204    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
205        match self.get_mut(&k) {
206            Some(value) => Some(std::mem::replace(value, v)),
207            None => {
208                self.0.push((k, v));
209                None
210            }
211        }
212    }
213
214    /// Remove the given key’s key-value pair from the map.
215    /// Returns the removed value, if it existed.
216    pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
217    where
218        K: Borrow<Q>,
219        Q: Eq,
220    {
221        let index = self.keys().position(|key| key.borrow() == k)?;
222        let (_, value) = self.0.remove(index);
223        Some(value)
224    }
225
226    /// Remove the given key’s key-value pair from the map.
227    /// Returns the removed key-value pair, if it existed.
228    pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
229    where
230        K: Borrow<Q>,
231        Q: Eq,
232    {
233        let index = self.keys().position(|key| key.borrow() == k)?;
234        Some(self.0.remove(index))
235    }
236}
237
238impl<K: Eq, V: PartialEq> VecMap<K, V> {
239    /// Check two maps for equality while considering the order of key-value pairs.
240    pub fn eq_ordered(&self, other: &Self) -> bool {
241        self.iter().eq(other.iter())
242    }
243}
244
245impl<K: Debug, V: Debug> Debug for VecMap<K, V> {
246    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247        f.debug_map().entries(self.iter()).finish()
248    }
249}
250
251impl<K, V> Default for VecMap<K, V> {
252    fn default() -> Self {
253        Self::new()
254    }
255}
256
257impl<'a, K: Eq + Copy, V: Copy> Extend<(&'a K, &'a V)> for VecMap<K, V> {
258    fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
259        let iter = iter.into_iter();
260        self.reserve(iter.size_hint().0);
261        for (key, value) in iter {
262            self.insert(*key, *value);
263        }
264    }
265}
266
267impl<K: Eq, V> Extend<(K, V)> for VecMap<K, V> {
268    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
269        let iter = iter.into_iter();
270        self.reserve(iter.size_hint().0);
271        for (key, value) in iter {
272            self.insert(key, value);
273        }
274    }
275}
276
277impl<K: Eq, V, const N: usize> From<[(K, V); N]> for VecMap<K, V> {
278    fn from(arr: [(K, V); N]) -> Self {
279        let mut map = Self::with_capacity(arr.len());
280        map.extend(arr);
281        map
282    }
283}
284
285impl<K: Eq, V> FromIterator<(K, V)> for VecMap<K, V> {
286    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
287        let iter = iter.into_iter();
288        let mut map = Self::with_capacity(iter.size_hint().0);
289        map.extend(iter);
290        map
291    }
292}
293
294impl<K, Q: ?Sized, V> std::ops::Index<&Q> for VecMap<K, V>
295where
296    K: Borrow<Q> + Eq,
297    Q: Eq,
298{
299    type Output = V;
300
301    /// Get a given key’s corresponding value from the map.
302    ///
303    /// # Panics
304    ///
305    /// Panics if the key is not in the map.
306    fn index(&self, key: &Q) -> &Self::Output {
307        self.get(key).expect("no entry found for key")
308    }
309}
310
311impl<'a, K, V> IntoIterator for &'a VecMap<K, V> {
312    type Item = (&'a K, &'a V);
313    type IntoIter = Iter<'a, K, V>;
314    fn into_iter(self) -> Self::IntoIter {
315        self.iter()
316    }
317}
318
319impl<'a, K, V> IntoIterator for &'a mut VecMap<K, V> {
320    type Item = (&'a K, &'a mut V);
321    type IntoIter = IterMut<'a, K, V>;
322    fn into_iter(self) -> Self::IntoIter {
323        self.iter_mut()
324    }
325}
326
327impl<K, V> IntoIterator for VecMap<K, V> {
328    type Item = (K, V);
329    type IntoIter = IntoIter<K, V>;
330
331    /// Get an iterator over the key-value pairs.
332    fn into_iter(self) -> Self::IntoIter {
333        IntoIter(self.0.into_iter())
334    }
335}
336
337impl<K: Eq + Ord, V: PartialEq + Ord> PartialEq for VecMap<K, V> {
338    fn eq(&self, other: &Self) -> bool {
339        self.iter()
340            .all(|(key, value)| other.get(key) == Some(value))
341            && other
342                .iter()
343                .all(|(key, value)| self.get(key) == Some(value))
344    }
345}
346
347impl<K: Eq + Ord, V: Eq + Ord> Eq for VecMap<K, V> {}
348
349/// An iterator over the keys of a map.
350/// Yields the keys as references.
351/// Generated by the [`keys`] method.
352///
353/// [`keys`]: VecMap::keys
354pub struct Keys<'a, K, V>(Iter<'a, K, V>);
355
356impl<K, V> Clone for Keys<'_, K, V> {
357    fn clone(&self) -> Self {
358        Keys(self.0.clone())
359    }
360}
361
362impl<K: Debug, V> Debug for Keys<'_, K, V> {
363    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364        f.debug_list().entries(Clone::clone(self)).finish()
365    }
366}
367
368impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
369    fn len(&self) -> usize {
370        self.0.len()
371    }
372}
373
374impl<'a, K, V> Iterator for Keys<'a, K, V> {
375    type Item = &'a K;
376    fn next(&mut self) -> Option<Self::Item> {
377        self.0.next().map(|(key, _)| key)
378    }
379    fn size_hint(&self) -> (usize, Option<usize>) {
380        self.0.size_hint()
381    }
382}
383
384impl<K, V> FusedIterator for Keys<'_, K, V> {}
385
386/// An iterator over the keys of a map.
387/// Yields the keys as values.
388/// Generated by the [`into_keys`] method.
389///
390/// [`into_keys`]: VecMap::into_keys
391pub struct IntoKeys<K, V>(IntoIter<K, V>);
392
393impl<K: Debug, V> Debug for IntoKeys<K, V> {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        f.debug_list()
396            .entries(self.0 .0.as_slice().iter().map(|(key, _)| key))
397            .finish()
398    }
399}
400
401impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
402    fn len(&self) -> usize {
403        self.0 .0.len()
404    }
405}
406
407impl<K, V> Iterator for IntoKeys<K, V> {
408    type Item = K;
409    fn next(&mut self) -> Option<Self::Item> {
410        self.0.next().map(|(key, _)| key)
411    }
412    fn size_hint(&self) -> (usize, Option<usize>) {
413        self.0.size_hint()
414    }
415}
416
417impl<K, V> FusedIterator for IntoKeys<K, V> {}
418
419/// An iterator over the values of a map.
420/// Yields the values as references.
421/// Generated by the [`values`] method.
422///
423/// [`values`]: VecMap::values
424pub struct Values<'a, K, V>(Iter<'a, K, V>);
425
426impl<K, V> Clone for Values<'_, K, V> {
427    fn clone(&self) -> Self {
428        Values(self.0.clone())
429    }
430}
431
432impl<K, V: Debug> Debug for Values<'_, K, V> {
433    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434        f.debug_list().entries(self.clone()).finish()
435    }
436}
437
438impl<K, V> ExactSizeIterator for Values<'_, K, V> {
439    fn len(&self) -> usize {
440        self.0.len()
441    }
442}
443
444impl<'a, K, V> Iterator for Values<'a, K, V> {
445    type Item = &'a V;
446    fn next(&mut self) -> Option<Self::Item> {
447        self.0.next().map(|(_, value)| value)
448    }
449    fn size_hint(&self) -> (usize, Option<usize>) {
450        self.0.size_hint()
451    }
452}
453
454impl<K, V> FusedIterator for Values<'_, K, V> {}
455
456/// An iterator over the values of a map.
457/// Yields the values as values.
458/// Generated by the [`values_mut`] method.
459///
460/// [`values_mut`]: VecMap::values_mut
461pub struct ValuesMut<'a, K, V>(IterMut<'a, K, V>);
462
463impl<K, V: Debug> Debug for ValuesMut<'_, K, V> {
464    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
465        f.debug_list()
466            .entries(self.0 .0.as_slice().iter().map(|(_, value)| value))
467            .finish()
468    }
469}
470
471impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
472    fn len(&self) -> usize {
473        self.0.len()
474    }
475}
476
477impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
478    type Item = &'a mut V;
479    fn next(&mut self) -> Option<Self::Item> {
480        self.0.next().map(|(_, value)| value)
481    }
482    fn size_hint(&self) -> (usize, Option<usize>) {
483        self.0.size_hint()
484    }
485}
486
487impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
488
489/// An iterator over the values of a map.
490/// Yields the values as values.
491/// Generated by the [`into_values`] method.
492///
493/// [`into_values`]: VecMap::into_values
494pub struct IntoValues<K, V>(IntoIter<K, V>);
495
496impl<K, V: Debug> Debug for IntoValues<K, V> {
497    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
498        f.debug_list()
499            .entries(self.0 .0.as_slice().iter().map(|(_, value)| value))
500            .finish()
501    }
502}
503
504impl<K, V> ExactSizeIterator for IntoValues<K, V> {
505    fn len(&self) -> usize {
506        self.0.len()
507    }
508}
509
510impl<K, V> Iterator for IntoValues<K, V> {
511    type Item = V;
512    fn next(&mut self) -> Option<Self::Item> {
513        self.0.next().map(|(_, value)| value)
514    }
515    fn size_hint(&self) -> (usize, Option<usize>) {
516        self.0.size_hint()
517    }
518}
519
520impl<K, V> FusedIterator for IntoValues<K, V> {}
521
522/// An iterator over the key-value pairs of a map.
523/// Yields the pairs as tuples of references.
524/// Generated by the [`iter`] method.
525///
526/// [`iter`]: VecMap::iter
527pub struct Iter<'a, K, V>(std::slice::Iter<'a, (K, V)>);
528
529impl<K, V> Clone for Iter<'_, K, V> {
530    fn clone(&self) -> Self {
531        Self(self.0.clone())
532    }
533}
534
535impl<K: Debug, V: Debug> Debug for Iter<'_, K, V> {
536    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537        f.debug_list().entries(self.clone()).finish()
538    }
539}
540
541impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
542    fn len(&self) -> usize {
543        self.0.len()
544    }
545}
546
547impl<'a, K, V> Iterator for Iter<'a, K, V> {
548    type Item = (&'a K, &'a V);
549    fn next(&mut self) -> Option<Self::Item> {
550        let (key, value) = self.0.next()?;
551        Some((key, value))
552    }
553    fn size_hint(&self) -> (usize, Option<usize>) {
554        self.0.size_hint()
555    }
556}
557
558impl<K, V> FusedIterator for Iter<'_, K, V> {}
559
560/// An iterator over the key-value pairs of a map.
561/// Yields the pairs as tuples of values.
562/// Generated by the [`into_iter`] method.
563///
564/// [`into_iter`]: IntoIterator::into_iter
565pub struct IntoIter<K, V>(std::vec::IntoIter<(K, V)>);
566
567impl<K: Debug, V: Debug> Debug for IntoIter<K, V> {
568    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
569        f.debug_list().entries(self.0.as_slice().iter()).finish()
570    }
571}
572
573impl<K, V> ExactSizeIterator for IntoIter<K, V> {
574    fn len(&self) -> usize {
575        self.0.len()
576    }
577}
578
579impl<K, V> Iterator for IntoIter<K, V> {
580    type Item = (K, V);
581    fn next(&mut self) -> Option<Self::Item> {
582        self.0.next()
583    }
584    fn size_hint(&self) -> (usize, Option<usize>) {
585        self.0.size_hint()
586    }
587}
588
589impl<K, V> FusedIterator for IntoIter<K, V> {}
590
591/// An iterator over the key-value pairs of a map.
592/// Yields the pairs as tuples of a reference and a mutable reference.
593/// Generated by the [`iter_mut`] method.
594///
595/// [`iter_mut`]: VecMap::iter_mut
596pub struct IterMut<'a, K, V>(std::slice::IterMut<'a, (K, V)>);
597
598impl<K: Debug, V: Debug> Debug for IterMut<'_, K, V> {
599    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
600        f.debug_list().entries(self.0.as_slice().iter()).finish()
601    }
602}
603
604impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
605    fn len(&self) -> usize {
606        self.0.len()
607    }
608}
609
610impl<'a, K, V> Iterator for IterMut<'a, K, V> {
611    type Item = (&'a K, &'a mut V);
612    fn next(&mut self) -> Option<Self::Item> {
613        let (key, value) = self.0.next()?;
614        Some((key, value))
615    }
616    fn size_hint(&self) -> (usize, Option<usize>) {
617        self.0.size_hint()
618    }
619}
620
621impl<K, V> FusedIterator for IterMut<'_, K, V> {}
622
623/// An iterator over the removed key-value pairs of a map.
624/// Yields the pairs as tuples of values.
625/// Generated by the [`drain`] method.
626///
627/// [`drain`]: VecMap::drain
628pub struct Drain<'a, K, V>(std::vec::Drain<'a, (K, V)>);
629
630impl<K: Debug, V: Debug> Debug for Drain<'_, K, V> {
631    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
632        f.debug_list().entries(self.0.as_slice().iter()).finish()
633    }
634}
635
636impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
637    fn len(&self) -> usize {
638        self.0.len()
639    }
640}
641
642impl<K, V> Iterator for Drain<'_, K, V> {
643    type Item = (K, V);
644    fn next(&mut self) -> Option<Self::Item> {
645        self.0.next()
646    }
647    fn size_hint(&self) -> (usize, Option<usize>) {
648        self.0.size_hint()
649    }
650}
651
652impl<K, V> FusedIterator for Drain<'_, K, V> {}
653
654/// A view into a single key-value pair of a map.
655/// Generated by the [`entry`] method.
656///
657/// [`entry`]: VecMap::entry
658#[derive(Debug)]
659pub enum Entry<'a, K, V> {
660    /// The given key was already in the map.
661    Occupied(OccupiedEntry<'a, K, V>),
662
663    /// The given key was not in the map.
664    Vacant(VacantEntry<'a, K, V>),
665}
666
667impl<'a, K, V> Entry<'a, K, V> {
668    /// Insert a value under the entry’s key if the entry is vacant.
669    pub fn or_insert(self, default: V) -> &'a mut V {
670        match self {
671            Entry::Occupied(o) => o.into_mut(),
672            Entry::Vacant(v) => v.insert(default),
673        }
674    }
675
676    /// Like [`or_insert`], but takes a closure that is only called if the entry is vacant.
677    ///
678    /// [`or_insert`]: Entry::or_insert
679    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
680        match self {
681            Entry::Occupied(o) => o.into_mut(),
682            Entry::Vacant(v) => v.insert(default()),
683        }
684    }
685
686    /// Like [`or_insert_with`], but the closure takes the entry’s key as an argument.
687    ///
688    /// [`or_insert_with`]: Entry::or_insert_with
689    pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
690        match self {
691            Entry::Occupied(o) => o.into_mut(),
692            Entry::Vacant(v) => {
693                let default = default(&v.key);
694                v.insert(default)
695            }
696        }
697    }
698
699    /// Get a reference to the entry’s key.
700    pub fn key(&self) -> &K {
701        match self {
702            Entry::Occupied(o) => o.key(),
703            Entry::Vacant(v) => v.key(),
704        }
705    }
706
707    /// Modify the entry’s value if the entry is occupied.
708    pub fn and_modify<F>(self, f: F) -> Self
709    where
710        F: FnOnce(&mut V),
711    {
712        match self {
713            Entry::Occupied(mut o) => {
714                let value = o.get_mut();
715                f(value);
716                Entry::Occupied(o)
717            }
718            Entry::Vacant(v) => Entry::Vacant(v),
719        }
720    }
721}
722
723impl<'a, K, V: Default> Entry<'a, K, V> {
724    /// Insert the default value under the entry’s key if the key is vacant.
725    pub fn or_default(self) -> &'a mut V {
726        self.or_insert(Default::default())
727    }
728}
729
730/// An occupied [`Entry`].
731pub struct OccupiedEntry<'a, K, V> {
732    index: usize,
733    key: K,
734    map: &'a mut VecMap<K, V>,
735}
736
737impl<'a, K, V> OccupiedEntry<'a, K, V> {
738    /// Get a reference to the entry’s key.
739    pub fn key(&self) -> &K {
740        &self.key
741    }
742
743    /// Remove the key-value pair at the entry’s key.
744    pub fn remove_entry(self) -> (K, V) {
745        self.map.0.remove(self.index)
746    }
747
748    /// Get a reference to the value at the entry’s key.
749    pub fn get(&self) -> &V {
750        &self.map.0[self.index].1
751    }
752
753    /// Get a mutable reference to the value at the entry’s key.
754    pub fn get_mut(&mut self) -> &mut V {
755        &mut self.map.0[self.index].1
756    }
757
758    /// Get a mutable reference to the value at the entry’s key that lives as long as the map.
759    pub fn into_mut(self) -> &'a mut V {
760        &mut self.map.0[self.index].1
761    }
762
763    /// Replace the value at the entry’s key with a new value.
764    pub fn insert(&mut self, value: V) -> V {
765        std::mem::replace(&mut self.map.0[self.index].1, value)
766    }
767
768    /// Remove the key-value pair at the entry’s key.
769    pub fn remove(self) -> V {
770        self.map.0.remove(self.index).1
771    }
772}
773
774impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
775    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
776        f.debug_tuple("OccupiedEntry")
777            .field(self.key())
778            .field(self.get())
779            .finish()
780    }
781}
782
783/// A vacant [`Entry`].
784pub struct VacantEntry<'a, K, V> {
785    key: K,
786    map: &'a mut VecMap<K, V>,
787}
788
789impl<'a, K, V> VacantEntry<'a, K, V> {
790    /// Get a reference to the entry’s key.
791    pub fn key(&self) -> &K {
792        &self.key
793    }
794
795    /// Get the entry’s key.
796    pub fn into_key(self) -> K {
797        self.key
798    }
799
800    /// Insert a value under the entry’s key.
801    pub fn insert(self, value: V) -> &'a mut V {
802        self.map.0.push((self.key, value));
803        &mut self.map.0.last_mut().unwrap().1
804    }
805}
806
807impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
808    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
809        f.debug_tuple("VacantEntry").field(self.key()).finish()
810    }
811}