vec_map/
lib.rs

1// Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#![deny(missing_docs)]
12
13//! A simple map based on a vector for small integer keys. Space requirements
14//! are O(highest integer key).
15
16// optional serde support
17#[cfg(feature = "serde")]
18#[macro_use]
19extern crate serde;
20
21use self::Entry::*;
22
23use std::cmp::{Ordering, max};
24use std::fmt;
25use std::hash::{Hash, Hasher};
26use std::iter::{Enumerate, FilterMap, FromIterator};
27use std::mem::{replace, swap};
28use std::ops::{Index, IndexMut};
29use std::slice;
30use std::vec;
31
32/// A map optimized for small integer keys.
33///
34/// # Examples
35///
36/// ```
37/// use vec_map::VecMap;
38///
39/// let mut months = VecMap::new();
40/// months.insert(1, "Jan");
41/// months.insert(2, "Feb");
42/// months.insert(3, "Mar");
43///
44/// if !months.contains_key(12) {
45///     println!("The end is near!");
46/// }
47///
48/// assert_eq!(months.get(1), Some(&"Jan"));
49///
50/// if let Some(value) = months.get_mut(3) {
51///     *value = "Venus";
52/// }
53///
54/// assert_eq!(months.get(3), Some(&"Venus"));
55///
56/// // Print out all months
57/// for (key, value) in &months {
58///     println!("month {} is {}", key, value);
59/// }
60///
61/// months.clear();
62/// assert!(months.is_empty());
63/// ```
64#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
65pub struct VecMap<V> {
66    n: usize,
67    v: Vec<Option<V>>,
68}
69
70/// A view into a single entry in a map, which may either be vacant or occupied.
71pub enum Entry<'a, V: 'a> {
72    /// A vacant Entry
73    Vacant(VacantEntry<'a, V>),
74
75    /// An occupied Entry
76    Occupied(OccupiedEntry<'a, V>),
77}
78
79/// A vacant Entry.
80pub struct VacantEntry<'a, V: 'a> {
81    map: &'a mut VecMap<V>,
82    index: usize,
83}
84
85/// An occupied Entry.
86pub struct OccupiedEntry<'a, V: 'a> {
87    map: &'a mut VecMap<V>,
88    index: usize,
89}
90
91impl<V> Default for VecMap<V> {
92    #[inline]
93    fn default() -> Self { Self::new() }
94}
95
96impl<V: Hash> Hash for VecMap<V> {
97    fn hash<H: Hasher>(&self, state: &mut H) {
98        // In order to not traverse the `VecMap` twice, count the elements
99        // during iteration.
100        let mut count: usize = 0;
101        for elt in self {
102            elt.hash(state);
103            count += 1;
104        }
105        count.hash(state);
106    }
107}
108
109impl<V> VecMap<V> {
110    /// Creates an empty `VecMap`.
111    ///
112    /// # Examples
113    ///
114    /// ```
115    /// use vec_map::VecMap;
116    /// let mut map: VecMap<&str> = VecMap::new();
117    /// ```
118    pub fn new() -> Self { VecMap { n: 0, v: vec![] } }
119
120    /// Creates an empty `VecMap` with space for at least `capacity`
121    /// elements before resizing.
122    ///
123    /// # Examples
124    ///
125    /// ```
126    /// use vec_map::VecMap;
127    /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
128    /// ```
129    pub fn with_capacity(capacity: usize) -> Self {
130        VecMap { n: 0, v: Vec::with_capacity(capacity) }
131    }
132
133    /// Returns the number of elements the `VecMap` can hold without
134    /// reallocating.
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use vec_map::VecMap;
140    /// let map: VecMap<String> = VecMap::with_capacity(10);
141    /// assert!(map.capacity() >= 10);
142    /// ```
143    #[inline]
144    pub fn capacity(&self) -> usize {
145        self.v.capacity()
146    }
147
148    /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
149    /// In the case of `VecMap` this means reallocations will not occur as long
150    /// as all inserted keys are less than `len`.
151    ///
152    /// The collection may reserve more space to avoid frequent reallocations.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// use vec_map::VecMap;
158    /// let mut map: VecMap<&str> = VecMap::new();
159    /// map.reserve_len(10);
160    /// assert!(map.capacity() >= 10);
161    /// ```
162    pub fn reserve_len(&mut self, len: usize) {
163        let cur_len = self.v.len();
164        if len >= cur_len {
165            self.v.reserve(len - cur_len);
166        }
167    }
168
169    /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
170    /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
171    /// keys are less than `len`.
172    ///
173    /// Note that the allocator may give the collection more space than it requests.
174    /// Therefore capacity cannot be relied upon to be precisely minimal.  Prefer
175    /// `reserve_len` if future insertions are expected.
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// use vec_map::VecMap;
181    /// let mut map: VecMap<&str> = VecMap::new();
182    /// map.reserve_len_exact(10);
183    /// assert!(map.capacity() >= 10);
184    /// ```
185    pub fn reserve_len_exact(&mut self, len: usize) {
186        let cur_len = self.v.len();
187        if len >= cur_len {
188            self.v.reserve_exact(len - cur_len);
189        }
190    }
191
192    /// Trims the `VecMap` of any excess capacity.
193    ///
194    /// The collection may reserve more space to avoid frequent reallocations.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use vec_map::VecMap;
200    /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
201    /// map.shrink_to_fit();
202    /// assert_eq!(map.capacity(), 0);
203    /// ```
204    pub fn shrink_to_fit(&mut self) {
205        // strip off trailing `None`s
206        if let Some(idx) = self.v.iter().rposition(Option::is_some) {
207            self.v.truncate(idx + 1);
208        } else {
209            self.v.clear();
210        }
211
212        self.v.shrink_to_fit()
213    }
214
215    /// Returns an iterator visiting all keys in ascending order of the keys.
216    /// The iterator's element type is `usize`.
217    pub fn keys(&self) -> Keys<V> {
218        Keys { iter: self.iter() }
219    }
220
221    /// Returns an iterator visiting all values in ascending order of the keys.
222    /// The iterator's element type is `&'r V`.
223    pub fn values(&self) -> Values<V> {
224        Values { iter: self.iter() }
225    }
226
227    /// Returns an iterator visiting all values in ascending order of the keys.
228    /// The iterator's element type is `&'r mut V`.
229    pub fn values_mut(&mut self) -> ValuesMut<V> {
230        ValuesMut { iter_mut: self.iter_mut() }
231    }
232
233    /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
234    /// The iterator's element type is `(usize, &'r V)`.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// use vec_map::VecMap;
240    ///
241    /// let mut map = VecMap::new();
242    /// map.insert(1, "a");
243    /// map.insert(3, "c");
244    /// map.insert(2, "b");
245    ///
246    /// // Print `1: a` then `2: b` then `3: c`
247    /// for (key, value) in map.iter() {
248    ///     println!("{}: {}", key, value);
249    /// }
250    /// ```
251    pub fn iter(&self) -> Iter<V> {
252        Iter {
253            front: 0,
254            back: self.v.len(),
255            n: self.n,
256            yielded: 0,
257            iter: self.v.iter()
258        }
259    }
260
261    /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
262    /// with mutable references to the values.
263    /// The iterator's element type is `(usize, &'r mut V)`.
264    ///
265    /// # Examples
266    ///
267    /// ```
268    /// use vec_map::VecMap;
269    ///
270    /// let mut map = VecMap::new();
271    /// map.insert(1, "a");
272    /// map.insert(2, "b");
273    /// map.insert(3, "c");
274    ///
275    /// for (key, value) in map.iter_mut() {
276    ///     *value = "x";
277    /// }
278    ///
279    /// for (key, value) in &map {
280    ///     assert_eq!(value, &"x");
281    /// }
282    /// ```
283    pub fn iter_mut(&mut self) -> IterMut<V> {
284        IterMut {
285            front: 0,
286            back: self.v.len(),
287            n: self.n,
288            yielded: 0,
289            iter: self.v.iter_mut()
290        }
291    }
292
293    /// Moves all elements from `other` into the map while overwriting existing keys.
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// use vec_map::VecMap;
299    ///
300    /// let mut a = VecMap::new();
301    /// a.insert(1, "a");
302    /// a.insert(2, "b");
303    ///
304    /// let mut b = VecMap::new();
305    /// b.insert(3, "c");
306    /// b.insert(4, "d");
307    ///
308    /// a.append(&mut b);
309    ///
310    /// assert_eq!(a.len(), 4);
311    /// assert_eq!(b.len(), 0);
312    /// assert_eq!(a[1], "a");
313    /// assert_eq!(a[2], "b");
314    /// assert_eq!(a[3], "c");
315    /// assert_eq!(a[4], "d");
316    /// ```
317    pub fn append(&mut self, other: &mut Self) {
318        self.extend(other.drain());
319    }
320
321    /// Splits the collection into two at the given key.
322    ///
323    /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
324    /// and the returned `Self` contains elements `[at, max_key)`.
325    ///
326    /// Note that the capacity of `self` does not change.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use vec_map::VecMap;
332    ///
333    /// let mut a = VecMap::new();
334    /// a.insert(1, "a");
335    /// a.insert(2, "b");
336    /// a.insert(3, "c");
337    /// a.insert(4, "d");
338    ///
339    /// let b = a.split_off(3);
340    ///
341    /// assert_eq!(a[1], "a");
342    /// assert_eq!(a[2], "b");
343    ///
344    /// assert_eq!(b[3], "c");
345    /// assert_eq!(b[4], "d");
346    /// ```
347    pub fn split_off(&mut self, at: usize) -> Self {
348        let mut other = VecMap::new();
349
350        if at == 0 {
351            // Move all elements to other
352            // The swap will also fix .n
353            swap(self, &mut other);
354            return other
355        } else if at >= self.v.len() {
356            // No elements to copy
357            return other;
358        }
359
360        // Look up the index of the first non-None item
361        let first_index = self.v.iter().position(|el| el.is_some());
362        let start_index = match first_index {
363            Some(index) => max(at, index),
364            None => {
365                // self has no elements
366                return other;
367            }
368        };
369
370        // Fill the new VecMap with `None`s until `start_index`
371        other.v.extend((0..start_index).map(|_| None));
372
373        // Move elements beginning with `start_index` from `self` into `other`
374        let mut taken = 0;
375        other.v.extend(self.v[start_index..].iter_mut().map(|el| {
376            let el = el.take();
377            if el.is_some() {
378                taken += 1;
379            }
380            el
381        }));
382        other.n = taken;
383        self.n -= taken;
384
385        other
386    }
387
388    /// Returns an iterator visiting all key-value pairs in ascending order of
389    /// the keys, emptying (but not consuming) the original `VecMap`.
390    /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.
391    ///
392    /// # Examples
393    ///
394    /// ```
395    /// use vec_map::VecMap;
396    ///
397    /// let mut map = VecMap::new();
398    /// map.insert(1, "a");
399    /// map.insert(3, "c");
400    /// map.insert(2, "b");
401    ///
402    /// let vec: Vec<(usize, &str)> = map.drain().collect();
403    ///
404    /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
405    /// ```
406    pub fn drain(&mut self) -> Drain<V> {
407        fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
408            v.map(|v| (i, v))
409        }
410        let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
411
412        self.n = 0;
413        Drain { iter: self.v.drain(..).enumerate().filter_map(filter) }
414    }
415
416    /// Returns the number of elements in the map.
417    ///
418    /// # Examples
419    ///
420    /// ```
421    /// use vec_map::VecMap;
422    ///
423    /// let mut a = VecMap::new();
424    /// assert_eq!(a.len(), 0);
425    /// a.insert(1, "a");
426    /// assert_eq!(a.len(), 1);
427    /// ```
428    pub fn len(&self) -> usize {
429        self.n
430    }
431
432    /// Returns true if the map contains no elements.
433    ///
434    /// # Examples
435    ///
436    /// ```
437    /// use vec_map::VecMap;
438    ///
439    /// let mut a = VecMap::new();
440    /// assert!(a.is_empty());
441    /// a.insert(1, "a");
442    /// assert!(!a.is_empty());
443    /// ```
444    pub fn is_empty(&self) -> bool {
445        self.n == 0
446    }
447
448    /// Clears the map, removing all key-value pairs.
449    ///
450    /// # Examples
451    ///
452    /// ```
453    /// use vec_map::VecMap;
454    ///
455    /// let mut a = VecMap::new();
456    /// a.insert(1, "a");
457    /// a.clear();
458    /// assert!(a.is_empty());
459    /// ```
460    pub fn clear(&mut self) { self.n = 0; self.v.clear() }
461
462    /// Returns a reference to the value corresponding to the key.
463    ///
464    /// # Examples
465    ///
466    /// ```
467    /// use vec_map::VecMap;
468    ///
469    /// let mut map = VecMap::new();
470    /// map.insert(1, "a");
471    /// assert_eq!(map.get(1), Some(&"a"));
472    /// assert_eq!(map.get(2), None);
473    /// ```
474    pub fn get(&self, key: usize) -> Option<&V> {
475        if key < self.v.len() {
476            self.v[key].as_ref()
477        } else {
478            None
479        }
480    }
481
482    /// Returns true if the map contains a value for the specified key.
483    ///
484    /// # Examples
485    ///
486    /// ```
487    /// use vec_map::VecMap;
488    ///
489    /// let mut map = VecMap::new();
490    /// map.insert(1, "a");
491    /// assert_eq!(map.contains_key(1), true);
492    /// assert_eq!(map.contains_key(2), false);
493    /// ```
494    #[inline]
495    pub fn contains_key(&self, key: usize) -> bool {
496        self.get(key).is_some()
497    }
498
499    /// Returns a mutable reference to the value corresponding to the key.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use vec_map::VecMap;
505    ///
506    /// let mut map = VecMap::new();
507    /// map.insert(1, "a");
508    /// if let Some(x) = map.get_mut(1) {
509    ///     *x = "b";
510    /// }
511    /// assert_eq!(map[1], "b");
512    /// ```
513    pub fn get_mut(&mut self, key: usize) -> Option<&mut V> {
514        if key < self.v.len() {
515            self.v[key].as_mut()
516        } else {
517            None
518        }
519    }
520
521    /// Inserts a key-value pair into the map. If the key already had a value
522    /// present in the map, that value is returned. Otherwise, `None` is returned.
523    ///
524    /// # Examples
525    ///
526    /// ```
527    /// use vec_map::VecMap;
528    ///
529    /// let mut map = VecMap::new();
530    /// assert_eq!(map.insert(37, "a"), None);
531    /// assert_eq!(map.is_empty(), false);
532    ///
533    /// map.insert(37, "b");
534    /// assert_eq!(map.insert(37, "c"), Some("b"));
535    /// assert_eq!(map[37], "c");
536    /// ```
537    pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
538        let len = self.v.len();
539        if len <= key {
540            self.v.extend((0..key - len + 1).map(|_| None));
541        }
542        let was = replace(&mut self.v[key], Some(value));
543        if was.is_none() {
544            self.n += 1;
545        }
546        was
547    }
548
549    /// Removes a key from the map, returning the value at the key if the key
550    /// was previously in the map.
551    ///
552    /// # Examples
553    ///
554    /// ```
555    /// use vec_map::VecMap;
556    ///
557    /// let mut map = VecMap::new();
558    /// map.insert(1, "a");
559    /// assert_eq!(map.remove(1), Some("a"));
560    /// assert_eq!(map.remove(1), None);
561    /// ```
562    pub fn remove(&mut self, key: usize) -> Option<V> {
563        if key >= self.v.len() {
564            return None;
565        }
566        let result = &mut self.v[key];
567        let was = result.take();
568        if was.is_some() {
569            self.n -= 1;
570        }
571        was
572    }
573
574    /// Gets the given key's corresponding entry in the map for in-place manipulation.
575    ///
576    /// # Examples
577    ///
578    /// ```
579    /// use vec_map::VecMap;
580    ///
581    /// let mut count: VecMap<u32> = VecMap::new();
582    ///
583    /// // count the number of occurrences of numbers in the vec
584    /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4] {
585    ///     *count.entry(x).or_insert(0) += 1;
586    /// }
587    ///
588    /// assert_eq!(count[1], 3);
589    /// ```
590    pub fn entry(&mut self, key: usize) -> Entry<V> {
591        // FIXME(Gankro): this is basically the dumbest implementation of
592        // entry possible, because weird non-lexical borrows issues make it
593        // completely insane to do any other way. That said, Entry is a border-line
594        // useless construct on VecMap, so it's hardly a big loss.
595        if self.contains_key(key) {
596            Occupied(OccupiedEntry {
597                map: self,
598                index: key,
599            })
600        } else {
601            Vacant(VacantEntry {
602                map: self,
603                index: key,
604            })
605        }
606    }
607
608    /// Retains only the elements specified by the predicate.
609    ///
610    /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// use vec_map::VecMap;
616    ///
617    /// let mut map: VecMap<usize> = (0..8).map(|x|(x, x*10)).collect();
618    /// map.retain(|k, _| k % 2 == 0);
619    /// assert_eq!(map.len(), 4);
620    /// ```
621    pub fn retain<F>(&mut self, mut f: F)
622        where F: FnMut(usize, &mut V) -> bool
623    {
624        for (i, e) in self.v.iter_mut().enumerate() {
625            let remove = match *e {
626                Some(ref mut value) => !f(i, value),
627                None => false,
628            };
629            if remove {
630                *e = None;
631                self.n -= 1;
632            }
633        }
634    }
635}
636
637impl<'a, V> Entry<'a, V> {
638    /// Ensures a value is in the entry by inserting the default if empty, and
639    /// returns a mutable reference to the value in the entry.
640    pub fn or_insert(self, default: V) -> &'a mut V {
641        match self {
642            Occupied(entry) => entry.into_mut(),
643            Vacant(entry) => entry.insert(default),
644        }
645    }
646
647    /// Ensures a value is in the entry by inserting the result of the default
648    /// function if empty, and returns a mutable reference to the value in the
649    /// entry.
650    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
651        match self {
652            Occupied(entry) => entry.into_mut(),
653            Vacant(entry) => entry.insert(default()),
654        }
655    }
656}
657
658impl<'a, V> VacantEntry<'a, V> {
659    /// Sets the value of the entry with the VacantEntry's key,
660    /// and returns a mutable reference to it.
661    pub fn insert(self, value: V) -> &'a mut V {
662        let index = self.index;
663        self.map.insert(index, value);
664        &mut self.map[index]
665    }
666}
667
668impl<'a, V> OccupiedEntry<'a, V> {
669    /// Gets a reference to the value in the entry.
670    pub fn get(&self) -> &V {
671        let index = self.index;
672        &self.map[index]
673    }
674
675    /// Gets a mutable reference to the value in the entry.
676    pub fn get_mut(&mut self) -> &mut V {
677        let index = self.index;
678        &mut self.map[index]
679    }
680
681    /// Converts the entry into a mutable reference to its value.
682    pub fn into_mut(self) -> &'a mut V {
683        let index = self.index;
684        &mut self.map[index]
685    }
686
687    /// Sets the value of the entry with the OccupiedEntry's key,
688    /// and returns the entry's old value.
689    pub fn insert(&mut self, value: V) -> V {
690        let index = self.index;
691        self.map.insert(index, value).unwrap()
692    }
693
694    /// Takes the value of the entry out of the map, and returns it.
695    pub fn remove(self) -> V {
696        let index = self.index;
697        self.map.remove(index).unwrap()
698    }
699}
700
701impl<V: Clone> Clone for VecMap<V> {
702    #[inline]
703    fn clone(&self) -> Self {
704        VecMap { n: self.n, v: self.v.clone() }
705    }
706
707    #[inline]
708    fn clone_from(&mut self, source: &Self) {
709        self.v.clone_from(&source.v);
710        self.n = source.n;
711    }
712}
713
714impl<V: PartialEq> PartialEq for VecMap<V> {
715    fn eq(&self, other: &Self) -> bool {
716        self.n == other.n && self.iter().eq(other.iter())
717    }
718}
719
720impl<V: Eq> Eq for VecMap<V> {}
721
722impl<V: PartialOrd> PartialOrd for VecMap<V> {
723    #[inline]
724    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
725        self.iter().partial_cmp(other.iter())
726    }
727}
728
729impl<V: Ord> Ord for VecMap<V> {
730    #[inline]
731    fn cmp(&self, other: &Self) -> Ordering {
732        self.iter().cmp(other.iter())
733    }
734}
735
736impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
737    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
738        f.debug_map().entries(self).finish()
739    }
740}
741
742impl<V> FromIterator<(usize, V)> for VecMap<V> {
743    fn from_iter<I: IntoIterator<Item = (usize, V)>>(iter: I) -> Self {
744        let mut map = Self::new();
745        map.extend(iter);
746        map
747    }
748}
749
750impl<T> IntoIterator for VecMap<T> {
751    type Item = (usize, T);
752    type IntoIter = IntoIter<T>;
753
754    /// Returns an iterator visiting all key-value pairs in ascending order of
755    /// the keys, consuming the original `VecMap`.
756    /// The iterator's element type is `(usize, &'r V)`.
757    ///
758    /// # Examples
759    ///
760    /// ```
761    /// use vec_map::VecMap;
762    ///
763    /// let mut map = VecMap::new();
764    /// map.insert(1, "a");
765    /// map.insert(3, "c");
766    /// map.insert(2, "b");
767    ///
768    /// let vec: Vec<(usize, &str)> = map.into_iter().collect();
769    ///
770    /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
771    /// ```
772    fn into_iter(self) -> IntoIter<T> {
773        IntoIter {
774            n: self.n,
775            yielded: 0,
776            iter: self.v.into_iter().enumerate()
777        }
778    }
779}
780
781impl<'a, T> IntoIterator for &'a VecMap<T> {
782    type Item = (usize, &'a T);
783    type IntoIter = Iter<'a, T>;
784
785    fn into_iter(self) -> Iter<'a, T> {
786        self.iter()
787    }
788}
789
790impl<'a, T> IntoIterator for &'a mut VecMap<T> {
791    type Item = (usize, &'a mut T);
792    type IntoIter = IterMut<'a, T>;
793
794    fn into_iter(self) -> IterMut<'a, T> {
795        self.iter_mut()
796    }
797}
798
799impl<V> Extend<(usize, V)> for VecMap<V> {
800    fn extend<I: IntoIterator<Item = (usize, V)>>(&mut self, iter: I) {
801        for (k, v) in iter {
802            self.insert(k, v);
803        }
804    }
805}
806
807impl<'a, V: Copy> Extend<(usize, &'a V)> for VecMap<V> {
808    fn extend<I: IntoIterator<Item = (usize, &'a V)>>(&mut self, iter: I) {
809        self.extend(iter.into_iter().map(|(key, &value)| (key, value)));
810    }
811}
812
813impl<V> Index<usize> for VecMap<V> {
814    type Output = V;
815
816    #[inline]
817    fn index(&self, i: usize) -> &V {
818        self.get(i).expect("key not present")
819    }
820}
821
822impl<'a, V> Index<&'a usize> for VecMap<V> {
823    type Output = V;
824
825    #[inline]
826    fn index(&self, i: &usize) -> &V {
827        self.get(*i).expect("key not present")
828    }
829}
830
831impl<V> IndexMut<usize> for VecMap<V> {
832    #[inline]
833    fn index_mut(&mut self, i: usize) -> &mut V {
834        self.get_mut(i).expect("key not present")
835    }
836}
837
838impl<'a, V> IndexMut<&'a usize> for VecMap<V> {
839    #[inline]
840    fn index_mut(&mut self, i: &usize) -> &mut V {
841        self.get_mut(*i).expect("key not present")
842    }
843}
844
845macro_rules! iterator {
846    (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
847        impl<'a, V> Iterator for $name<'a, V> {
848            type Item = $elem;
849
850            #[inline]
851            fn next(&mut self) -> Option<$elem> {
852                while self.front < self.back {
853                    if let Some(elem) = self.iter.next() {
854                        if let Some(x) = elem$(. $getter ())+ {
855                            let index = self.front;
856                            self.front += 1;
857                            self.yielded += 1;
858                            return Some((index, x));
859                        }
860                    }
861                    self.front += 1;
862                }
863                None
864            }
865
866            #[inline]
867            fn size_hint(&self) -> (usize, Option<usize>) {
868                (self.n - self.yielded, Some(self.n - self.yielded))
869            }
870        }
871    }
872}
873
874macro_rules! double_ended_iterator {
875    (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
876        impl<'a, V> DoubleEndedIterator for $name<'a, V> {
877            #[inline]
878            fn next_back(&mut self) -> Option<$elem> {
879                while self.front < self.back {
880                    if let Some(elem) = self.iter.next_back() {
881                        if let Some(x) = elem$(. $getter ())+ {
882                            self.back -= 1;
883                            return Some((self.back, x));
884                        }
885                    }
886                    self.back -= 1;
887                }
888                None
889            }
890        }
891    }
892}
893
894/// An iterator over the key-value pairs of a map.
895pub struct Iter<'a, V: 'a> {
896    front: usize,
897    back: usize,
898    n: usize,
899    yielded: usize,
900    iter: slice::Iter<'a, Option<V>>
901}
902
903// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
904impl<'a, V> Clone for Iter<'a, V> {
905    fn clone(&self) -> Iter<'a, V> {
906        Iter {
907            front: self.front,
908            back: self.back,
909            n: self.n,
910            yielded: self.yielded,
911            iter: self.iter.clone()
912        }
913    }
914}
915
916iterator! { impl Iter -> (usize, &'a V), as_ref }
917impl<'a, V> ExactSizeIterator for Iter<'a, V> {}
918double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }
919
920/// An iterator over the key-value pairs of a map, with the
921/// values being mutable.
922pub struct IterMut<'a, V: 'a> {
923    front: usize,
924    back: usize,
925    n: usize,
926    yielded: usize,
927    iter: slice::IterMut<'a, Option<V>>
928}
929
930iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
931impl<'a, V> ExactSizeIterator for IterMut<'a, V> {}
932double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
933
934/// An iterator over the keys of a map.
935pub struct Keys<'a, V: 'a> {
936    iter: Iter<'a, V>,
937}
938
939// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
940impl<'a, V> Clone for Keys<'a, V> {
941    fn clone(&self) -> Keys<'a, V> {
942        Keys {
943            iter: self.iter.clone()
944        }
945    }
946}
947
948/// An iterator over the values of a map.
949pub struct Values<'a, V: 'a> {
950    iter: Iter<'a, V>,
951}
952
953// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
954impl<'a, V> Clone for Values<'a, V> {
955    fn clone(&self) -> Values<'a, V> {
956        Values {
957            iter: self.iter.clone()
958        }
959    }
960}
961
962/// An iterator over the values of a map.
963pub struct ValuesMut<'a, V: 'a> {
964    iter_mut: IterMut<'a, V>,
965}
966
967/// A consuming iterator over the key-value pairs of a map.
968pub struct IntoIter<V> {
969    n: usize,
970    yielded: usize,
971    iter: Enumerate<vec::IntoIter<Option<V>>>,
972}
973
974/// A draining iterator over the key-value pairs of a map.
975pub struct Drain<'a, V: 'a> {
976    iter: FilterMap<
977    Enumerate<vec::Drain<'a, Option<V>>>,
978    fn((usize, Option<V>)) -> Option<(usize, V)>>
979}
980
981impl<'a, V> Iterator for Drain<'a, V> {
982    type Item = (usize, V);
983
984    fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
985    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
986}
987
988impl<'a, V> ExactSizeIterator for Drain<'a, V> {}
989
990impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
991    fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
992}
993
994impl<'a, V> Iterator for Keys<'a, V> {
995    type Item = usize;
996
997    fn next(&mut self) -> Option<usize> { self.iter.next().map(|e| e.0) }
998    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
999}
1000
1001impl<'a, V> ExactSizeIterator for Keys<'a, V> {}
1002
1003impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
1004    fn next_back(&mut self) -> Option<usize> { self.iter.next_back().map(|e| e.0) }
1005}
1006
1007impl<'a, V> Iterator for Values<'a, V> {
1008    type Item = &'a V;
1009
1010    fn next(&mut self) -> Option<(&'a V)> { self.iter.next().map(|e| e.1) }
1011    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1012}
1013
1014impl<'a, V> ExactSizeIterator for Values<'a, V> {}
1015
1016impl<'a, V> DoubleEndedIterator for Values<'a, V> {
1017    fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back().map(|e| e.1) }
1018}
1019
1020impl<'a, V> Iterator for ValuesMut<'a, V> {
1021    type Item = &'a mut V;
1022
1023    fn next(&mut self) -> Option<(&'a mut V)> { self.iter_mut.next().map(|e| e.1) }
1024    fn size_hint(&self) -> (usize, Option<usize>) { self.iter_mut.size_hint() }
1025}
1026
1027impl<'a, V> ExactSizeIterator for ValuesMut<'a, V> {}
1028
1029impl<'a, V> DoubleEndedIterator for ValuesMut<'a, V> {
1030    fn next_back(&mut self) -> Option<&'a mut V> { self.iter_mut.next_back().map(|e| e.1) }
1031}
1032
1033impl<V> Iterator for IntoIter<V> {
1034    type Item = (usize, V);
1035
1036    fn next(&mut self) -> Option<(usize, V)> {
1037        loop {
1038            match self.iter.next() {
1039                None => return None,
1040                Some((i, Some(value))) => {
1041                    self.yielded += 1;
1042                    return Some((i, value))
1043                },
1044                _ => {}
1045            }
1046        }
1047    }
1048
1049    fn size_hint(&self) -> (usize, Option<usize>) {
1050        (self.n - self.yielded, Some(self.n - self.yielded))
1051    }
1052}
1053
1054impl<V> ExactSizeIterator for IntoIter<V> {}
1055
1056impl<V> DoubleEndedIterator for IntoIter<V> {
1057    fn next_back(&mut self) -> Option<(usize, V)> {
1058        loop {
1059            match self.iter.next_back() {
1060                None => return None,
1061                Some((i, Some(value))) => return Some((i, value)),
1062                _ => {}
1063            }
1064        }
1065    }
1066}
1067
1068#[allow(dead_code)]
1069fn assert_properties() {
1070    fn vec_map_covariant<'a, T>(map: VecMap<&'static T>) -> VecMap<&'a T> { map }
1071
1072    fn into_iter_covariant<'a, T>(iter: IntoIter<&'static T>) -> IntoIter<&'a T> { iter }
1073
1074    fn iter_covariant<'i, 'a, T>(iter: Iter<'i, &'static T>) -> Iter<'i, &'a T> { iter }
1075
1076    fn keys_covariant<'i, 'a, T>(iter: Keys<'i, &'static T>) -> Keys<'i, &'a T> { iter }
1077
1078    fn values_covariant<'i, 'a, T>(iter: Values<'i, &'static T>) -> Values<'i, &'a T> { iter }
1079}
1080
1081#[cfg(test)]
1082mod test {
1083    use super::VecMap;
1084    use super::Entry::{Occupied, Vacant};
1085    use std::hash::{Hash, Hasher};
1086    use std::collections::hash_map::DefaultHasher;
1087
1088    #[test]
1089    fn test_get_mut() {
1090        let mut m = VecMap::new();
1091        assert!(m.insert(1, 12).is_none());
1092        assert!(m.insert(2, 8).is_none());
1093        assert!(m.insert(5, 14).is_none());
1094        let new = 100;
1095        match m.get_mut(5) {
1096            None => panic!(), Some(x) => *x = new
1097        }
1098        assert_eq!(m.get(5), Some(&new));
1099    }
1100
1101    #[test]
1102    fn test_len() {
1103        let mut map = VecMap::new();
1104        assert_eq!(map.len(), 0);
1105        assert!(map.is_empty());
1106        assert!(map.insert(5, 20).is_none());
1107        assert_eq!(map.len(), 1);
1108        assert!(!map.is_empty());
1109        assert!(map.insert(11, 12).is_none());
1110        assert_eq!(map.len(), 2);
1111        assert!(!map.is_empty());
1112        assert!(map.insert(14, 22).is_none());
1113        assert_eq!(map.len(), 3);
1114        assert!(!map.is_empty());
1115    }
1116
1117    #[test]
1118    fn test_clear() {
1119        let mut map = VecMap::new();
1120        assert!(map.insert(5, 20).is_none());
1121        assert!(map.insert(11, 12).is_none());
1122        assert!(map.insert(14, 22).is_none());
1123        map.clear();
1124        assert!(map.is_empty());
1125        assert!(map.get(5).is_none());
1126        assert!(map.get(11).is_none());
1127        assert!(map.get(14).is_none());
1128    }
1129
1130    #[test]
1131    fn test_insert() {
1132        let mut m = VecMap::new();
1133        assert_eq!(m.insert(1, 2), None);
1134        assert_eq!(m.insert(1, 3), Some(2));
1135        assert_eq!(m.insert(1, 4), Some(3));
1136    }
1137
1138    #[test]
1139    fn test_remove() {
1140        let mut m = VecMap::new();
1141        m.insert(1, 2);
1142        assert_eq!(m.remove(1), Some(2));
1143        assert_eq!(m.remove(1), None);
1144    }
1145
1146    #[test]
1147    fn test_keys() {
1148        let mut map = VecMap::new();
1149        map.insert(1, 'a');
1150        map.insert(2, 'b');
1151        map.insert(3, 'c');
1152        let keys: Vec<_> = map.keys().collect();
1153        assert_eq!(keys.len(), 3);
1154        assert!(keys.contains(&1));
1155        assert!(keys.contains(&2));
1156        assert!(keys.contains(&3));
1157    }
1158
1159    #[test]
1160    fn test_values() {
1161        let mut map = VecMap::new();
1162        map.insert(1, 'a');
1163        map.insert(2, 'b');
1164        map.insert(3, 'c');
1165        let values: Vec<_> = map.values().cloned().collect();
1166        assert_eq!(values.len(), 3);
1167        assert!(values.contains(&'a'));
1168        assert!(values.contains(&'b'));
1169        assert!(values.contains(&'c'));
1170    }
1171
1172    #[test]
1173    fn test_iterator() {
1174        let mut m = VecMap::new();
1175
1176        assert!(m.insert(0, 1).is_none());
1177        assert!(m.insert(1, 2).is_none());
1178        assert!(m.insert(3, 5).is_none());
1179        assert!(m.insert(6, 10).is_none());
1180        assert!(m.insert(10, 11).is_none());
1181
1182        let mut it = m.iter();
1183        assert_eq!(it.size_hint(), (5, Some(5)));
1184        assert_eq!(it.next().unwrap(), (0, &1));
1185        assert_eq!(it.size_hint(), (4, Some(4)));
1186        assert_eq!(it.next().unwrap(), (1, &2));
1187        assert_eq!(it.size_hint(), (3, Some(3)));
1188        assert_eq!(it.next().unwrap(), (3, &5));
1189        assert_eq!(it.size_hint(), (2, Some(2)));
1190        assert_eq!(it.next().unwrap(), (6, &10));
1191        assert_eq!(it.size_hint(), (1, Some(1)));
1192        assert_eq!(it.next().unwrap(), (10, &11));
1193        assert_eq!(it.size_hint(), (0, Some(0)));
1194        assert!(it.next().is_none());
1195    }
1196
1197    #[test]
1198    fn test_iterator_size_hints() {
1199        let mut m = VecMap::new();
1200
1201        assert!(m.insert(0, 1).is_none());
1202        assert!(m.insert(1, 2).is_none());
1203        assert!(m.insert(3, 5).is_none());
1204        assert!(m.insert(6, 10).is_none());
1205        assert!(m.insert(10, 11).is_none());
1206
1207        assert_eq!(m.iter().size_hint(), (5, Some(5)));
1208        assert_eq!(m.iter().rev().size_hint(), (5, Some(5)));
1209        assert_eq!(m.iter_mut().size_hint(), (5, Some(5)));
1210        assert_eq!(m.iter_mut().rev().size_hint(), (5, Some(5)));
1211    }
1212
1213    #[test]
1214    fn test_mut_iterator() {
1215        let mut m = VecMap::new();
1216
1217        assert!(m.insert(0, 1).is_none());
1218        assert!(m.insert(1, 2).is_none());
1219        assert!(m.insert(3, 5).is_none());
1220        assert!(m.insert(6, 10).is_none());
1221        assert!(m.insert(10, 11).is_none());
1222
1223        for (k, v) in &mut m {
1224            *v += k as isize;
1225        }
1226
1227        let mut it = m.iter();
1228        assert_eq!(it.next().unwrap(), (0, &1));
1229        assert_eq!(it.next().unwrap(), (1, &3));
1230        assert_eq!(it.next().unwrap(), (3, &8));
1231        assert_eq!(it.next().unwrap(), (6, &16));
1232        assert_eq!(it.next().unwrap(), (10, &21));
1233        assert!(it.next().is_none());
1234    }
1235
1236    #[test]
1237    fn test_rev_iterator() {
1238        let mut m = VecMap::new();
1239
1240        assert!(m.insert(0, 1).is_none());
1241        assert!(m.insert(1, 2).is_none());
1242        assert!(m.insert(3, 5).is_none());
1243        assert!(m.insert(6, 10).is_none());
1244        assert!(m.insert(10, 11).is_none());
1245
1246        let mut it = m.iter().rev();
1247        assert_eq!(it.next().unwrap(), (10, &11));
1248        assert_eq!(it.next().unwrap(), (6, &10));
1249        assert_eq!(it.next().unwrap(), (3, &5));
1250        assert_eq!(it.next().unwrap(), (1, &2));
1251        assert_eq!(it.next().unwrap(), (0, &1));
1252        assert!(it.next().is_none());
1253    }
1254
1255    #[test]
1256    fn test_mut_rev_iterator() {
1257        let mut m = VecMap::new();
1258
1259        assert!(m.insert(0, 1).is_none());
1260        assert!(m.insert(1, 2).is_none());
1261        assert!(m.insert(3, 5).is_none());
1262        assert!(m.insert(6, 10).is_none());
1263        assert!(m.insert(10, 11).is_none());
1264
1265        for (k, v) in m.iter_mut().rev() {
1266            *v += k as isize;
1267        }
1268
1269        let mut it = m.iter();
1270        assert_eq!(it.next().unwrap(), (0, &1));
1271        assert_eq!(it.next().unwrap(), (1, &3));
1272        assert_eq!(it.next().unwrap(), (3, &8));
1273        assert_eq!(it.next().unwrap(), (6, &16));
1274        assert_eq!(it.next().unwrap(), (10, &21));
1275        assert!(it.next().is_none());
1276    }
1277
1278    #[test]
1279    fn test_move_iter() {
1280        let mut m: VecMap<Box<_>> = VecMap::new();
1281        m.insert(1, Box::new(2));
1282        let mut called = false;
1283        for (k, v) in m {
1284            assert!(!called);
1285            called = true;
1286            assert_eq!(k, 1);
1287            assert_eq!(v, Box::new(2));
1288        }
1289        assert!(called);
1290    }
1291
1292    #[test]
1293    fn test_drain_iterator() {
1294        let mut map = VecMap::new();
1295        map.insert(1, "a");
1296        map.insert(3, "c");
1297        map.insert(2, "b");
1298
1299        let vec: Vec<_> = map.drain().collect();
1300
1301        assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
1302        assert_eq!(map.len(), 0);
1303    }
1304
1305    #[test]
1306    fn test_append() {
1307        let mut a = VecMap::new();
1308        a.insert(1, "a");
1309        a.insert(2, "b");
1310        a.insert(3, "c");
1311
1312        let mut b = VecMap::new();
1313        b.insert(3, "d");  // Overwrite element from a
1314        b.insert(4, "e");
1315        b.insert(5, "f");
1316
1317        a.append(&mut b);
1318
1319        assert_eq!(a.len(), 5);
1320        assert_eq!(b.len(), 0);
1321        // Capacity shouldn't change for possible reuse
1322        assert!(b.capacity() >= 4);
1323
1324        assert_eq!(a[1], "a");
1325        assert_eq!(a[2], "b");
1326        assert_eq!(a[3], "d");
1327        assert_eq!(a[4], "e");
1328        assert_eq!(a[5], "f");
1329    }
1330
1331    #[test]
1332    fn test_split_off() {
1333        // Split within the key range
1334        let mut a = VecMap::new();
1335        a.insert(1, "a");
1336        a.insert(2, "b");
1337        a.insert(3, "c");
1338        a.insert(4, "d");
1339
1340        let b = a.split_off(3);
1341
1342        assert_eq!(a.len(), 2);
1343        assert_eq!(b.len(), 2);
1344
1345        assert_eq!(a[1], "a");
1346        assert_eq!(a[2], "b");
1347
1348        assert_eq!(b[3], "c");
1349        assert_eq!(b[4], "d");
1350
1351        // Split at 0
1352        a.clear();
1353        a.insert(1, "a");
1354        a.insert(2, "b");
1355        a.insert(3, "c");
1356        a.insert(4, "d");
1357
1358        let b = a.split_off(0);
1359
1360        assert_eq!(a.len(), 0);
1361        assert_eq!(b.len(), 4);
1362        assert_eq!(b[1], "a");
1363        assert_eq!(b[2], "b");
1364        assert_eq!(b[3], "c");
1365        assert_eq!(b[4], "d");
1366
1367        // Split behind max_key
1368        a.clear();
1369        a.insert(1, "a");
1370        a.insert(2, "b");
1371        a.insert(3, "c");
1372        a.insert(4, "d");
1373
1374        let b = a.split_off(5);
1375
1376        assert_eq!(a.len(), 4);
1377        assert_eq!(b.len(), 0);
1378        assert_eq!(a[1], "a");
1379        assert_eq!(a[2], "b");
1380        assert_eq!(a[3], "c");
1381        assert_eq!(a[4], "d");
1382    }
1383
1384    #[test]
1385    fn test_show() {
1386        let mut map = VecMap::new();
1387        let empty = VecMap::<i32>::new();
1388
1389        map.insert(1, 2);
1390        map.insert(3, 4);
1391
1392        let map_str = format!("{:?}", map);
1393        assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
1394        assert_eq!(format!("{:?}", empty), "{}");
1395    }
1396
1397    #[test]
1398    fn test_clone() {
1399        let mut a = VecMap::new();
1400
1401        a.insert(1, 'x');
1402        a.insert(4, 'y');
1403        a.insert(6, 'z');
1404
1405        assert_eq!(a.clone().iter().collect::<Vec<_>>(), [(1, &'x'), (4, &'y'), (6, &'z')]);
1406    }
1407
1408    #[test]
1409    fn test_eq() {
1410        let mut a = VecMap::new();
1411        let mut b = VecMap::new();
1412
1413        assert!(a == b);
1414        assert!(a.insert(0, 5).is_none());
1415        assert!(a != b);
1416        assert!(b.insert(0, 4).is_none());
1417        assert!(a != b);
1418        assert!(a.insert(5, 19).is_none());
1419        assert!(a != b);
1420        assert!(!b.insert(0, 5).is_none());
1421        assert!(a != b);
1422        assert!(b.insert(5, 19).is_none());
1423        assert!(a == b);
1424
1425        a = VecMap::new();
1426        b = VecMap::with_capacity(1);
1427        assert!(a == b);
1428    }
1429
1430    #[test]
1431    fn test_lt() {
1432        let mut a = VecMap::new();
1433        let mut b = VecMap::new();
1434
1435        assert!(!(a < b) && !(b < a));
1436        assert!(b.insert(2, 5).is_none());
1437        assert!(a < b);
1438        assert!(a.insert(2, 7).is_none());
1439        assert!(!(a < b) && b < a);
1440        assert!(b.insert(1, 0).is_none());
1441        assert!(b < a);
1442        assert!(a.insert(0, 6).is_none());
1443        assert!(a < b);
1444        assert!(a.insert(6, 2).is_none());
1445        assert!(a < b && !(b < a));
1446    }
1447
1448    #[test]
1449    fn test_ord() {
1450        let mut a = VecMap::new();
1451        let mut b = VecMap::new();
1452
1453        assert!(a <= b && a >= b);
1454        assert!(a.insert(1, 1).is_none());
1455        assert!(a > b && a >= b);
1456        assert!(b < a && b <= a);
1457        assert!(b.insert(2, 2).is_none());
1458        assert!(b > a && b >= a);
1459        assert!(a < b && a <= b);
1460    }
1461
1462    #[test]
1463    fn test_hash() {
1464        fn hash<T: Hash>(t: &T) -> u64 {
1465            let mut s = DefaultHasher::new();
1466            t.hash(&mut s);
1467            s.finish()
1468        }
1469
1470        let mut x = VecMap::new();
1471        let mut y = VecMap::new();
1472
1473        assert!(hash(&x) == hash(&y));
1474        x.insert(1, 'a');
1475        x.insert(2, 'b');
1476        x.insert(3, 'c');
1477
1478        y.insert(3, 'c');
1479        y.insert(2, 'b');
1480        y.insert(1, 'a');
1481
1482        assert!(hash(&x) == hash(&y));
1483
1484        x.insert(1000, 'd');
1485        x.remove(1000);
1486
1487        assert!(hash(&x) == hash(&y));
1488    }
1489
1490    #[test]
1491    fn test_from_iter() {
1492        let xs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1493
1494        let map: VecMap<_> = xs.iter().cloned().collect();
1495
1496        for &(k, v) in &xs {
1497            assert_eq!(map.get(k), Some(&v));
1498        }
1499    }
1500
1501    #[test]
1502    fn test_index() {
1503        let mut map = VecMap::new();
1504
1505        map.insert(1, 2);
1506        map.insert(2, 1);
1507        map.insert(3, 4);
1508
1509        assert_eq!(map[3], 4);
1510    }
1511
1512    #[test]
1513    #[should_panic]
1514    fn test_index_nonexistent() {
1515        let mut map = VecMap::new();
1516
1517        map.insert(1, 2);
1518        map.insert(2, 1);
1519        map.insert(3, 4);
1520
1521        map[4];
1522    }
1523
1524    #[test]
1525    fn test_entry() {
1526        let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1527
1528        let mut map: VecMap<_> = xs.iter().cloned().collect();
1529
1530        // Existing key (insert)
1531        match map.entry(1) {
1532            Vacant(_) => unreachable!(),
1533            Occupied(mut view) => {
1534                assert_eq!(view.get(), &10);
1535                assert_eq!(view.insert(100), 10);
1536            }
1537        }
1538
1539        assert_eq!(map.get(1).unwrap(), &100);
1540        assert_eq!(map.len(), 6);
1541
1542        // Existing key (update)
1543        match map.entry(2) {
1544            Vacant(_) => unreachable!(),
1545            Occupied(mut view) => {
1546                let v = view.get_mut();
1547                *v *= 10;
1548            }
1549        }
1550
1551        assert_eq!(map.get(2).unwrap(), &200);
1552        assert_eq!(map.len(), 6);
1553
1554        // Existing key (take)
1555        match map.entry(3) {
1556            Vacant(_) => unreachable!(),
1557            Occupied(view) => {
1558                assert_eq!(view.remove(), 30);
1559            }
1560        }
1561
1562        assert_eq!(map.get(3), None);
1563        assert_eq!(map.len(), 5);
1564
1565        // Inexistent key (insert)
1566        match map.entry(10) {
1567            Occupied(_) => unreachable!(),
1568            Vacant(view) => {
1569                assert_eq!(*view.insert(1000), 1000);
1570            }
1571        }
1572
1573        assert_eq!(map.get(10).unwrap(), &1000);
1574        assert_eq!(map.len(), 6);
1575    }
1576
1577    #[test]
1578    fn test_extend_ref() {
1579        let mut a = VecMap::new();
1580        a.insert(1, "one");
1581        let mut b = VecMap::new();
1582        b.insert(2, "two");
1583        b.insert(3, "three");
1584
1585        a.extend(&b);
1586
1587        assert_eq!(a.len(), 3);
1588        assert_eq!(a[&1], "one");
1589        assert_eq!(a[&2], "two");
1590        assert_eq!(a[&3], "three");
1591    }
1592
1593    #[test]
1594    #[cfg(feature = "serde")]
1595    fn test_serde() {
1596        use serde::{Serialize, Deserialize};
1597        fn impls_serde_traits<'de, S: Serialize + Deserialize<'de>>() {}
1598
1599        impls_serde_traits::<VecMap<u32>>();
1600    }
1601
1602    #[test]
1603    fn test_retain() {
1604        let mut map = VecMap::new();
1605        map.insert(1, "one");
1606        map.insert(2, "two");
1607        map.insert(3, "three");
1608        map.retain(|k, v| match k {
1609            1 => false,
1610            2 => {
1611                *v = "two changed";
1612                true
1613            },
1614            3 => false,
1615            _ => panic!(),
1616        });
1617
1618        assert_eq!(map.len(), 1);
1619        assert_eq!(map.get(1), None);
1620        assert_eq!(map[2], "two changed");
1621        assert_eq!(map.get(3), None);
1622    }
1623}