]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec_map.rs
65592d138c72c63758fd6028db83c3e249529908
[rust.git] / src / libcollections / vec_map.rs
1 // Copyright 2012-2014 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 //! A simple map based on a vector for small integer keys. Space requirements
12 //! are O(highest integer key).
13
14 #![allow(missing_docs)]
15
16 use self::Entry::*;
17
18 use core::prelude::*;
19
20 use core::cmp::Ordering;
21 use core::default::Default;
22 use core::fmt;
23 use core::hash::{Hash, Writer, Hasher};
24 use core::iter::{Enumerate, FilterMap, Map, FromIterator, IntoIterator};
25 use core::iter;
26 use core::mem::replace;
27 use core::ops::{Index, IndexMut};
28
29 use {vec, slice};
30 use vec::Vec;
31
32 /// A map optimized for small integer keys.
33 ///
34 /// # Examples
35 ///
36 /// ```
37 /// use std::collections::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 /// match months.get_mut(&3) {
51 ///     Some(value) => *value = "Venus",
52 ///     None => (),
53 /// }
54 ///
55 /// assert_eq!(months.get(&3), Some(&"Venus"));
56 ///
57 /// // Print out all months
58 /// for (key, value) in months.iter() {
59 ///     println!("month {} is {}", key, value);
60 /// }
61 ///
62 /// months.clear();
63 /// assert!(months.is_empty());
64 /// ```
65 pub struct VecMap<V> {
66     v: Vec<Option<V>>,
67 }
68
69 /// A view into a single entry in a map, which may either be vacant or occupied.
70 #[unstable(feature = "collections",
71            reason = "precise API still under development")]
72 pub enum Entry<'a, V:'a> {
73     /// A vacant Entry
74     Vacant(VacantEntry<'a, V>),
75     /// An occupied Entry
76     Occupied(OccupiedEntry<'a, V>),
77 }
78
79 /// A vacant Entry.
80 #[unstable(feature = "collections",
81            reason = "precise API still under development")]
82 pub struct VacantEntry<'a, V:'a> {
83     map: &'a mut VecMap<V>,
84     index: usize,
85 }
86
87 /// An occupied Entry.
88 #[unstable(feature = "collections",
89            reason = "precise API still under development")]
90 pub struct OccupiedEntry<'a, V:'a> {
91     map: &'a mut VecMap<V>,
92     index: usize,
93 }
94
95 #[stable(feature = "rust1", since = "1.0.0")]
96 impl<V> Default for VecMap<V> {
97     #[stable(feature = "rust1", since = "1.0.0")]
98     #[inline]
99     fn default() -> VecMap<V> { VecMap::new() }
100 }
101
102 impl<V:Clone> Clone for VecMap<V> {
103     #[inline]
104     fn clone(&self) -> VecMap<V> {
105         VecMap { v: self.v.clone() }
106     }
107
108     #[inline]
109     fn clone_from(&mut self, source: &VecMap<V>) {
110         self.v.clone_from(&source.v);
111     }
112 }
113
114 impl<S: Writer + Hasher, V: Hash<S>> Hash<S> for VecMap<V> {
115     fn hash(&self, state: &mut S) {
116         // In order to not traverse the `VecMap` twice, count the elements
117         // during iteration.
118         let mut count: usize = 0;
119         for elt in self {
120             elt.hash(state);
121             count += 1;
122         }
123         count.hash(state);
124     }
125 }
126
127 impl<V> VecMap<V> {
128     /// Creates an empty `VecMap`.
129     ///
130     /// # Examples
131     ///
132     /// ```
133     /// use std::collections::VecMap;
134     /// let mut map: VecMap<&str> = VecMap::new();
135     /// ```
136     #[stable(feature = "rust1", since = "1.0.0")]
137     pub fn new() -> VecMap<V> { VecMap { v: vec![] } }
138
139     /// Creates an empty `VecMap` with space for at least `capacity`
140     /// elements before resizing.
141     ///
142     /// # Examples
143     ///
144     /// ```
145     /// use std::collections::VecMap;
146     /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
147     /// ```
148     #[stable(feature = "rust1", since = "1.0.0")]
149     pub fn with_capacity(capacity: usize) -> VecMap<V> {
150         VecMap { v: Vec::with_capacity(capacity) }
151     }
152
153     /// Returns the number of elements the `VecMap` can hold without
154     /// reallocating.
155     ///
156     /// # Examples
157     ///
158     /// ```
159     /// use std::collections::VecMap;
160     /// let map: VecMap<String> = VecMap::with_capacity(10);
161     /// assert!(map.capacity() >= 10);
162     /// ```
163     #[inline]
164     #[stable(feature = "rust1", since = "1.0.0")]
165     pub fn capacity(&self) -> usize {
166         self.v.capacity()
167     }
168
169     /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
170     /// In the case of `VecMap` this means reallocations will not occur as long
171     /// as all inserted keys are less than `len`.
172     ///
173     /// The collection may reserve more space to avoid frequent reallocations.
174     ///
175     /// # Examples
176     ///
177     /// ```
178     /// use std::collections::VecMap;
179     /// let mut map: VecMap<&str> = VecMap::new();
180     /// map.reserve_len(10);
181     /// assert!(map.capacity() >= 10);
182     /// ```
183     #[stable(feature = "rust1", since = "1.0.0")]
184     pub fn reserve_len(&mut self, len: usize) {
185         let cur_len = self.v.len();
186         if len >= cur_len {
187             self.v.reserve(len - cur_len);
188         }
189     }
190
191     /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
192     /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
193     /// keys are less than `len`.
194     ///
195     /// Note that the allocator may give the collection more space than it requests.
196     /// Therefore capacity cannot be relied upon to be precisely minimal.  Prefer
197     /// `reserve_len` if future insertions are expected.
198     ///
199     /// # Examples
200     ///
201     /// ```
202     /// use std::collections::VecMap;
203     /// let mut map: VecMap<&str> = VecMap::new();
204     /// map.reserve_len_exact(10);
205     /// assert!(map.capacity() >= 10);
206     /// ```
207     #[stable(feature = "rust1", since = "1.0.0")]
208     pub fn reserve_len_exact(&mut self, len: usize) {
209         let cur_len = self.v.len();
210         if len >= cur_len {
211             self.v.reserve_exact(len - cur_len);
212         }
213     }
214
215     /// Returns an iterator visiting all keys in ascending order of the keys.
216     /// The iterator's element type is `usize`.
217     #[stable(feature = "rust1", since = "1.0.0")]
218     pub fn keys<'r>(&'r self) -> Keys<'r, V> {
219         fn first<A, B>((a, _): (A, B)) -> A { a }
220         let first: fn((usize, &'r V)) -> usize = first; // coerce to fn pointer
221
222         Keys { iter: self.iter().map(first) }
223     }
224
225     /// Returns an iterator visiting all values in ascending order of the keys.
226     /// The iterator's element type is `&'r V`.
227     #[stable(feature = "rust1", since = "1.0.0")]
228     pub fn values<'r>(&'r self) -> Values<'r, V> {
229         fn second<A, B>((_, b): (A, B)) -> B { b }
230         let second: fn((usize, &'r V)) -> &'r V = second; // coerce to fn pointer
231
232         Values { iter: self.iter().map(second) }
233     }
234
235     /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
236     /// The iterator's element type is `(usize, &'r V)`.
237     ///
238     /// # Examples
239     ///
240     /// ```
241     /// use std::collections::VecMap;
242     ///
243     /// let mut map = VecMap::new();
244     /// map.insert(1, "a");
245     /// map.insert(3, "c");
246     /// map.insert(2, "b");
247     ///
248     /// // Print `1: a` then `2: b` then `3: c`
249     /// for (key, value) in map.iter() {
250     ///     println!("{}: {}", key, value);
251     /// }
252     /// ```
253     #[stable(feature = "rust1", since = "1.0.0")]
254     pub fn iter<'r>(&'r self) -> Iter<'r, V> {
255         Iter {
256             front: 0,
257             back: self.v.len(),
258             iter: self.v.iter()
259         }
260     }
261
262     /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
263     /// with mutable references to the values.
264     /// The iterator's element type is `(usize, &'r mut V)`.
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// use std::collections::VecMap;
270     ///
271     /// let mut map = VecMap::new();
272     /// map.insert(1, "a");
273     /// map.insert(2, "b");
274     /// map.insert(3, "c");
275     ///
276     /// for (key, value) in map.iter_mut() {
277     ///     *value = "x";
278     /// }
279     ///
280     /// for (key, value) in map.iter() {
281     ///     assert_eq!(value, &"x");
282     /// }
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
286         IterMut {
287             front: 0,
288             back: self.v.len(),
289             iter: self.v.iter_mut()
290         }
291     }
292
293     /// Returns an iterator visiting all key-value pairs in ascending order of
294     /// the keys, consuming the original `VecMap`.
295     /// The iterator's element type is `(usize, &'r V)`.
296     ///
297     /// # Examples
298     ///
299     /// ```
300     /// use std::collections::VecMap;
301     ///
302     /// let mut map = VecMap::new();
303     /// map.insert(1, "a");
304     /// map.insert(3, "c");
305     /// map.insert(2, "b");
306     ///
307     /// let vec: Vec<(usize, &str)> = map.into_iter().collect();
308     ///
309     /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
310     /// ```
311     #[stable(feature = "rust1", since = "1.0.0")]
312     pub fn into_iter(self) -> IntoIter<V> {
313         fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
314             v.map(|v| (i, v))
315         }
316         let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
317
318         IntoIter { iter: self.v.into_iter().enumerate().filter_map(filter) }
319     }
320
321     /// Returns an iterator visiting all key-value pairs in ascending order of
322     /// the keys, emptying (but not consuming) the original `VecMap`.
323     /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.
324     ///
325     /// # Examples
326     ///
327     /// ```
328     /// use std::collections::VecMap;
329     ///
330     /// let mut map = VecMap::new();
331     /// map.insert(1, "a");
332     /// map.insert(3, "c");
333     /// map.insert(2, "b");
334     ///
335     /// let vec: Vec<(usize, &str)> = map.drain().collect();
336     ///
337     /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
338     /// ```
339     #[unstable(feature = "collections",
340                reason = "matches collection reform specification, waiting for dust to settle")]
341     pub fn drain<'a>(&'a mut self) -> Drain<'a, V> {
342         fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
343             v.map(|v| (i, v))
344         }
345         let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
346
347         Drain { iter: self.v.drain().enumerate().filter_map(filter) }
348     }
349
350     /// Return the number of elements in the map.
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// use std::collections::VecMap;
356     ///
357     /// let mut a = VecMap::new();
358     /// assert_eq!(a.len(), 0);
359     /// a.insert(1, "a");
360     /// assert_eq!(a.len(), 1);
361     /// ```
362     #[stable(feature = "rust1", since = "1.0.0")]
363     pub fn len(&self) -> usize {
364         self.v.iter().filter(|elt| elt.is_some()).count()
365     }
366
367     /// Return true if the map contains no elements.
368     ///
369     /// # Examples
370     ///
371     /// ```
372     /// use std::collections::VecMap;
373     ///
374     /// let mut a = VecMap::new();
375     /// assert!(a.is_empty());
376     /// a.insert(1, "a");
377     /// assert!(!a.is_empty());
378     /// ```
379     #[stable(feature = "rust1", since = "1.0.0")]
380     pub fn is_empty(&self) -> bool {
381         self.v.iter().all(|elt| elt.is_none())
382     }
383
384     /// Clears the map, removing all key-value pairs.
385     ///
386     /// # Examples
387     ///
388     /// ```
389     /// use std::collections::VecMap;
390     ///
391     /// let mut a = VecMap::new();
392     /// a.insert(1, "a");
393     /// a.clear();
394     /// assert!(a.is_empty());
395     /// ```
396     #[stable(feature = "rust1", since = "1.0.0")]
397     pub fn clear(&mut self) { self.v.clear() }
398
399     /// Returns a reference to the value corresponding to the key.
400     ///
401     /// # Examples
402     ///
403     /// ```
404     /// use std::collections::VecMap;
405     ///
406     /// let mut map = VecMap::new();
407     /// map.insert(1, "a");
408     /// assert_eq!(map.get(&1), Some(&"a"));
409     /// assert_eq!(map.get(&2), None);
410     /// ```
411     #[stable(feature = "rust1", since = "1.0.0")]
412     pub fn get(&self, key: &usize) -> Option<&V> {
413         if *key < self.v.len() {
414             match self.v[*key] {
415               Some(ref value) => Some(value),
416               None => None
417             }
418         } else {
419             None
420         }
421     }
422
423     /// Returns true if the map contains a value for the specified key.
424     ///
425     /// # Examples
426     ///
427     /// ```
428     /// use std::collections::VecMap;
429     ///
430     /// let mut map = VecMap::new();
431     /// map.insert(1, "a");
432     /// assert_eq!(map.contains_key(&1), true);
433     /// assert_eq!(map.contains_key(&2), false);
434     /// ```
435     #[inline]
436     #[stable(feature = "rust1", since = "1.0.0")]
437     pub fn contains_key(&self, key: &usize) -> bool {
438         self.get(key).is_some()
439     }
440
441     /// Returns a mutable reference to the value corresponding to the key.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// use std::collections::VecMap;
447     ///
448     /// let mut map = VecMap::new();
449     /// map.insert(1, "a");
450     /// match map.get_mut(&1) {
451     ///     Some(x) => *x = "b",
452     ///     None => (),
453     /// }
454     /// assert_eq!(map[1], "b");
455     /// ```
456     #[stable(feature = "rust1", since = "1.0.0")]
457     pub fn get_mut(&mut self, key: &usize) -> Option<&mut V> {
458         if *key < self.v.len() {
459             match *(&mut self.v[*key]) {
460               Some(ref mut value) => Some(value),
461               None => None
462             }
463         } else {
464             None
465         }
466     }
467
468     /// Inserts a key-value pair from the map. If the key already had a value
469     /// present in the map, that value is returned. Otherwise, `None` is returned.
470     ///
471     /// # Examples
472     ///
473     /// ```
474     /// use std::collections::VecMap;
475     ///
476     /// let mut map = VecMap::new();
477     /// assert_eq!(map.insert(37, "a"), None);
478     /// assert_eq!(map.is_empty(), false);
479     ///
480     /// map.insert(37, "b");
481     /// assert_eq!(map.insert(37, "c"), Some("b"));
482     /// assert_eq!(map[37], "c");
483     /// ```
484     #[stable(feature = "rust1", since = "1.0.0")]
485     pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
486         let len = self.v.len();
487         if len <= key {
488             self.v.extend((0..key - len + 1).map(|_| None));
489         }
490         replace(&mut self.v[key], Some(value))
491     }
492
493     /// Removes a key from the map, returning the value at the key if the key
494     /// was previously in the map.
495     ///
496     /// # Examples
497     ///
498     /// ```
499     /// use std::collections::VecMap;
500     ///
501     /// let mut map = VecMap::new();
502     /// map.insert(1, "a");
503     /// assert_eq!(map.remove(&1), Some("a"));
504     /// assert_eq!(map.remove(&1), None);
505     /// ```
506     #[stable(feature = "rust1", since = "1.0.0")]
507     pub fn remove(&mut self, key: &usize) -> Option<V> {
508         if *key >= self.v.len() {
509             return None;
510         }
511         let result = &mut self.v[*key];
512         result.take()
513     }
514
515     /// Gets the given key's corresponding entry in the map for in-place manipulation.
516     ///
517     /// # Examples
518     ///
519     /// ```
520     /// use std::collections::VecMap;
521     /// use std::collections::vec_map::Entry;
522     ///
523     /// let mut count: VecMap<u32> = VecMap::new();
524     ///
525     /// // count the number of occurrences of numbers in the vec
526     /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4].iter() {
527     ///     match count.entry(*x) {
528     ///         Entry::Vacant(view) => {
529     ///             view.insert(1);
530     ///         },
531     ///         Entry::Occupied(mut view) => {
532     ///             let v = view.get_mut();
533     ///             *v += 1;
534     ///         },
535     ///     }
536     /// }
537     ///
538     /// assert_eq!(count[1], 3);
539     /// ```
540     #[stable(feature = "rust1", since = "1.0.0")]
541     pub fn entry(&mut self, key: usize) -> Entry<V> {
542         // FIXME(Gankro): this is basically the dumbest implementation of
543         // entry possible, because weird non-lexical borrows issues make it
544         // completely insane to do any other way. That said, Entry is a border-line
545         // useless construct on VecMap, so it's hardly a big loss.
546         if self.contains_key(&key) {
547             Occupied(OccupiedEntry {
548                 map: self,
549                 index: key,
550             })
551         } else {
552             Vacant(VacantEntry {
553                 map: self,
554                 index: key,
555             })
556         }
557     }
558 }
559
560
561 impl<'a, V> Entry<'a, V> {
562     #[unstable(feature = "collections",
563                reason = "matches collection reform v2 specification, waiting for dust to settle")]
564     /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
565     pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> {
566         match self {
567             Occupied(entry) => Ok(entry.into_mut()),
568             Vacant(entry) => Err(entry),
569         }
570     }
571 }
572
573 impl<'a, V> VacantEntry<'a, V> {
574     /// Sets the value of the entry with the VacantEntry's key,
575     /// and returns a mutable reference to it.
576     #[stable(feature = "rust1", since = "1.0.0")]
577     pub fn insert(self, value: V) -> &'a mut V {
578         let index = self.index;
579         self.map.insert(index, value);
580         &mut self.map[index]
581     }
582 }
583
584 impl<'a, V> OccupiedEntry<'a, V> {
585     /// Gets a reference to the value in the entry.
586     #[stable(feature = "rust1", since = "1.0.0")]
587     pub fn get(&self) -> &V {
588         let index = self.index;
589         &self.map[index]
590     }
591
592     /// Gets a mutable reference to the value in the entry.
593     #[stable(feature = "rust1", since = "1.0.0")]
594     pub fn get_mut(&mut self) -> &mut V {
595         let index = self.index;
596         &mut self.map[index]
597     }
598
599     /// Converts the entry into a mutable reference to its value.
600     #[stable(feature = "rust1", since = "1.0.0")]
601     pub fn into_mut(self) -> &'a mut V {
602         let index = self.index;
603         &mut self.map[index]
604     }
605
606     /// Sets the value of the entry with the OccupiedEntry's key,
607     /// and returns the entry's old value.
608     #[stable(feature = "rust1", since = "1.0.0")]
609     pub fn insert(&mut self, value: V) -> V {
610         let index = self.index;
611         self.map.insert(index, value).unwrap()
612     }
613
614     /// Takes the value of the entry out of the map, and returns it.
615     #[stable(feature = "rust1", since = "1.0.0")]
616     pub fn remove(self) -> V {
617         let index = self.index;
618         self.map.remove(&index).unwrap()
619     }
620 }
621
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<V: PartialEq> PartialEq for VecMap<V> {
624     fn eq(&self, other: &VecMap<V>) -> bool {
625         iter::order::eq(self.iter(), other.iter())
626     }
627 }
628
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<V: Eq> Eq for VecMap<V> {}
631
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl<V: PartialOrd> PartialOrd for VecMap<V> {
634     #[inline]
635     fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {
636         iter::order::partial_cmp(self.iter(), other.iter())
637     }
638 }
639
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<V: Ord> Ord for VecMap<V> {
642     #[inline]
643     fn cmp(&self, other: &VecMap<V>) -> Ordering {
644         iter::order::cmp(self.iter(), other.iter())
645     }
646 }
647
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
650     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651         try!(write!(f, "VecMap {{"));
652
653         for (i, (k, v)) in self.iter().enumerate() {
654             if i != 0 { try!(write!(f, ", ")); }
655             try!(write!(f, "{}: {:?}", k, *v));
656         }
657
658         write!(f, "}}")
659     }
660 }
661
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl<V> FromIterator<(usize, V)> for VecMap<V> {
664     fn from_iter<Iter: Iterator<Item=(usize, V)>>(iter: Iter) -> VecMap<V> {
665         let mut map = VecMap::new();
666         map.extend(iter);
667         map
668     }
669 }
670
671 impl<T> IntoIterator for VecMap<T> {
672     type Iter = IntoIter<T>;
673
674     fn into_iter(self) -> IntoIter<T> {
675         self.into_iter()
676     }
677 }
678
679 impl<'a, T> IntoIterator for &'a VecMap<T> {
680     type Iter = Iter<'a, T>;
681
682     fn into_iter(self) -> Iter<'a, T> {
683         self.iter()
684     }
685 }
686
687 impl<'a, T> IntoIterator for &'a mut VecMap<T> {
688     type Iter = IterMut<'a, T>;
689
690     fn into_iter(mut self) -> IterMut<'a, T> {
691         self.iter_mut()
692     }
693 }
694
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<V> Extend<(usize, V)> for VecMap<V> {
697     fn extend<Iter: Iterator<Item=(usize, V)>>(&mut self, iter: Iter) {
698         for (k, v) in iter {
699             self.insert(k, v);
700         }
701     }
702 }
703
704 impl<V> Index<usize> for VecMap<V> {
705     type Output = V;
706
707     #[inline]
708     fn index<'a>(&'a self, i: &usize) -> &'a V {
709         self.get(i).expect("key not present")
710     }
711 }
712
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl<V> IndexMut<usize> for VecMap<V> {
715     type Output = V;
716
717     #[inline]
718     fn index_mut<'a>(&'a mut self, i: &usize) -> &'a mut V {
719         self.get_mut(i).expect("key not present")
720     }
721 }
722
723 macro_rules! iterator {
724     (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
725         #[stable(feature = "rust1", since = "1.0.0")]
726         impl<'a, V> Iterator for $name<'a, V> {
727             type Item = $elem;
728
729             #[inline]
730             fn next(&mut self) -> Option<$elem> {
731                 while self.front < self.back {
732                     match self.iter.next() {
733                         Some(elem) => {
734                             match elem$(. $getter ())+ {
735                                 Some(x) => {
736                                     let index = self.front;
737                                     self.front += 1;
738                                     return Some((index, x));
739                                 },
740                                 None => {},
741                             }
742                         }
743                         _ => ()
744                     }
745                     self.front += 1;
746                 }
747                 None
748             }
749
750             #[inline]
751             fn size_hint(&self) -> (usize, Option<usize>) {
752                 (0, Some(self.back - self.front))
753             }
754         }
755     }
756 }
757
758 macro_rules! double_ended_iterator {
759     (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
760         #[stable(feature = "rust1", since = "1.0.0")]
761         impl<'a, V> DoubleEndedIterator for $name<'a, V> {
762             #[inline]
763             fn next_back(&mut self) -> Option<$elem> {
764                 while self.front < self.back {
765                     match self.iter.next_back() {
766                         Some(elem) => {
767                             match elem$(. $getter ())+ {
768                                 Some(x) => {
769                                     self.back -= 1;
770                                     return Some((self.back, x));
771                                 },
772                                 None => {},
773                             }
774                         }
775                         _ => ()
776                     }
777                     self.back -= 1;
778                 }
779                 None
780             }
781         }
782     }
783 }
784
785 /// An iterator over the key-value pairs of a map.
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub struct Iter<'a, V:'a> {
788     front: usize,
789     back: usize,
790     iter: slice::Iter<'a, Option<V>>
791 }
792
793 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
794 impl<'a, V> Clone for Iter<'a, V> {
795     fn clone(&self) -> Iter<'a, V> {
796         Iter {
797             front: self.front,
798             back: self.back,
799             iter: self.iter.clone()
800         }
801     }
802 }
803
804 iterator! { impl Iter -> (usize, &'a V), as_ref }
805 double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }
806
807 /// An iterator over the key-value pairs of a map, with the
808 /// values being mutable.
809 #[stable(feature = "rust1", since = "1.0.0")]
810 pub struct IterMut<'a, V:'a> {
811     front: usize,
812     back: usize,
813     iter: slice::IterMut<'a, Option<V>>
814 }
815
816 iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
817 double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
818
819 /// An iterator over the keys of a map.
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub struct Keys<'a, V: 'a> {
822     iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> usize>
823 }
824
825 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
826 impl<'a, V> Clone for Keys<'a, V> {
827     fn clone(&self) -> Keys<'a, V> {
828         Keys {
829             iter: self.iter.clone()
830         }
831     }
832 }
833
834 /// An iterator over the values of a map.
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub struct Values<'a, V: 'a> {
837     iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> &'a V>
838 }
839
840 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
841 impl<'a, V> Clone for Values<'a, V> {
842     fn clone(&self) -> Values<'a, V> {
843         Values {
844             iter: self.iter.clone()
845         }
846     }
847 }
848
849 /// A consuming iterator over the key-value pairs of a map.
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub struct IntoIter<V> {
852     iter: FilterMap<
853     Enumerate<vec::IntoIter<Option<V>>>,
854     fn((usize, Option<V>)) -> Option<(usize, V)>>
855 }
856
857 #[unstable(feature = "collections")]
858 pub struct Drain<'a, V> {
859     iter: FilterMap<
860     Enumerate<vec::Drain<'a, Option<V>>>,
861     fn((usize, Option<V>)) -> Option<(usize, V)>>
862 }
863
864 #[unstable(feature = "collections")]
865 impl<'a, V> Iterator for Drain<'a, V> {
866     type Item = (usize, V);
867
868     fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
869     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
870 }
871
872 #[unstable(feature = "collections")]
873 impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
874     fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
875 }
876
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl<'a, V> Iterator for Keys<'a, V> {
879     type Item = usize;
880
881     fn next(&mut self) -> Option<usize> { self.iter.next() }
882     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
883 }
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
886     fn next_back(&mut self) -> Option<usize> { self.iter.next_back() }
887 }
888
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<'a, V> Iterator for Values<'a, V> {
891     type Item = &'a V;
892
893     fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
894     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
895 }
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
898     fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
899 }
900
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<V> Iterator for IntoIter<V> {
903     type Item = (usize, V);
904
905     fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
906     fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
907 }
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<V> DoubleEndedIterator for IntoIter<V> {
910     fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
911 }
912
913 #[cfg(test)]
914 mod test_map {
915     use prelude::*;
916     use core::hash::{hash, SipHasher};
917
918     use super::VecMap;
919     use super::Entry::{Occupied, Vacant};
920
921     #[test]
922     fn test_get_mut() {
923         let mut m = VecMap::new();
924         assert!(m.insert(1, 12).is_none());
925         assert!(m.insert(2, 8).is_none());
926         assert!(m.insert(5, 14).is_none());
927         let new = 100;
928         match m.get_mut(&5) {
929             None => panic!(), Some(x) => *x = new
930         }
931         assert_eq!(m.get(&5), Some(&new));
932     }
933
934     #[test]
935     fn test_len() {
936         let mut map = VecMap::new();
937         assert_eq!(map.len(), 0);
938         assert!(map.is_empty());
939         assert!(map.insert(5, 20).is_none());
940         assert_eq!(map.len(), 1);
941         assert!(!map.is_empty());
942         assert!(map.insert(11, 12).is_none());
943         assert_eq!(map.len(), 2);
944         assert!(!map.is_empty());
945         assert!(map.insert(14, 22).is_none());
946         assert_eq!(map.len(), 3);
947         assert!(!map.is_empty());
948     }
949
950     #[test]
951     fn test_clear() {
952         let mut map = VecMap::new();
953         assert!(map.insert(5, 20).is_none());
954         assert!(map.insert(11, 12).is_none());
955         assert!(map.insert(14, 22).is_none());
956         map.clear();
957         assert!(map.is_empty());
958         assert!(map.get(&5).is_none());
959         assert!(map.get(&11).is_none());
960         assert!(map.get(&14).is_none());
961     }
962
963     #[test]
964     fn test_insert() {
965         let mut m = VecMap::new();
966         assert_eq!(m.insert(1, 2), None);
967         assert_eq!(m.insert(1, 3), Some(2));
968         assert_eq!(m.insert(1, 4), Some(3));
969     }
970
971     #[test]
972     fn test_remove() {
973         let mut m = VecMap::new();
974         m.insert(1, 2);
975         assert_eq!(m.remove(&1), Some(2));
976         assert_eq!(m.remove(&1), None);
977     }
978
979     #[test]
980     fn test_keys() {
981         let mut map = VecMap::new();
982         map.insert(1, 'a');
983         map.insert(2, 'b');
984         map.insert(3, 'c');
985         let keys: Vec<_> = map.keys().collect();
986         assert_eq!(keys.len(), 3);
987         assert!(keys.contains(&1));
988         assert!(keys.contains(&2));
989         assert!(keys.contains(&3));
990     }
991
992     #[test]
993     fn test_values() {
994         let mut map = VecMap::new();
995         map.insert(1, 'a');
996         map.insert(2, 'b');
997         map.insert(3, 'c');
998         let values: Vec<_> = map.values().cloned().collect();
999         assert_eq!(values.len(), 3);
1000         assert!(values.contains(&'a'));
1001         assert!(values.contains(&'b'));
1002         assert!(values.contains(&'c'));
1003     }
1004
1005     #[test]
1006     fn test_iterator() {
1007         let mut m = VecMap::new();
1008
1009         assert!(m.insert(0, 1).is_none());
1010         assert!(m.insert(1, 2).is_none());
1011         assert!(m.insert(3, 5).is_none());
1012         assert!(m.insert(6, 10).is_none());
1013         assert!(m.insert(10, 11).is_none());
1014
1015         let mut it = m.iter();
1016         assert_eq!(it.size_hint(), (0, Some(11)));
1017         assert_eq!(it.next().unwrap(), (0, &1));
1018         assert_eq!(it.size_hint(), (0, Some(10)));
1019         assert_eq!(it.next().unwrap(), (1, &2));
1020         assert_eq!(it.size_hint(), (0, Some(9)));
1021         assert_eq!(it.next().unwrap(), (3, &5));
1022         assert_eq!(it.size_hint(), (0, Some(7)));
1023         assert_eq!(it.next().unwrap(), (6, &10));
1024         assert_eq!(it.size_hint(), (0, Some(4)));
1025         assert_eq!(it.next().unwrap(), (10, &11));
1026         assert_eq!(it.size_hint(), (0, Some(0)));
1027         assert!(it.next().is_none());
1028     }
1029
1030     #[test]
1031     fn test_iterator_size_hints() {
1032         let mut m = VecMap::new();
1033
1034         assert!(m.insert(0, 1).is_none());
1035         assert!(m.insert(1, 2).is_none());
1036         assert!(m.insert(3, 5).is_none());
1037         assert!(m.insert(6, 10).is_none());
1038         assert!(m.insert(10, 11).is_none());
1039
1040         assert_eq!(m.iter().size_hint(), (0, Some(11)));
1041         assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
1042         assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
1043         assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
1044     }
1045
1046     #[test]
1047     fn test_mut_iterator() {
1048         let mut m = VecMap::new();
1049
1050         assert!(m.insert(0, 1).is_none());
1051         assert!(m.insert(1, 2).is_none());
1052         assert!(m.insert(3, 5).is_none());
1053         assert!(m.insert(6, 10).is_none());
1054         assert!(m.insert(10, 11).is_none());
1055
1056         for (k, v) in &mut m {
1057             *v += k as isize;
1058         }
1059
1060         let mut it = m.iter();
1061         assert_eq!(it.next().unwrap(), (0, &1));
1062         assert_eq!(it.next().unwrap(), (1, &3));
1063         assert_eq!(it.next().unwrap(), (3, &8));
1064         assert_eq!(it.next().unwrap(), (6, &16));
1065         assert_eq!(it.next().unwrap(), (10, &21));
1066         assert!(it.next().is_none());
1067     }
1068
1069     #[test]
1070     fn test_rev_iterator() {
1071         let mut m = VecMap::new();
1072
1073         assert!(m.insert(0, 1).is_none());
1074         assert!(m.insert(1, 2).is_none());
1075         assert!(m.insert(3, 5).is_none());
1076         assert!(m.insert(6, 10).is_none());
1077         assert!(m.insert(10, 11).is_none());
1078
1079         let mut it = m.iter().rev();
1080         assert_eq!(it.next().unwrap(), (10, &11));
1081         assert_eq!(it.next().unwrap(), (6, &10));
1082         assert_eq!(it.next().unwrap(), (3, &5));
1083         assert_eq!(it.next().unwrap(), (1, &2));
1084         assert_eq!(it.next().unwrap(), (0, &1));
1085         assert!(it.next().is_none());
1086     }
1087
1088     #[test]
1089     fn test_mut_rev_iterator() {
1090         let mut m = VecMap::new();
1091
1092         assert!(m.insert(0, 1).is_none());
1093         assert!(m.insert(1, 2).is_none());
1094         assert!(m.insert(3, 5).is_none());
1095         assert!(m.insert(6, 10).is_none());
1096         assert!(m.insert(10, 11).is_none());
1097
1098         for (k, v) in m.iter_mut().rev() {
1099             *v += k as isize;
1100         }
1101
1102         let mut it = m.iter();
1103         assert_eq!(it.next().unwrap(), (0, &1));
1104         assert_eq!(it.next().unwrap(), (1, &3));
1105         assert_eq!(it.next().unwrap(), (3, &8));
1106         assert_eq!(it.next().unwrap(), (6, &16));
1107         assert_eq!(it.next().unwrap(), (10, &21));
1108         assert!(it.next().is_none());
1109     }
1110
1111     #[test]
1112     fn test_move_iter() {
1113         let mut m = VecMap::new();
1114         m.insert(1, box 2);
1115         let mut called = false;
1116         for (k, v) in m {
1117             assert!(!called);
1118             called = true;
1119             assert_eq!(k, 1);
1120             assert_eq!(v, box 2);
1121         }
1122         assert!(called);
1123     }
1124
1125     #[test]
1126     fn test_drain_iterator() {
1127         let mut map = VecMap::new();
1128         map.insert(1, "a");
1129         map.insert(3, "c");
1130         map.insert(2, "b");
1131
1132         let vec: Vec<_> = map.drain().collect();
1133
1134         assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
1135         assert_eq!(map.len(), 0);
1136     }
1137
1138     #[test]
1139     fn test_show() {
1140         let mut map = VecMap::new();
1141         let empty = VecMap::<i32>::new();
1142
1143         map.insert(1, 2);
1144         map.insert(3, 4);
1145
1146         let map_str = format!("{:?}", map);
1147         assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
1148         assert_eq!(format!("{:?}", empty), "VecMap {}");
1149     }
1150
1151     #[test]
1152     fn test_clone() {
1153         let mut a = VecMap::new();
1154
1155         a.insert(1, 'x');
1156         a.insert(4, 'y');
1157         a.insert(6, 'z');
1158
1159         assert!(a.clone() == a);
1160     }
1161
1162     #[test]
1163     fn test_eq() {
1164         let mut a = VecMap::new();
1165         let mut b = VecMap::new();
1166
1167         assert!(a == b);
1168         assert!(a.insert(0, 5).is_none());
1169         assert!(a != b);
1170         assert!(b.insert(0, 4).is_none());
1171         assert!(a != b);
1172         assert!(a.insert(5, 19).is_none());
1173         assert!(a != b);
1174         assert!(!b.insert(0, 5).is_none());
1175         assert!(a != b);
1176         assert!(b.insert(5, 19).is_none());
1177         assert!(a == b);
1178
1179         a = VecMap::new();
1180         b = VecMap::with_capacity(1);
1181         assert!(a == b);
1182     }
1183
1184     #[test]
1185     fn test_lt() {
1186         let mut a = VecMap::new();
1187         let mut b = VecMap::new();
1188
1189         assert!(!(a < b) && !(b < a));
1190         assert!(b.insert(2, 5).is_none());
1191         assert!(a < b);
1192         assert!(a.insert(2, 7).is_none());
1193         assert!(!(a < b) && b < a);
1194         assert!(b.insert(1, 0).is_none());
1195         assert!(b < a);
1196         assert!(a.insert(0, 6).is_none());
1197         assert!(a < b);
1198         assert!(a.insert(6, 2).is_none());
1199         assert!(a < b && !(b < a));
1200     }
1201
1202     #[test]
1203     fn test_ord() {
1204         let mut a = VecMap::new();
1205         let mut b = VecMap::new();
1206
1207         assert!(a <= b && a >= b);
1208         assert!(a.insert(1, 1).is_none());
1209         assert!(a > b && a >= b);
1210         assert!(b < a && b <= a);
1211         assert!(b.insert(2, 2).is_none());
1212         assert!(b > a && b >= a);
1213         assert!(a < b && a <= b);
1214     }
1215
1216     #[test]
1217     fn test_hash() {
1218         let mut x = VecMap::new();
1219         let mut y = VecMap::new();
1220
1221         assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1222         x.insert(1, 'a');
1223         x.insert(2, 'b');
1224         x.insert(3, 'c');
1225
1226         y.insert(3, 'c');
1227         y.insert(2, 'b');
1228         y.insert(1, 'a');
1229
1230         assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1231
1232         x.insert(1000, 'd');
1233         x.remove(&1000);
1234
1235         assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1236     }
1237
1238     #[test]
1239     fn test_from_iter() {
1240         let xs = vec![(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1241
1242         let map: VecMap<_> = xs.iter().cloned().collect();
1243
1244         for &(k, v) in &xs {
1245             assert_eq!(map.get(&k), Some(&v));
1246         }
1247     }
1248
1249     #[test]
1250     fn test_index() {
1251         let mut map = VecMap::new();
1252
1253         map.insert(1, 2);
1254         map.insert(2, 1);
1255         map.insert(3, 4);
1256
1257         assert_eq!(map[3], 4);
1258     }
1259
1260     #[test]
1261     #[should_fail]
1262     fn test_index_nonexistent() {
1263         let mut map = VecMap::new();
1264
1265         map.insert(1, 2);
1266         map.insert(2, 1);
1267         map.insert(3, 4);
1268
1269         map[4];
1270     }
1271
1272     #[test]
1273     fn test_entry(){
1274         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1275
1276         let mut map: VecMap<_> = xs.iter().cloned().collect();
1277
1278         // Existing key (insert)
1279         match map.entry(1) {
1280             Vacant(_) => unreachable!(),
1281             Occupied(mut view) => {
1282                 assert_eq!(view.get(), &10);
1283                 assert_eq!(view.insert(100), 10);
1284             }
1285         }
1286         assert_eq!(map.get(&1).unwrap(), &100);
1287         assert_eq!(map.len(), 6);
1288
1289
1290         // Existing key (update)
1291         match map.entry(2) {
1292             Vacant(_) => unreachable!(),
1293             Occupied(mut view) => {
1294                 let v = view.get_mut();
1295                 *v *= 10;
1296             }
1297         }
1298         assert_eq!(map.get(&2).unwrap(), &200);
1299         assert_eq!(map.len(), 6);
1300
1301         // Existing key (take)
1302         match map.entry(3) {
1303             Vacant(_) => unreachable!(),
1304             Occupied(view) => {
1305                 assert_eq!(view.remove(), 30);
1306             }
1307         }
1308         assert_eq!(map.get(&3), None);
1309         assert_eq!(map.len(), 5);
1310
1311
1312         // Inexistent key (insert)
1313         match map.entry(10) {
1314             Occupied(_) => unreachable!(),
1315             Vacant(view) => {
1316                 assert_eq!(*view.insert(1000), 1000);
1317             }
1318         }
1319         assert_eq!(map.get(&10).unwrap(), &1000);
1320         assert_eq!(map.len(), 6);
1321     }
1322 }
1323
1324 #[cfg(test)]
1325 mod bench {
1326     use test::Bencher;
1327     use super::VecMap;
1328     use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1329
1330     #[bench]
1331     pub fn insert_rand_100(b: &mut Bencher) {
1332         let mut m = VecMap::new();
1333         insert_rand_n(100, &mut m, b,
1334                       |m, i| { m.insert(i, 1); },
1335                       |m, i| { m.remove(&i); });
1336     }
1337
1338     #[bench]
1339     pub fn insert_rand_10_000(b: &mut Bencher) {
1340         let mut m = VecMap::new();
1341         insert_rand_n(10_000, &mut m, b,
1342                       |m, i| { m.insert(i, 1); },
1343                       |m, i| { m.remove(&i); });
1344     }
1345
1346     // Insert seq
1347     #[bench]
1348     pub fn insert_seq_100(b: &mut Bencher) {
1349         let mut m = VecMap::new();
1350         insert_seq_n(100, &mut m, b,
1351                      |m, i| { m.insert(i, 1); },
1352                      |m, i| { m.remove(&i); });
1353     }
1354
1355     #[bench]
1356     pub fn insert_seq_10_000(b: &mut Bencher) {
1357         let mut m = VecMap::new();
1358         insert_seq_n(10_000, &mut m, b,
1359                      |m, i| { m.insert(i, 1); },
1360                      |m, i| { m.remove(&i); });
1361     }
1362
1363     // Find rand
1364     #[bench]
1365     pub fn find_rand_100(b: &mut Bencher) {
1366         let mut m = VecMap::new();
1367         find_rand_n(100, &mut m, b,
1368                     |m, i| { m.insert(i, 1); },
1369                     |m, i| { m.get(&i); });
1370     }
1371
1372     #[bench]
1373     pub fn find_rand_10_000(b: &mut Bencher) {
1374         let mut m = VecMap::new();
1375         find_rand_n(10_000, &mut m, b,
1376                     |m, i| { m.insert(i, 1); },
1377                     |m, i| { m.get(&i); });
1378     }
1379
1380     // Find seq
1381     #[bench]
1382     pub fn find_seq_100(b: &mut Bencher) {
1383         let mut m = VecMap::new();
1384         find_seq_n(100, &mut m, b,
1385                    |m, i| { m.insert(i, 1); },
1386                    |m, i| { m.get(&i); });
1387     }
1388
1389     #[bench]
1390     pub fn find_seq_10_000(b: &mut Bencher) {
1391         let mut m = VecMap::new();
1392         find_seq_n(10_000, &mut m, b,
1393                    |m, i| { m.insert(i, 1); },
1394                    |m, i| { m.get(&i); });
1395     }
1396 }