vecmap/
map.rs

1//! `VecMap` is a vector-based map implementation which retains the order of inserted entries.
2
3mod entry;
4mod impls;
5mod iter;
6mod mutable_keys;
7#[cfg(feature = "serde")]
8mod serde;
9
10use super::{Entries, Slot, TryReserveError};
11use alloc::vec::Vec;
12use core::borrow::Borrow;
13use core::cmp::Ordering;
14use core::mem;
15use core::ops::RangeBounds;
16use core::ptr;
17
18pub use self::entry::{Entry, OccupiedEntry, VacantEntry};
19pub use self::iter::*;
20pub use self::mutable_keys::MutableKeys;
21
22/// A vector-based map implementation which retains the order of inserted entries.
23///
24/// Internally it is represented as a `Vec<(K, V)>` to support keys that are neither `Hash` nor
25/// `Ord`.
26#[derive(Clone, Debug)]
27pub struct VecMap<K, V> {
28    pub(crate) base: Vec<Slot<K, V>>,
29}
30
31impl<K, V> VecMap<K, V> {
32    /// Create a new map. (Does not allocate.)
33    ///
34    /// # Examples
35    ///
36    /// ```
37    /// use vecmap::VecMap;
38    ///
39    /// let mut map: VecMap<i32, &str> = VecMap::new();
40    /// ```
41    pub const fn new() -> Self {
42        VecMap { base: Vec::new() }
43    }
44
45    /// Create a new map with capacity for `capacity` key-value pairs. (Does not allocate if
46    /// `capacity` is zero.)
47    ///
48    /// # Examples
49    ///
50    /// ```
51    /// use vecmap::VecMap;
52    ///
53    /// let mut map: VecMap<i32, &str> = VecMap::with_capacity(10);
54    /// assert_eq!(map.len(), 0);
55    /// assert!(map.capacity() >= 10);
56    /// ```
57    pub fn with_capacity(capacity: usize) -> Self {
58        VecMap {
59            base: Vec::with_capacity(capacity),
60        }
61    }
62
63    /// Returns the number of entries the map can hold without reallocating.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// use vecmap::VecMap;
69    ///
70    /// let mut map: VecMap<i32, &str> = VecMap::with_capacity(10);
71    /// assert_eq!(map.capacity(), 10);
72    /// ```
73    pub fn capacity(&self) -> usize {
74        self.base.capacity()
75    }
76
77    /// Returns the number of entries in the map, also referred to as its 'length'.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use vecmap::VecMap;
83    ///
84    /// let mut a = VecMap::new();
85    /// assert_eq!(a.len(), 0);
86    /// a.insert(1, "a");
87    /// assert_eq!(a.len(), 1);
88    /// ```
89    pub fn len(&self) -> usize {
90        self.base.len()
91    }
92
93    /// Returns `true` if the map contains no entries.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// use vecmap::VecMap;
99    ///
100    /// let mut a = VecMap::new();
101    /// assert!(a.is_empty());
102    /// a.insert(1, "a");
103    /// assert!(!a.is_empty());
104    /// ```
105    pub fn is_empty(&self) -> bool {
106        self.base.is_empty()
107    }
108
109    /// Clears the map, removing all entries.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use vecmap::VecMap;
115    ///
116    /// let mut a = VecMap::new();
117    /// a.insert(1, "a");
118    /// a.clear();
119    /// assert!(a.is_empty());
120    /// ```
121    pub fn clear(&mut self) {
122        self.base.clear();
123    }
124
125    /// Shortens the map, keeping the first `len` key-value pairs and dropping the rest.
126    ///
127    /// If `len` is greater than the map's current length, this has no effect.
128    ///
129    /// # Examples
130    ///
131    /// Truncating a four element map to two elements:
132    ///
133    /// ```
134    /// use vecmap::VecMap;
135    ///
136    /// let mut map = VecMap::from([("a", 1), ("b", 2), ("c", 3), ("d", 4)]);
137    /// map.truncate(2);
138    /// assert_eq!(map, VecMap::from([("a", 1), ("b", 2)]));
139    /// ```
140    ///
141    /// No truncation occurs when `len` is greater than the map's current length:
142    ///
143    /// ```
144    /// use vecmap::VecMap;
145    ///
146    /// let mut map = VecMap::from([("a", 1), ("b", 2), ("c", 3), ("d", 4)]);
147    /// map.truncate(8);
148    /// assert_eq!(map, VecMap::from([("a", 1), ("b", 2), ("c", 3), ("d", 4)]));
149    /// ```
150    pub fn truncate(&mut self, len: usize) {
151        self.base.truncate(len);
152    }
153
154    /// Reverses the order of entries in the map, in place.
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// # extern crate alloc;
160    /// # use alloc::vec::Vec;
161    /// use vecmap::VecMap;
162    ///
163    /// let mut map = VecMap::from_iter([("a", 1), ("b", 2), ("c", 3)]);
164    /// map.reverse();
165    /// let reversed: Vec<(&str, u8)> = map.into_iter().collect();
166    /// assert_eq!(reversed, Vec::from_iter([("c", 3), ("b", 2), ("a", 1)]));
167    /// ```
168    pub fn reverse(&mut self) {
169        self.base.reverse();
170    }
171
172    /// Reserves capacity for at least `additional` more elements to be inserted in the given
173    /// `VecMap<K, V>`. The collection may reserve more space to speculatively avoid frequent
174    /// reallocations. After calling `reserve`, capacity will be greater than or equal to
175    /// `self.len() + additional`. Does nothing if capacity is already sufficient.
176    ///
177    /// # Panics
178    ///
179    /// Panics if the new capacity exceeds `isize::MAX` bytes.
180    ///
181    /// # Examples
182    ///
183    /// ```
184    /// use vecmap::VecMap;
185    ///
186    /// let mut map = VecMap::from_iter([("a", 1)]);
187    /// map.reserve(10);
188    /// assert!(map.capacity() >= 11);
189    /// ```
190    pub fn reserve(&mut self, additional: usize) {
191        self.base.reserve(additional);
192    }
193
194    /// Reserves the minimum capacity for at least `additional` more elements to be inserted in the
195    /// given `VecMap<K, V>`. Unlike [`reserve`], this will not deliberately over-allocate to
196    /// speculatively avoid frequent allocations. After calling `reserve_exact`, capacity will be
197    /// greater than or equal to `self.len() + additional`. Does nothing if the capacity is already
198    /// sufficient.
199    ///
200    /// Note that the allocator may give the collection more space than it requests. Therefore,
201    /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
202    /// insertions are expected.
203    ///
204    /// [`reserve`]: VecMap::reserve
205    ///
206    /// # Panics
207    ///
208    /// Panics if the new capacity exceeds `isize::MAX` bytes.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use vecmap::VecMap;
214    ///
215    /// let mut map = VecMap::from_iter([("a", 1)]);
216    /// map.reserve(10);
217    /// assert!(map.capacity() >= 11);
218    /// ```
219    pub fn reserve_exact(&mut self, additional: usize) {
220        self.base.reserve_exact(additional);
221    }
222
223    /// Tries to reserve capacity for at least `additional` more elements to be inserted in the
224    /// given `VecMap<K, V>`. The collection may reserve more space to speculatively avoid frequent
225    /// reallocations. After calling `try_reserve`, capacity will be greater than or equal to
226    /// `self.len() + additional` if it returns `Ok(())`. Does nothing if capacity is already
227    /// sufficient. This method preserves the contents even if an error occurs.
228    ///
229    /// # Errors
230    ///
231    /// If the capacity overflows, or the allocator reports a failure, then an error
232    /// is returned.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// use vecmap::{TryReserveError, VecMap};
238    ///
239    /// fn process_data(data: &[(u32, u32)]) -> Result<VecMap<u32, u32>, TryReserveError> {
240    ///     let mut output = VecMap::new();
241    ///
242    ///     // Pre-reserve the memory, exiting if we can't
243    ///     output.try_reserve(data.len())?;
244    ///
245    ///     // Now we know this can't OOM in the middle of our complex work
246    ///     output.extend(data.iter().map(|(k, v)| {
247    ///         (k * 2 + 5, v * 2 + 5) // very complicated
248    ///     }));
249    ///
250    ///     Ok(output)
251    /// }
252    /// # process_data(&[(1, 1), (2, 2), (3, 3)]).expect("why is the test harness OOMing?");
253    /// ```
254    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
255        self.base.try_reserve(additional)
256    }
257
258    /// Tries to reserve the minimum capacity for at least `additional` elements to be inserted in
259    /// the given `VecMap<K, V>`. Unlike [`try_reserve`], this will not deliberately over-allocate
260    /// to speculatively avoid frequent allocations. After calling `try_reserve_exact`, capacity
261    /// will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does
262    /// nothing if the capacity is already sufficient.
263    ///
264    /// Note that the allocator may give the collection more space than it requests. Therefore,
265    /// capacity can not be relied upon to be precisely minimal. Prefer [`try_reserve`] if future
266    /// insertions are expected.
267    ///
268    /// [`try_reserve`]: VecMap::try_reserve
269    ///
270    /// # Errors
271    ///
272    /// If the capacity overflows, or the allocator reports a failure, then an error is returned.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use vecmap::{TryReserveError, VecMap};
278    ///
279    /// fn process_data(data: &[(u32, u32)]) -> Result<VecMap<u32, u32>, TryReserveError> {
280    ///     let mut output = VecMap::new();
281    ///
282    ///     // Pre-reserve the memory, exiting if we can't
283    ///     output.try_reserve_exact(data.len())?;
284    ///
285    ///     // Now we know this can't OOM in the middle of our complex work
286    ///     output.extend(data.iter().map(|(k, v)| {
287    ///         (k * 2 + 5, v * 2 + 5) // very complicated
288    ///     }));
289    ///
290    ///     Ok(output)
291    /// }
292    /// # process_data(&[(1, 1), (2, 2), (3, 3)]).expect("why is the test harness OOMing?");
293    /// ```
294    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
295        self.base.try_reserve_exact(additional)
296    }
297
298    /// Retains only the elements specified by the predicate.
299    ///
300    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
301    ///
302    /// # Examples
303    ///
304    /// ```
305    /// use vecmap::VecMap;
306    ///
307    /// let mut map: VecMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
308    /// map.retain(|&k, _| k % 2 == 0);
309    /// assert_eq!(map.len(), 4);
310    /// ```
311    pub fn retain<F>(&mut self, mut f: F)
312    where
313        F: FnMut(&K, &mut V) -> bool,
314    {
315        self.base.retain_mut(|slot| {
316            let (key, value) = slot.ref_mut();
317            f(key, value)
318        });
319    }
320
321    /// Shrinks the capacity of the map as much as possible. It will drop down as much as possible
322    /// while maintaining the internal rules and possibly leaving some space in accordance with
323    /// the resize policy.
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// use vecmap::VecMap;
329    ///
330    /// let mut map: VecMap<i32, i32> = VecMap::with_capacity(100);
331    /// map.insert(1, 2);
332    /// map.insert(3, 4);
333    /// assert!(map.capacity() >= 100);
334    /// map.shrink_to_fit();
335    /// assert!(map.capacity() >= 2);
336    /// ```
337    pub fn shrink_to_fit(&mut self) {
338        self.base.shrink_to_fit();
339    }
340
341    /// Shrinks the capacity of the map with a lower limit. It will drop down no lower than the
342    /// supplied limit while maintaining the internal rules and possibly leaving some space in
343    /// accordance with the resize policy.
344    ///
345    /// If the current capacity is less than the lower limit, this is a no-op.
346    ///
347    /// # Examples
348    ///
349    /// ```
350    /// use vecmap::VecMap;
351    ///
352    /// let mut map: VecMap<i32, i32> = VecMap::with_capacity(100);
353    /// map.insert(1, 2);
354    /// map.insert(3, 4);
355    /// assert!(map.capacity() >= 100);
356    /// map.shrink_to(10);
357    /// assert!(map.capacity() >= 10);
358    /// map.shrink_to(0);
359    /// assert!(map.capacity() >= 2);
360    /// ```
361    pub fn shrink_to(&mut self, min_capacity: usize) {
362        self.base.shrink_to(min_capacity);
363    }
364
365    /// Splits the map into two at the given index.
366    ///
367    /// Returns a newly allocated map containing the key-value pairs in the range `[at, len)`.
368    /// After the call, the original map will be left containing the key-value pairs `[0, at)`
369    /// with its previous capacity unchanged.
370    ///
371    /// # Panics
372    ///
373    /// Panics if `at > len`.
374    ///
375    /// # Examples
376    ///
377    /// ```
378    /// use vecmap::VecMap;
379    ///
380    /// let mut map = VecMap::from([("a", 1), ("b", 2), ("c", 3)]);
381    /// let map2 = map.split_off(1);
382    /// assert_eq!(map, VecMap::from([("a", 1)]));
383    /// assert_eq!(map2, VecMap::from([("b", 2), ("c", 3)]));
384    /// ```
385    pub fn split_off(&mut self, at: usize) -> VecMap<K, V> {
386        VecMap {
387            base: self.base.split_off(at),
388        }
389    }
390
391    /// Search over a sorted map for a key.
392    ///
393    /// Returns the position where that key is present, or the position where it can be inserted to
394    /// maintain the sort. See [`slice::binary_search`] for more details.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// use vecmap::VecMap;
400    ///
401    /// let map = VecMap::from([("a", 1), ("b", 2), ("d", 4)]);
402    /// assert_eq!(map.binary_search_keys(&"b"), Ok(1));
403    /// assert_eq!(map.binary_search_keys(&"c"), Err(2));
404    /// assert_eq!(map.binary_search_keys(&"z"), Err(3));
405    /// ```
406    pub fn binary_search_keys(&self, key: &K) -> Result<usize, usize>
407    where
408        K: Ord,
409    {
410        self.binary_search_by(|k, _| k.cmp(key))
411    }
412
413    /// Search over a sorted map with a comparator function.
414    ///
415    /// Returns the position where that value is present, or the position where it can be inserted
416    /// to maintain the sort. See [`slice::binary_search_by`] for more details.
417    ///
418    /// # Examples
419    ///
420    /// ```
421    /// use vecmap::VecMap;
422    ///
423    /// let map = VecMap::from([("a", 1), ("b", 2), ("d", 4)]);
424    /// assert_eq!(map.binary_search_by(|k, _| k.cmp(&"b")), Ok(1));
425    /// assert_eq!(map.binary_search_by(|k, _| k.cmp(&"c")), Err(2));
426    /// assert_eq!(map.binary_search_by(|k, _| k.cmp(&"z")), Err(3));
427    /// assert_eq!(map.binary_search_by(|_, v| v.cmp(&4)), Ok(2));
428    /// ```
429    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
430    where
431        F: FnMut(&'a K, &'a V) -> Ordering,
432    {
433        self.as_slice().binary_search_by(|(k, v)| f(k, v))
434    }
435
436    /// Search over a sorted map with an extraction function.
437    ///
438    /// Returns the position where that value is present, or the position where it can be inserted
439    /// to maintain the sort. See [`slice::binary_search_by_key`] for more details.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// use vecmap::VecMap;
445    ///
446    /// let map = VecMap::from([("a", 1), ("b", 2), ("d", 4)]);
447    /// assert_eq!(map.binary_search_by_key(&"b", |&k, _| k), Ok(1));
448    /// assert_eq!(map.binary_search_by_key(&"c", |&k, _| k), Err(2));
449    /// assert_eq!(map.binary_search_by_key(&"z", |&k, _| k), Err(3));
450    /// assert_eq!(map.binary_search_by_key(&4, |_, &v| v), Ok(2));
451    /// ```
452    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
453    where
454        F: FnMut(&'a K, &'a V) -> B,
455        B: Ord,
456    {
457        self.as_slice().binary_search_by_key(b, |(k, v)| f(k, v))
458    }
459
460    /// Returns the index of the partition point of a sorted map according to the given predicate
461    /// (the index of the first element of the second partition).
462    ///
463    /// See [`slice::partition_point`] for more details.
464    ///
465    /// # Examples
466    ///
467    /// ```
468    /// use vecmap::VecMap;
469    ///
470    /// let map = VecMap::from([("a", 1), ("b", 2), ("d", 4)]);
471    /// assert_eq!(map.partition_point(|&k, _| k < "d"), 2);
472    /// assert_eq!(map.partition_point(|_, &v| v < 2), 1);
473    /// assert_eq!(map.partition_point(|_, &v| v > 100), 0);
474    /// assert_eq!(map.partition_point(|_, &v| v < 100), 3);
475    /// ```
476    pub fn partition_point<P>(&self, mut pred: P) -> usize
477    where
478        P: FnMut(&K, &V) -> bool,
479    {
480        self.as_slice().partition_point(|(k, v)| pred(k, v))
481    }
482
483    /// Removes the specified range from the vector in bulk, returning all removed elements as an
484    /// iterator. If the iterator is dropped before being fully consumed, it drops the remaining
485    /// removed elements.
486    ///
487    /// The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
488    ///
489    /// # Panics
490    ///
491    /// Panics if the starting point is greater than the end point or if the end point is greater
492    /// than the length of the vector.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// use vecmap::{vecmap, VecMap};
498    ///
499    /// let mut v = vecmap!["a" => 1, "b" => 2, "c" => 3];
500    /// let u: VecMap<_, _> = v.drain(1..).collect();
501    /// assert_eq!(v, vecmap!["a" => 1]);
502    /// assert_eq!(u, vecmap!["b" => 2, "c" => 3]);
503    ///
504    /// // A full range clears the vector, like `clear()` does
505    /// v.drain(..);
506    /// assert_eq!(v, vecmap![]);
507    /// ```
508    pub fn drain<R>(&mut self, range: R) -> Drain<'_, K, V>
509    where
510        R: RangeBounds<usize>,
511    {
512        Drain::new(self, range)
513    }
514
515    // Push a key-value pair at the end of the `VecMap` without checking whether the key already
516    // exists.
517    fn push(&mut self, key: K, value: V) -> usize {
518        let index = self.base.len();
519        self.base.push(Slot::new(key, value));
520        index
521    }
522
523    /// Sorts the map by key.
524    ///
525    /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*))
526    /// worst-case.
527    ///
528    /// When applicable, unstable sorting is preferred because it is generally faster than stable
529    /// sorting and it doesn't allocate auxiliary memory. See
530    /// [`sort_unstable_keys`](VecMap::sort_unstable_keys).
531    ///
532    /// # Examples
533    ///
534    /// ```
535    /// use vecmap::VecMap;
536    ///
537    /// let mut map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
538    ///
539    /// map.sort_keys();
540    /// let vec: Vec<_> = map.into_iter().collect();
541    /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
542    /// ```
543    pub fn sort_keys(&mut self)
544    where
545        K: Ord,
546    {
547        self.base.sort_by(|a, b| a.key().cmp(b.key()));
548    }
549
550    /// Sorts the map by key.
551    ///
552    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
553    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
554    ///
555    /// # Examples
556    ///
557    /// ```
558    /// use vecmap::VecMap;
559    ///
560    /// let mut map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
561    ///
562    /// map.sort_unstable_keys();
563    /// assert_eq!(map.as_slice(), [("a", 1), ("b", 2), ("c", 3)]);
564    /// ```
565    pub fn sort_unstable_keys(&mut self)
566    where
567        K: Ord,
568    {
569        self.base.sort_unstable_by(|a, b| a.key().cmp(b.key()));
570    }
571
572    /// Sorts the map with a comparator function.
573    ///
574    /// This sort is stable (i.e., does not reorder equal elements) and *O*(*n* \* log(*n*))
575    /// worst-case.
576    ///
577    /// # Examples
578    ///
579    ///
580    /// ```
581    /// use vecmap::VecMap;
582    ///
583    /// let mut map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
584    ///
585    /// map.sort_by(|(k1, _), (k2, _)| k2.cmp(&k1));
586    /// let vec: Vec<_> = map.into_iter().collect();
587    /// assert_eq!(vec, [("c", 3), ("b", 2), ("a", 1)]);
588    /// ```
589    pub fn sort_by<F>(&mut self, mut compare: F)
590    where
591        F: FnMut((&K, &V), (&K, &V)) -> Ordering,
592    {
593        self.base.sort_by(|a, b| compare(a.refs(), b.refs()));
594    }
595
596    /// Sorts the map with a comparator function.
597    ///
598    /// This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not
599    /// allocate), and *O*(*n* \* log(*n*)) worst-case.
600    ///
601    /// # Examples
602    ///
603    /// ```
604    /// use vecmap::VecMap;
605    ///
606    /// let mut map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
607    ///
608    /// map.sort_unstable_by(|(k1, _), (k2, _)| k2.cmp(&k1));
609    /// let vec: Vec<_> = map.into_iter().collect();
610    /// assert_eq!(vec, [("c", 3), ("b", 2), ("a", 1)]);
611    /// ```
612    pub fn sort_unstable_by<F>(&mut self, mut compare: F)
613    where
614        F: FnMut((&K, &V), (&K, &V)) -> Ordering,
615    {
616        self.base
617            .sort_unstable_by(|a, b| compare(a.refs(), b.refs()));
618    }
619
620    /// Sort the map’s key-value pairs in place using a sort-key extraction function.
621    ///
622    /// During sorting, the function is called at most once per entry, by using temporary storage
623    /// to remember the results of its evaluation. The order of calls to the function is
624    /// unspecified and may change between versions of `vecmap-rs` or the standard library.
625    ///
626    /// See [`slice::sort_by_cached_key`] for more details.
627    ///
628    /// # Examples
629    ///
630    /// ```
631    /// use vecmap::VecMap;
632    ///
633    /// let mut map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
634    ///
635    /// map.sort_by_cached_key(|_, v| v.to_string());
636    /// let vec: Vec<_> = map.into_iter().collect();
637    /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
638    /// ```
639    pub fn sort_by_cached_key<T, F>(&mut self, mut sort_key: F)
640    where
641        T: Ord,
642        F: FnMut(&K, &V) -> T,
643    {
644        self.base
645            .sort_by_cached_key(|a| sort_key(a.key(), a.value()));
646    }
647
648    /// Extracts a slice containing the map entries.
649    ///
650    /// ```
651    /// use vecmap::VecMap;
652    ///
653    /// let map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
654    /// let slice = map.as_slice();
655    /// assert_eq!(slice, [("b", 2), ("a", 1), ("c", 3)]);
656    /// ```
657    pub fn as_slice(&self) -> &[(K, V)] {
658        // SAFETY: `&[Slot<K, V>]` and `&[(K, V)]` have the same memory layout.
659        unsafe { &*(ptr::from_ref::<[Slot<K, V>]>(self.base.as_slice()) as *const [(K, V)]) }
660    }
661
662    /// Copies the map entries into a new `Vec<(K, V)>`.
663    ///
664    /// ```
665    /// use vecmap::VecMap;
666    ///
667    /// let map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
668    /// let vec = map.to_vec();
669    /// assert_eq!(vec, [("b", 2), ("a", 1), ("c", 3)]);
670    /// // Here, `map` and `vec` can be modified independently.
671    /// ```
672    pub fn to_vec(&self) -> Vec<(K, V)>
673    where
674        K: Clone,
675        V: Clone,
676    {
677        self.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
678    }
679
680    /// Takes ownership of the map and returns its entries as a `Vec<(K, V)>`.
681    ///
682    /// ```
683    /// use vecmap::VecMap;
684    ///
685    /// let map = VecMap::from([("b", 2), ("a", 1), ("c", 3)]);
686    /// let vec = map.into_vec();
687    /// assert_eq!(vec, [("b", 2), ("a", 1), ("c", 3)]);
688    /// ```
689    pub fn into_vec(self) -> Vec<(K, V)> {
690        // SAFETY: `Vec<Slot<K, V>>` and `Vec<(K, V)>` have the same memory layout.
691        unsafe { super::transmute_vec(self.base) }
692    }
693
694    /// Takes ownership of provided vector and converts it into `VecMap`.
695    ///
696    /// # Safety
697    ///
698    /// The vector must have no duplicate keys. One way to guarantee it is to
699    /// sort the vector (e.g. by using [`[T]::sort_by_key`][slice-sort-by-key]) and then drop
700    /// duplicate keys (e.g. by using [`Vec::dedup_by_key`]).
701    ///
702    /// # Example
703    ///
704    /// ```
705    /// use vecmap::VecMap;
706    ///
707    /// let mut vec = vec![("b", 2), ("a", 1), ("c", 3), ("b", 4)];
708    /// vec.sort_by_key(|slot| slot.0);
709    /// vec.dedup_by_key(|slot| slot.0);
710    /// // SAFETY: We've just deduplicated the vector.
711    /// let map = unsafe { VecMap::from_vec_unchecked(vec) };
712    ///
713    /// assert_eq!(map, VecMap::from([("b", 2), ("a", 1), ("c", 3)]));
714    /// ```
715    ///
716    /// [slice-sort-by-key]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_key
717    pub unsafe fn from_vec_unchecked(vec: Vec<(K, V)>) -> Self {
718        // SAFETY: `Vec<(K, V)>` and `Vec<Slot<K, V>>` have the same memory layout.
719        let base = unsafe { super::transmute_vec(vec) };
720        VecMap { base }
721    }
722}
723
724// Lookup operations.
725impl<K, V> VecMap<K, V> {
726    /// Return `true` if an equivalent to `key` exists in the map.
727    ///
728    /// # Examples
729    ///
730    /// ```
731    /// use vecmap::VecMap;
732    ///
733    /// let mut map = VecMap::new();
734    /// map.insert(1, "a");
735    /// assert_eq!(map.contains_key(&1), true);
736    /// assert_eq!(map.contains_key(&2), false);
737    /// ```
738    pub fn contains_key<Q>(&self, key: &Q) -> bool
739    where
740        K: Borrow<Q>,
741        Q: Eq + ?Sized,
742    {
743        self.get_index_of(key).is_some()
744    }
745
746    /// Get the first key-value pair.
747    ///
748    /// ```
749    /// use vecmap::VecMap;
750    ///
751    /// let mut map = VecMap::from_iter([("a", 1), ("b", 2)]);
752    /// assert_eq!(map.first(), Some((&"a", &1)));
753    /// ```
754    pub fn first(&self) -> Option<(&K, &V)> {
755        self.base.first().map(Slot::refs)
756    }
757
758    /// Get the first key-value pair, with mutable access to the value.
759    ///
760    /// # Examples
761    ///
762    /// ```
763    /// use vecmap::VecMap;
764    ///
765    /// let mut map = VecMap::from_iter([("a", 1), ("b", 2)]);
766    ///
767    /// if let Some((_, v)) = map.first_mut() {
768    ///     *v = *v + 10;
769    /// }
770    /// assert_eq!(map.first(), Some((&"a", &11)));
771    /// ```
772    pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
773        self.base.first_mut().map(Slot::ref_mut)
774    }
775
776    /// Get the last key-value pair.
777    ///
778    /// # Examples
779    ///
780    /// ```
781    /// use vecmap::VecMap;
782    ///
783    /// let mut map = VecMap::from_iter([("a", 1), ("b", 2)]);
784    /// assert_eq!(map.last(), Some((&"b", &2)));
785    /// map.pop();
786    /// map.pop();
787    /// assert_eq!(map.last(), None);
788    /// ```
789    pub fn last(&self) -> Option<(&K, &V)> {
790        self.base.last().map(Slot::refs)
791    }
792
793    /// Get the last key-value pair, with mutable access to the value.
794    ///
795    /// # Examples
796    ///
797    /// ```
798    /// use vecmap::VecMap;
799    ///
800    /// let mut map = VecMap::from_iter([("a", 1), ("b", 2)]);
801    ///
802    /// if let Some((_, v)) = map.last_mut() {
803    ///     *v = *v + 10;
804    /// }
805    /// assert_eq!(map.last(), Some((&"b", &12)));
806    /// ```
807    pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
808        self.base.last_mut().map(Slot::ref_mut)
809    }
810
811    /// Return a reference to the value stored for `key`, if it is present, else `None`.
812    ///
813    /// # Examples
814    ///
815    /// ```
816    /// use vecmap::VecMap;
817    ///
818    /// let mut map = VecMap::new();
819    /// map.insert(1, "a");
820    /// assert_eq!(map.get(&1), Some(&"a"));
821    /// assert_eq!(map.get(&2), None);
822    /// ```
823    pub fn get<Q>(&self, key: &Q) -> Option<&V>
824    where
825        K: Borrow<Q>,
826        Q: Eq + ?Sized,
827    {
828        self.get_index_of(key).map(|index| self.base[index].value())
829    }
830
831    /// Return a mutable reference to the value stored for `key`, if it is present, else `None`.
832    ///
833    /// # Examples
834    ///
835    /// ```
836    /// use vecmap::VecMap;
837    ///
838    /// let mut map = VecMap::new();
839    /// map.insert(1, "a");
840    /// if let Some(x) = map.get_mut(&1) {
841    ///     *x = "b";
842    /// }
843    /// assert_eq!(map[&1], "b");
844    /// ```
845    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
846    where
847        K: Borrow<Q>,
848        Q: Eq + ?Sized,
849    {
850        self.get_index_of(key)
851            .map(|index| self.base[index].value_mut())
852    }
853
854    /// Return references to the key-value pair stored at `index`, if it is present, else `None`.
855    ///
856    /// # Examples
857    ///
858    /// ```
859    /// use vecmap::VecMap;
860    ///
861    /// let mut map = VecMap::new();
862    /// map.insert(1, "a");
863    /// assert_eq!(map.get_index(0), Some((&1, &"a")));
864    /// assert_eq!(map.get_index(1), None);
865    /// ```
866    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
867        self.base.get(index).map(Slot::refs)
868    }
869
870    /// Return a reference to the key and a mutable reference to the value stored at `index`, if it
871    /// is present, else `None`.
872    ///
873    /// # Examples
874    ///
875    /// ```
876    /// use vecmap::VecMap;
877    ///
878    /// let mut map = VecMap::new();
879    /// map.insert(1, "a");
880    /// if let Some((_, v)) = map.get_index_mut(0) {
881    ///     *v = "b";
882    /// }
883    /// assert_eq!(map[0], "b");
884    /// ```
885    pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
886        self.base.get_mut(index).map(Slot::ref_mut)
887    }
888
889    /// Return the index and references to the key-value pair stored for `key`, if it is present,
890    /// else `None`.
891    ///
892    /// # Examples
893    ///
894    /// ```
895    /// use vecmap::VecMap;
896    ///
897    /// let mut map = VecMap::new();
898    /// map.insert(1, "a");
899    /// assert_eq!(map.get_full(&1), Some((0, &1, &"a")));
900    /// assert_eq!(map.get_full(&2), None);
901    /// ```
902    pub fn get_full<Q>(&self, key: &Q) -> Option<(usize, &K, &V)>
903    where
904        K: Borrow<Q>,
905        Q: Eq + ?Sized,
906    {
907        self.get_index_of(key).map(|index| {
908            let (key, value) = self.base[index].refs();
909            (index, key, value)
910        })
911    }
912
913    /// Return the index, a reference to the key and a mutable reference to the value stored for
914    /// `key`, if it is present, else `None`.
915    ///
916    /// # Examples
917    ///
918    /// ```
919    /// use vecmap::VecMap;
920    ///
921    /// let mut map = VecMap::new();
922    /// map.insert(1, "a");
923    ///
924    /// if let Some((_, _, v)) = map.get_full_mut(&1) {
925    ///     *v = "b";
926    /// }
927    /// assert_eq!(map.get(&1), Some(&"b"));
928    /// ```
929    pub fn get_full_mut<Q>(&mut self, key: &Q) -> Option<(usize, &K, &mut V)>
930    where
931        K: Borrow<Q>,
932        Q: Eq + ?Sized,
933    {
934        self.get_index_of(key).map(|index| {
935            let (key, value) = self.base[index].ref_mut();
936            (index, key, value)
937        })
938    }
939
940    /// Return references to the key-value pair stored for `key`, if it is present, else `None`.
941    ///
942    /// # Examples
943    ///
944    /// ```
945    /// use vecmap::VecMap;
946    ///
947    /// let mut map = VecMap::new();
948    /// map.insert(1, "a");
949    /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
950    /// assert_eq!(map.get_key_value(&2), None);
951    /// ```
952    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
953    where
954        K: Borrow<Q>,
955        Q: Eq + ?Sized,
956    {
957        self.get_index_of(key).map(|index| self.base[index].refs())
958    }
959
960    /// Return item index, if it exists in the map.
961    ///
962    /// # Examples
963    ///
964    /// ```
965    /// use vecmap::VecMap;
966    ///
967    /// let mut map = VecMap::new();
968    /// map.insert("a", 10);
969    /// map.insert("b", 20);
970    /// assert_eq!(map.get_index_of("a"), Some(0));
971    /// assert_eq!(map.get_index_of("b"), Some(1));
972    /// assert_eq!(map.get_index_of("c"), None);
973    /// ```
974    pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
975    where
976        K: Borrow<Q>,
977        Q: Eq + ?Sized,
978    {
979        if self.base.is_empty() {
980            return None;
981        }
982
983        self.base.iter().position(|slot| slot.key().borrow() == key)
984    }
985}
986
987// Removal operations.
988impl<K, V> VecMap<K, V> {
989    /// Removes the last element from the map and returns it, or [`None`] if it
990    /// is empty.
991    ///
992    /// # Examples
993    ///
994    /// ```
995    /// use vecmap::VecMap;
996    ///
997    /// let mut map = VecMap::from_iter([("a", 1), ("b", 2)]);
998    /// assert_eq!(map.pop(), Some(("b", 2)));
999    /// assert_eq!(map.pop(), Some(("a", 1)));
1000    /// assert!(map.is_empty());
1001    /// assert_eq!(map.pop(), None);
1002    /// ```
1003    pub fn pop(&mut self) -> Option<(K, V)> {
1004        self.base.pop().map(Slot::into_key_value)
1005    }
1006
1007    /// Remove the key-value pair equivalent to `key` and return its value.
1008    ///
1009    /// Like `Vec::remove`, the pair is removed by shifting all of the elements that follow it,
1010    /// preserving their relative order. **This perturbs the index of all of those elements!**
1011    ///
1012    /// # Examples
1013    ///
1014    /// ```
1015    /// use vecmap::VecMap;
1016    ///
1017    /// let mut map = VecMap::from_iter([(1, "a"), (2, "b"), (3, "c"), (4, "d")]);
1018    /// assert_eq!(map.remove(&2), Some("b"));
1019    /// assert_eq!(map.remove(&2), None);
1020    /// assert_eq!(map, VecMap::from_iter([(1, "a"), (3, "c"), (4, "d")]));
1021    /// ```
1022    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
1023    where
1024        K: Borrow<Q>,
1025        Q: Eq + ?Sized,
1026    {
1027        self.get_index_of(key)
1028            .map(|index| self.remove_index(index).1)
1029    }
1030
1031    /// Remove and return the key-value pair equivalent to `key`.
1032    ///
1033    /// Like `Vec::remove`, the pair is removed by shifting all of the elements that follow it,
1034    /// preserving their relative order. **This perturbs the index of all of those elements!**
1035    ///
1036    /// # Examples
1037    ///
1038    /// ```
1039    /// use vecmap::VecMap;
1040    ///
1041    /// let mut map = VecMap::from_iter([(1, "a"), (2, "b"), (3, "c"), (4, "d")]);
1042    /// assert_eq!(map.remove_entry(&2), Some((2, "b")));
1043    /// assert_eq!(map.remove_entry(&2), None);
1044    /// assert_eq!(map, VecMap::from_iter([(1, "a"), (3, "c"), (4, "d")]));
1045    /// ```
1046    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1047    where
1048        K: Borrow<Q>,
1049        Q: Eq + ?Sized,
1050    {
1051        self.get_index_of(key).map(|index| self.remove_index(index))
1052    }
1053
1054    /// Removes and returns the key-value pair at position `index` within the map, shifting all
1055    /// elements after it to the left.
1056    ///
1057    /// If you don't need the order of elements to be preserved, use [`swap_remove`] instead.
1058    ///
1059    /// [`swap_remove`]: VecMap::swap_remove
1060    ///
1061    /// # Panics
1062    ///
1063    /// Panics if `index` is out of bounds.
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```
1068    /// use vecmap::VecMap;
1069    ///
1070    /// let mut v = VecMap::from([("a", 1), ("b", 2), ("c", 3)]);
1071    /// assert_eq!(v.remove_index(1), ("b", 2));
1072    /// assert_eq!(v, VecMap::from([("a", 1), ("c", 3)]));
1073    /// ```
1074    pub fn remove_index(&mut self, index: usize) -> (K, V) {
1075        self.base.remove(index).into_key_value()
1076    }
1077
1078    /// Remove the key-value pair equivalent to `key` and return its value.
1079    ///
1080    /// Like `Vec::swap_remove`, the pair is removed by swapping it with the last element of the
1081    /// map and popping it off. **This perturbs the position of what used to be the last element!**
1082    ///
1083    /// Return `None` if `key` is not in map.
1084    ///
1085    /// ```
1086    /// use vecmap::VecMap;
1087    ///
1088    /// let mut map = VecMap::from_iter([(1, "a"), (2, "b"), (3, "c"), (4, "d")]);
1089    /// assert_eq!(map.swap_remove(&2), Some("b"));
1090    /// assert_eq!(map.swap_remove(&2), None);
1091    /// assert_eq!(map, VecMap::from_iter([(1, "a"), (4, "d"), (3, "c")]));
1092    /// ```
1093    pub fn swap_remove<Q>(&mut self, key: &Q) -> Option<V>
1094    where
1095        K: Borrow<Q>,
1096        Q: Eq + ?Sized,
1097    {
1098        self.get_index_of(key)
1099            .map(|index| self.swap_remove_index(index).1)
1100    }
1101
1102    /// Remove and return the key-value pair equivalent to `key`.
1103    ///
1104    /// Like `Vec::swap_remove`, the pair is removed by swapping it with the last element of the
1105    /// map and popping it off. **This perturbs the position of what used to be the last element!**
1106    ///
1107    /// Return `None` if `key` is not in map.
1108    ///
1109    /// ```
1110    /// use vecmap::VecMap;
1111    ///
1112    /// let mut map = VecMap::from_iter([(1, "a"), (2, "b"), (3, "c"), (4, "d")]);
1113    /// assert_eq!(map.swap_remove_entry(&2), Some((2, "b")));
1114    /// assert_eq!(map.swap_remove_entry(&2), None);
1115    /// assert_eq!(map, VecMap::from_iter([(1, "a"), (4, "d"), (3, "c")]));
1116    /// ```
1117    pub fn swap_remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
1118    where
1119        K: Borrow<Q>,
1120        Q: Eq + ?Sized,
1121    {
1122        self.get_index_of(key)
1123            .map(|index| self.swap_remove_index(index))
1124    }
1125
1126    /// Removes a key-value pair from the map and returns it.
1127    ///
1128    /// The removed key-value pair is replaced by the last key-value pair of the map.
1129    ///
1130    /// If you need to preserve the element order, use [`remove`] instead.
1131    ///
1132    /// [`remove`]: VecMap::remove
1133    ///
1134    /// # Panics
1135    ///
1136    /// Panics if `index` is out of bounds.
1137    ///
1138    /// # Examples
1139    ///
1140    /// ```
1141    /// use vecmap::VecMap;
1142    ///
1143    /// let mut v = VecMap::from([("foo", 1), ("bar", 2), ("baz", 3), ("qux", 4)]);
1144    ///
1145    /// assert_eq!(v.swap_remove_index(0), ("foo", 1));
1146    /// assert_eq!(v, VecMap::from([("qux", 4), ("bar", 2), ("baz", 3)]));
1147    ///
1148    /// assert_eq!(v.swap_remove_index(0), ("qux", 4));
1149    /// assert_eq!(v, VecMap::from([("baz", 3), ("bar", 2)]));
1150    /// ```
1151    pub fn swap_remove_index(&mut self, index: usize) -> (K, V) {
1152        self.base.swap_remove(index).into_key_value()
1153    }
1154
1155    /// Swaps the position of two key-value pairs in the map.
1156    ///
1157    /// # Arguments
1158    ///
1159    /// * a - The index of the first element
1160    /// * b - The index of the second element
1161    ///
1162    /// # Panics
1163    ///
1164    /// Panics if `a` or `b` are out of bounds.
1165    ///
1166    /// # Examples
1167    ///
1168    /// ```
1169    /// use vecmap::VecMap;
1170    ///
1171    /// let mut map = VecMap::from([("a", 1), ("b", 2), ("c", 3), ("d", 4)]);
1172    /// map.swap_indices(1, 3);
1173    /// assert_eq!(map.to_vec(), [("a", 1), ("d", 4), ("c", 3), ("b", 2)]);
1174    /// ```
1175    pub fn swap_indices(&mut self, a: usize, b: usize) {
1176        self.base.swap(a, b);
1177    }
1178}
1179
1180// Insertion operations.
1181impl<K, V> VecMap<K, V>
1182where
1183    K: Eq,
1184{
1185    /// Insert a key-value pair in the map.
1186    ///
1187    /// If an equivalent key already exists in the map: the key remains and retains in its place
1188    /// in the order, its corresponding value is updated with `value` and the older value is
1189    /// returned inside `Some(_)`.
1190    ///
1191    /// If no equivalent key existed in the map: the new key-value pair is inserted, last in
1192    /// order, and `None` is returned.
1193    ///
1194    /// See also [`entry`](#method.entry) if you you want to insert *or* modify or if you need to
1195    /// get the index of the corresponding key-value pair.
1196    ///
1197    /// # Examples
1198    ///
1199    /// ```
1200    /// use vecmap::VecMap;
1201    ///
1202    /// let mut map = VecMap::new();
1203    /// assert_eq!(map.insert(37, "a"), None);
1204    /// assert_eq!(map.is_empty(), false);
1205    ///
1206    /// map.insert(37, "b");
1207    /// assert_eq!(map.insert(37, "c"), Some("b"));
1208    /// assert_eq!(map[&37], "c");
1209    /// ```
1210    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
1211        self.insert_full(key, value).1
1212    }
1213
1214    /// Insert a key-value pair in the map, and get their index.
1215    ///
1216    /// If an equivalent key already exists in the map: the key remains and
1217    /// retains in its place in the order, its corresponding value is updated
1218    /// with `value` and the older value is returned inside `(index, Some(_))`.
1219    ///
1220    /// If no equivalent key existed in the map: the new key-value pair is
1221    /// inserted, last in order, and `(index, None)` is returned.
1222    ///
1223    /// See also [`entry`](#method.entry) if you you want to insert *or* modify
1224    /// or if you need to get the index of the corresponding key-value pair.
1225    ///
1226    /// # Examples
1227    ///
1228    /// ```
1229    /// use vecmap::VecMap;
1230    ///
1231    /// let mut map = VecMap::new();
1232    /// assert_eq!(map.insert_full("a", 1), (0, None));
1233    /// assert_eq!(map.insert_full("b", 2), (1, None));
1234    /// assert_eq!(map.insert_full("b", 3), (1, Some(2)));
1235    /// assert_eq!(map["b"], 3);
1236    /// ```
1237    pub fn insert_full(&mut self, key: K, value: V) -> (usize, Option<V>) {
1238        match self.get_index_of(&key) {
1239            Some(index) => {
1240                let old_slot = mem::replace(&mut self.base[index], Slot::new(key, value));
1241                (index, Some(old_slot.into_value()))
1242            }
1243            None => (self.push(key, value), None),
1244        }
1245    }
1246
1247    /// Insert a key-value pair at position `index` within the map, shifting all
1248    /// elements after it to the right.
1249    ///
1250    /// If an equivalent key already exists in the map: the key is removed from the map and the new
1251    /// key-value pair is inserted at `index`. The old index and its value are returned inside
1252    /// `Some((usize, _))`.
1253    ///
1254    /// If no equivalent key existed in the map: the new key-value pair is
1255    /// inserted at position `index` and `None` is returned.
1256    ///
1257    /// # Panics
1258    ///
1259    /// Panics if `index > len`.
1260    ///
1261    /// # Examples
1262    ///
1263    /// ```
1264    /// use vecmap::VecMap;
1265    ///
1266    /// let mut map = VecMap::new();
1267    /// assert_eq!(map.insert_at(0, "a", 1), None);
1268    /// assert_eq!(map.insert_at(1, "b", 2), None);
1269    /// assert_eq!(map.insert_at(0, "b", 3), Some((1, 2)));
1270    /// assert_eq!(map.to_vec(), [("b", 3), ("a", 1)]);
1271    /// ```
1272    pub fn insert_at(&mut self, index: usize, key: K, value: V) -> Option<(usize, V)> {
1273        if let Some(old_index) = self.get_index_of(&key) {
1274            let old_slot = if old_index == index {
1275                mem::replace(&mut self.base[index], Slot::new(key, value))
1276            } else {
1277                let old_slot = self.base.remove(old_index);
1278                self.base.insert(index, Slot::new(key, value));
1279                old_slot
1280            };
1281
1282            Some((old_index, old_slot.into_value()))
1283        } else {
1284            self.base.insert(index, Slot::new(key, value));
1285            None
1286        }
1287    }
1288
1289    /// Get the given key's corresponding entry in the map for insertion and/or in-place
1290    /// manipulation.
1291    ///
1292    /// ## Examples
1293    ///
1294    /// ```
1295    /// use vecmap::VecMap;
1296    ///
1297    /// let mut letters = VecMap::new();
1298    ///
1299    /// for ch in "a short treatise on fungi".chars() {
1300    ///     letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
1301    /// }
1302    ///
1303    /// assert_eq!(letters[&'s'], 2);
1304    /// assert_eq!(letters[&'t'], 3);
1305    /// assert_eq!(letters[&'u'], 1);
1306    /// assert_eq!(letters.get(&'y'), None);
1307    /// ```
1308    pub fn entry(&mut self, key: K) -> Entry<K, V> {
1309        match self.get_index_of(&key) {
1310            Some(index) => Entry::Occupied(OccupiedEntry::new(self, key, index)),
1311            None => Entry::Vacant(VacantEntry::new(self, key)),
1312        }
1313    }
1314
1315    /// Moves all key-value pairs from `other` into `self`, leaving `other` empty.
1316    ///
1317    /// This is equivalent to calling [`insert`][Self::insert] for each key-value pair from `other`
1318    /// in order, which means that for keys that already exist in `self`, their value is updated in
1319    /// the current position.
1320    ///
1321    /// # Examples
1322    ///
1323    /// ```
1324    /// use vecmap::VecMap;
1325    ///
1326    /// // Note: Key (3) is present in both maps.
1327    /// let mut a = VecMap::from([(3, "c"), (2, "b"), (1, "a")]);
1328    /// let mut b = VecMap::from([(3, "d"), (4, "e"), (5, "f")]);
1329    /// let old_capacity = b.capacity();
1330    ///
1331    /// a.append(&mut b);
1332    ///
1333    /// assert_eq!(a.len(), 5);
1334    /// assert_eq!(b.len(), 0);
1335    /// assert_eq!(b.capacity(), old_capacity);
1336    ///
1337    /// assert!(a.keys().eq(&[3, 2, 1, 4, 5]));
1338    /// assert_eq!(a[&3], "d"); // "c" was overwritten.
1339    /// ```
1340    pub fn append(&mut self, other: &mut VecMap<K, V>) {
1341        self.extend(other.drain(..));
1342    }
1343}
1344
1345// Iterator adapters.
1346impl<K, V> VecMap<K, V> {
1347    /// An iterator visiting all key-value pairs in insertion order. The iterator element type is
1348    /// `(&'a K, &'a V)`.
1349    ///
1350    /// # Examples
1351    ///
1352    /// ```
1353    /// use vecmap::VecMap;
1354    ///
1355    /// let map = VecMap::from([
1356    ///     ("a", 1),
1357    ///     ("b", 2),
1358    ///     ("c", 3),
1359    /// ]);
1360    ///
1361    /// for (key, val) in map.iter() {
1362    ///     println!("key: {key} val: {val}");
1363    /// }
1364    /// ```
1365    pub fn iter(&self) -> Iter<'_, K, V> {
1366        Iter::new(self.as_entries())
1367    }
1368
1369    /// An iterator visiting all key-value pairs in insertion order, with mutable references to the
1370    /// values. The iterator element type is `(&'a K, &'a mut V)`.
1371    ///
1372    /// # Examples
1373    ///
1374    /// ```
1375    /// use vecmap::VecMap;
1376    ///
1377    /// let mut map = VecMap::from([
1378    ///     ("a", 1),
1379    ///     ("b", 2),
1380    ///     ("c", 3),
1381    /// ]);
1382    ///
1383    /// // Update all values
1384    /// for (_, val) in map.iter_mut() {
1385    ///     *val *= 2;
1386    /// }
1387    ///
1388    /// for (key, val) in &map {
1389    ///     println!("key: {key} val: {val}");
1390    /// }
1391    /// ```
1392    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
1393        IterMut::new(self.as_entries_mut())
1394    }
1395
1396    /// An iterator visiting all keys in insertion order. The iterator element type is `&'a K`.
1397    ///
1398    /// # Examples
1399    ///
1400    /// ```
1401    /// use vecmap::VecMap;
1402    ///
1403    /// let map = VecMap::from([
1404    ///     ("a", 1),
1405    ///     ("b", 2),
1406    ///     ("c", 3),
1407    /// ]);
1408    ///
1409    /// for key in map.keys() {
1410    ///     println!("{key}");
1411    /// }
1412    /// ```
1413    pub fn keys(&self) -> Keys<'_, K, V> {
1414        Keys::new(self.as_entries())
1415    }
1416
1417    /// Creates a consuming iterator visiting all the keys in insertion order. The object cannot be
1418    /// used after calling this. The iterator element type is `K`.
1419    ///
1420    /// # Examples
1421    ///
1422    /// ```
1423    /// use vecmap::VecMap;
1424    ///
1425    /// let map = VecMap::from([
1426    ///     ("a", 1),
1427    ///     ("b", 2),
1428    ///     ("c", 3),
1429    /// ]);
1430    ///
1431    /// let mut vec: Vec<&str> = map.into_keys().collect();
1432    /// assert_eq!(vec, ["a", "b", "c"]);
1433    /// ```
1434    pub fn into_keys(self) -> IntoKeys<K, V> {
1435        IntoKeys::new(self.into_entries())
1436    }
1437
1438    /// An iterator visiting all values in insertion order. The iterator element type is `&'a V`.
1439    ///
1440    /// # Examples
1441    ///
1442    /// ```
1443    /// use vecmap::VecMap;
1444    ///
1445    /// let map = VecMap::from([
1446    ///     ("a", 1),
1447    ///     ("b", 2),
1448    ///     ("c", 3),
1449    /// ]);
1450    ///
1451    /// for val in map.values() {
1452    ///     println!("{val}");
1453    /// }
1454    /// ```
1455    pub fn values(&self) -> Values<'_, K, V> {
1456        Values::new(self.as_entries())
1457    }
1458
1459    /// An iterator visiting all values mutably in insertion order. The iterator element type is
1460    /// `&'a mut V`.
1461    ///
1462    /// # Examples
1463    ///
1464    /// ```
1465    /// use vecmap::VecMap;
1466    ///
1467    /// let mut map = VecMap::from([
1468    ///     ("a", 1),
1469    ///     ("b", 2),
1470    ///     ("c", 3),
1471    /// ]);
1472    ///
1473    /// for val in map.values_mut() {
1474    ///     *val = *val + 10;
1475    /// }
1476    ///
1477    /// for val in map.values() {
1478    ///     println!("{val}");
1479    /// }
1480    /// ```
1481    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
1482        ValuesMut::new(self.as_entries_mut())
1483    }
1484
1485    /// Creates a consuming iterator visiting all the values in insertion order. The object cannot
1486    /// be used after calling this. The iterator element type is `V`.
1487    ///
1488    /// # Examples
1489    ///
1490    /// ```
1491    /// use vecmap::VecMap;
1492    ///
1493    /// let map = VecMap::from([
1494    ///     ("a", 1),
1495    ///     ("b", 2),
1496    ///     ("c", 3),
1497    /// ]);
1498    ///
1499    /// let mut vec: Vec<i32> = map.into_values().collect();
1500    /// assert_eq!(vec, [1, 2, 3]);
1501    /// ```
1502    pub fn into_values(self) -> IntoValues<K, V> {
1503        IntoValues::new(self.into_entries())
1504    }
1505}
1506
1507impl<K, V> Entries for VecMap<K, V> {
1508    type Entry = Slot<K, V>;
1509
1510    fn as_entries(&self) -> &[Self::Entry] {
1511        &self.base
1512    }
1513
1514    fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
1515        &mut self.base
1516    }
1517
1518    fn into_entries(self) -> Vec<Self::Entry> {
1519        self.base
1520    }
1521}