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