Skip to main content

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