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