]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec_map.rs
Remove all `i` suffixes
[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};
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.iter() {
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 #[stable(feature = "rust1", since = "1.0.0")]
540 impl<V> Extend<(uint, V)> for VecMap<V> {
541     fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) {
542         for (k, v) in iter {
543             self.insert(k, v);
544         }
545     }
546 }
547
548 impl<V> Index<uint> for VecMap<V> {
549     type Output = V;
550
551     #[inline]
552     fn index<'a>(&'a self, i: &uint) -> &'a V {
553         self.get(i).expect("key not present")
554     }
555 }
556
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<V> IndexMut<uint> for VecMap<V> {
559     type Output = V;
560
561     #[inline]
562     fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
563         self.get_mut(i).expect("key not present")
564     }
565 }
566
567 macro_rules! iterator {
568     (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
569         #[stable(feature = "rust1", since = "1.0.0")]
570         impl<'a, V> Iterator for $name<'a, V> {
571             type Item = $elem;
572
573             #[inline]
574             fn next(&mut self) -> Option<$elem> {
575                 while self.front < self.back {
576                     match self.iter.next() {
577                         Some(elem) => {
578                             match elem$(. $getter ())+ {
579                                 Some(x) => {
580                                     let index = self.front;
581                                     self.front += 1;
582                                     return Some((index, x));
583                                 },
584                                 None => {},
585                             }
586                         }
587                         _ => ()
588                     }
589                     self.front += 1;
590                 }
591                 None
592             }
593
594             #[inline]
595             fn size_hint(&self) -> (uint, Option<uint>) {
596                 (0, Some(self.back - self.front))
597             }
598         }
599     }
600 }
601
602 macro_rules! double_ended_iterator {
603     (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
604         #[stable(feature = "rust1", since = "1.0.0")]
605         impl<'a, V> DoubleEndedIterator for $name<'a, V> {
606             #[inline]
607             fn next_back(&mut self) -> Option<$elem> {
608                 while self.front < self.back {
609                     match self.iter.next_back() {
610                         Some(elem) => {
611                             match elem$(. $getter ())+ {
612                                 Some(x) => {
613                                     self.back -= 1;
614                                     return Some((self.back, x));
615                                 },
616                                 None => {},
617                             }
618                         }
619                         _ => ()
620                     }
621                     self.back -= 1;
622                 }
623                 None
624             }
625         }
626     }
627 }
628
629 /// An iterator over the key-value pairs of a map.
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub struct Iter<'a, V:'a> {
632     front: uint,
633     back: uint,
634     iter: slice::Iter<'a, Option<V>>
635 }
636
637 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
638 impl<'a, V> Clone for Iter<'a, V> {
639     fn clone(&self) -> Iter<'a, V> {
640         Iter {
641             front: self.front,
642             back: self.back,
643             iter: self.iter.clone()
644         }
645     }
646 }
647
648 iterator! { impl Iter -> (uint, &'a V), as_ref }
649 double_ended_iterator! { impl Iter -> (uint, &'a V), as_ref }
650
651 /// An iterator over the key-value pairs of a map, with the
652 /// values being mutable.
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub struct IterMut<'a, V:'a> {
655     front: uint,
656     back: uint,
657     iter: slice::IterMut<'a, Option<V>>
658 }
659
660 iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
661 double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
662
663 /// An iterator over the keys of a map.
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub struct Keys<'a, V: 'a> {
666     iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint>
667 }
668
669 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
670 impl<'a, V> Clone for Keys<'a, V> {
671     fn clone(&self) -> Keys<'a, V> {
672         Keys {
673             iter: self.iter.clone()
674         }
675     }
676 }
677
678 /// An iterator over the values of a map.
679 #[stable(feature = "rust1", since = "1.0.0")]
680 pub struct Values<'a, V: 'a> {
681     iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
682 }
683
684 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
685 impl<'a, V> Clone for Values<'a, V> {
686     fn clone(&self) -> Values<'a, V> {
687         Values {
688             iter: self.iter.clone()
689         }
690     }
691 }
692
693 /// A consuming iterator over the key-value pairs of a map.
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub struct IntoIter<V> {
696     iter: FilterMap<
697     (uint, Option<V>),
698     (uint, V),
699     Enumerate<vec::IntoIter<Option<V>>>,
700     fn((uint, Option<V>)) -> Option<(uint, V)>>
701 }
702
703 #[unstable(feature = "collections")]
704 pub struct Drain<'a, V> {
705     iter: FilterMap<
706     (uint, Option<V>),
707     (uint, V),
708     Enumerate<vec::Drain<'a, Option<V>>>,
709     fn((uint, Option<V>)) -> Option<(uint, V)>>
710 }
711
712 #[unstable(feature = "collections")]
713 impl<'a, V> Iterator for Drain<'a, V> {
714     type Item = (uint, V);
715
716     fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
717     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
718 }
719
720 #[unstable(feature = "collections")]
721 impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
722     fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
723 }
724
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl<'a, V> Iterator for Keys<'a, V> {
727     type Item = uint;
728
729     fn next(&mut self) -> Option<uint> { self.iter.next() }
730     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
731 }
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
734     fn next_back(&mut self) -> Option<uint> { self.iter.next_back() }
735 }
736
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<'a, V> Iterator for Values<'a, V> {
739     type Item = &'a V;
740
741     fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
742     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
743 }
744 #[stable(feature = "rust1", since = "1.0.0")]
745 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
746     fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
747 }
748
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<V> Iterator for IntoIter<V> {
751     type Item = (uint, V);
752
753     fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
754     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
755 }
756 #[stable(feature = "rust1", since = "1.0.0")]
757 impl<V> DoubleEndedIterator for IntoIter<V> {
758     fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
759 }
760
761 #[cfg(test)]
762 mod test_map {
763     use prelude::*;
764     use core::hash::{hash, SipHasher};
765
766     use super::VecMap;
767
768     #[test]
769     fn test_get_mut() {
770         let mut m = VecMap::new();
771         assert!(m.insert(1, 12).is_none());
772         assert!(m.insert(2, 8).is_none());
773         assert!(m.insert(5, 14).is_none());
774         let new = 100;
775         match m.get_mut(&5) {
776             None => panic!(), Some(x) => *x = new
777         }
778         assert_eq!(m.get(&5), Some(&new));
779     }
780
781     #[test]
782     fn test_len() {
783         let mut map = VecMap::new();
784         assert_eq!(map.len(), 0);
785         assert!(map.is_empty());
786         assert!(map.insert(5, 20).is_none());
787         assert_eq!(map.len(), 1);
788         assert!(!map.is_empty());
789         assert!(map.insert(11, 12).is_none());
790         assert_eq!(map.len(), 2);
791         assert!(!map.is_empty());
792         assert!(map.insert(14, 22).is_none());
793         assert_eq!(map.len(), 3);
794         assert!(!map.is_empty());
795     }
796
797     #[test]
798     fn test_clear() {
799         let mut map = VecMap::new();
800         assert!(map.insert(5, 20).is_none());
801         assert!(map.insert(11, 12).is_none());
802         assert!(map.insert(14, 22).is_none());
803         map.clear();
804         assert!(map.is_empty());
805         assert!(map.get(&5).is_none());
806         assert!(map.get(&11).is_none());
807         assert!(map.get(&14).is_none());
808     }
809
810     #[test]
811     fn test_insert() {
812         let mut m = VecMap::new();
813         assert_eq!(m.insert(1, 2), None);
814         assert_eq!(m.insert(1, 3), Some(2));
815         assert_eq!(m.insert(1, 4), Some(3));
816     }
817
818     #[test]
819     fn test_remove() {
820         let mut m = VecMap::new();
821         m.insert(1, 2);
822         assert_eq!(m.remove(&1), Some(2));
823         assert_eq!(m.remove(&1), None);
824     }
825
826     #[test]
827     fn test_keys() {
828         let mut map = VecMap::new();
829         map.insert(1, 'a');
830         map.insert(2, 'b');
831         map.insert(3, 'c');
832         let keys = map.keys().collect::<Vec<uint>>();
833         assert_eq!(keys.len(), 3);
834         assert!(keys.contains(&1));
835         assert!(keys.contains(&2));
836         assert!(keys.contains(&3));
837     }
838
839     #[test]
840     fn test_values() {
841         let mut map = VecMap::new();
842         map.insert(1, 'a');
843         map.insert(2, 'b');
844         map.insert(3, 'c');
845         let values = map.values().map(|&v| v).collect::<Vec<char>>();
846         assert_eq!(values.len(), 3);
847         assert!(values.contains(&'a'));
848         assert!(values.contains(&'b'));
849         assert!(values.contains(&'c'));
850     }
851
852     #[test]
853     fn test_iterator() {
854         let mut m = VecMap::new();
855
856         assert!(m.insert(0, 1).is_none());
857         assert!(m.insert(1, 2).is_none());
858         assert!(m.insert(3, 5).is_none());
859         assert!(m.insert(6, 10).is_none());
860         assert!(m.insert(10, 11).is_none());
861
862         let mut it = m.iter();
863         assert_eq!(it.size_hint(), (0, Some(11)));
864         assert_eq!(it.next().unwrap(), (0, &1));
865         assert_eq!(it.size_hint(), (0, Some(10)));
866         assert_eq!(it.next().unwrap(), (1, &2));
867         assert_eq!(it.size_hint(), (0, Some(9)));
868         assert_eq!(it.next().unwrap(), (3, &5));
869         assert_eq!(it.size_hint(), (0, Some(7)));
870         assert_eq!(it.next().unwrap(), (6, &10));
871         assert_eq!(it.size_hint(), (0, Some(4)));
872         assert_eq!(it.next().unwrap(), (10, &11));
873         assert_eq!(it.size_hint(), (0, Some(0)));
874         assert!(it.next().is_none());
875     }
876
877     #[test]
878     fn test_iterator_size_hints() {
879         let mut m = VecMap::new();
880
881         assert!(m.insert(0, 1).is_none());
882         assert!(m.insert(1, 2).is_none());
883         assert!(m.insert(3, 5).is_none());
884         assert!(m.insert(6, 10).is_none());
885         assert!(m.insert(10, 11).is_none());
886
887         assert_eq!(m.iter().size_hint(), (0, Some(11)));
888         assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
889         assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
890         assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
891     }
892
893     #[test]
894     fn test_mut_iterator() {
895         let mut m = VecMap::new();
896
897         assert!(m.insert(0, 1).is_none());
898         assert!(m.insert(1, 2).is_none());
899         assert!(m.insert(3, 5).is_none());
900         assert!(m.insert(6, 10).is_none());
901         assert!(m.insert(10, 11).is_none());
902
903         for (k, v) in m.iter_mut() {
904             *v += k as int;
905         }
906
907         let mut it = m.iter();
908         assert_eq!(it.next().unwrap(), (0, &1));
909         assert_eq!(it.next().unwrap(), (1, &3));
910         assert_eq!(it.next().unwrap(), (3, &8));
911         assert_eq!(it.next().unwrap(), (6, &16));
912         assert_eq!(it.next().unwrap(), (10, &21));
913         assert!(it.next().is_none());
914     }
915
916     #[test]
917     fn test_rev_iterator() {
918         let mut m = VecMap::new();
919
920         assert!(m.insert(0, 1).is_none());
921         assert!(m.insert(1, 2).is_none());
922         assert!(m.insert(3, 5).is_none());
923         assert!(m.insert(6, 10).is_none());
924         assert!(m.insert(10, 11).is_none());
925
926         let mut it = m.iter().rev();
927         assert_eq!(it.next().unwrap(), (10, &11));
928         assert_eq!(it.next().unwrap(), (6, &10));
929         assert_eq!(it.next().unwrap(), (3, &5));
930         assert_eq!(it.next().unwrap(), (1, &2));
931         assert_eq!(it.next().unwrap(), (0, &1));
932         assert!(it.next().is_none());
933     }
934
935     #[test]
936     fn test_mut_rev_iterator() {
937         let mut m = VecMap::new();
938
939         assert!(m.insert(0, 1).is_none());
940         assert!(m.insert(1, 2).is_none());
941         assert!(m.insert(3, 5).is_none());
942         assert!(m.insert(6, 10).is_none());
943         assert!(m.insert(10, 11).is_none());
944
945         for (k, v) in m.iter_mut().rev() {
946             *v += k as int;
947         }
948
949         let mut it = m.iter();
950         assert_eq!(it.next().unwrap(), (0, &1));
951         assert_eq!(it.next().unwrap(), (1, &3));
952         assert_eq!(it.next().unwrap(), (3, &8));
953         assert_eq!(it.next().unwrap(), (6, &16));
954         assert_eq!(it.next().unwrap(), (10, &21));
955         assert!(it.next().is_none());
956     }
957
958     #[test]
959     fn test_move_iter() {
960         let mut m = VecMap::new();
961         m.insert(1, box 2);
962         let mut called = false;
963         for (k, v) in m.into_iter() {
964             assert!(!called);
965             called = true;
966             assert_eq!(k, 1);
967             assert_eq!(v, box 2);
968         }
969         assert!(called);
970     }
971
972     #[test]
973     fn test_drain_iterator() {
974         let mut map = VecMap::new();
975         map.insert(1, "a");
976         map.insert(3, "c");
977         map.insert(2, "b");
978
979         let vec: Vec<(usize, &str)> = map.drain().collect();
980
981         assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
982         assert_eq!(map.len(), 0);
983     }
984
985     #[test]
986     fn test_show() {
987         let mut map = VecMap::new();
988         let empty = VecMap::<int>::new();
989
990         map.insert(1, 2);
991         map.insert(3, 4);
992
993         let map_str = format!("{:?}", map);
994         assert!(map_str == "VecMap {1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
995         assert_eq!(format!("{:?}", empty), "VecMap {}");
996     }
997
998     #[test]
999     fn test_clone() {
1000         let mut a = VecMap::new();
1001
1002         a.insert(1, 'x');
1003         a.insert(4, 'y');
1004         a.insert(6, 'z');
1005
1006         assert!(a.clone() == a);
1007     }
1008
1009     #[test]
1010     fn test_eq() {
1011         let mut a = VecMap::new();
1012         let mut b = VecMap::new();
1013
1014         assert!(a == b);
1015         assert!(a.insert(0, 5).is_none());
1016         assert!(a != b);
1017         assert!(b.insert(0, 4).is_none());
1018         assert!(a != b);
1019         assert!(a.insert(5, 19).is_none());
1020         assert!(a != b);
1021         assert!(!b.insert(0, 5).is_none());
1022         assert!(a != b);
1023         assert!(b.insert(5, 19).is_none());
1024         assert!(a == b);
1025
1026         a = VecMap::new();
1027         b = VecMap::with_capacity(1);
1028         assert!(a == b);
1029     }
1030
1031     #[test]
1032     fn test_lt() {
1033         let mut a = VecMap::new();
1034         let mut b = VecMap::new();
1035
1036         assert!(!(a < b) && !(b < a));
1037         assert!(b.insert(2u, 5).is_none());
1038         assert!(a < b);
1039         assert!(a.insert(2, 7).is_none());
1040         assert!(!(a < b) && b < a);
1041         assert!(b.insert(1, 0).is_none());
1042         assert!(b < a);
1043         assert!(a.insert(0, 6).is_none());
1044         assert!(a < b);
1045         assert!(a.insert(6, 2).is_none());
1046         assert!(a < b && !(b < a));
1047     }
1048
1049     #[test]
1050     fn test_ord() {
1051         let mut a = VecMap::new();
1052         let mut b = VecMap::new();
1053
1054         assert!(a <= b && a >= b);
1055         assert!(a.insert(1u, 1).is_none());
1056         assert!(a > b && a >= b);
1057         assert!(b < a && b <= a);
1058         assert!(b.insert(2, 2).is_none());
1059         assert!(b > a && b >= a);
1060         assert!(a < b && a <= b);
1061     }
1062
1063     #[test]
1064     fn test_hash() {
1065         let mut x = VecMap::new();
1066         let mut y = VecMap::new();
1067
1068         assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1069         x.insert(1, 'a');
1070         x.insert(2, 'b');
1071         x.insert(3, 'c');
1072
1073         y.insert(3, 'c');
1074         y.insert(2, 'b');
1075         y.insert(1, 'a');
1076
1077         assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1078
1079         x.insert(1000, 'd');
1080         x.remove(&1000);
1081
1082         assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y));
1083     }
1084
1085     #[test]
1086     fn test_from_iter() {
1087         let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1088
1089         let map: VecMap<char> = xs.iter().map(|&x| x).collect();
1090
1091         for &(k, v) in xs.iter() {
1092             assert_eq!(map.get(&k), Some(&v));
1093         }
1094     }
1095
1096     #[test]
1097     fn test_index() {
1098         let mut map: VecMap<int> = VecMap::new();
1099
1100         map.insert(1, 2);
1101         map.insert(2, 1);
1102         map.insert(3, 4);
1103
1104         assert_eq!(map[3], 4);
1105     }
1106
1107     #[test]
1108     #[should_fail]
1109     fn test_index_nonexistent() {
1110         let mut map: VecMap<int> = VecMap::new();
1111
1112         map.insert(1, 2);
1113         map.insert(2, 1);
1114         map.insert(3, 4);
1115
1116         map[4];
1117     }
1118 }
1119
1120 #[cfg(test)]
1121 mod bench {
1122     use test::Bencher;
1123     use super::VecMap;
1124     use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1125
1126     #[bench]
1127     pub fn insert_rand_100(b: &mut Bencher) {
1128         let mut m : VecMap<uint> = VecMap::new();
1129         insert_rand_n(100, &mut m, b,
1130                       |m, i| { m.insert(i, 1); },
1131                       |m, i| { m.remove(&i); });
1132     }
1133
1134     #[bench]
1135     pub fn insert_rand_10_000(b: &mut Bencher) {
1136         let mut m : VecMap<uint> = VecMap::new();
1137         insert_rand_n(10_000, &mut m, b,
1138                       |m, i| { m.insert(i, 1); },
1139                       |m, i| { m.remove(&i); });
1140     }
1141
1142     // Insert seq
1143     #[bench]
1144     pub fn insert_seq_100(b: &mut Bencher) {
1145         let mut m : VecMap<uint> = VecMap::new();
1146         insert_seq_n(100, &mut m, b,
1147                      |m, i| { m.insert(i, 1); },
1148                      |m, i| { m.remove(&i); });
1149     }
1150
1151     #[bench]
1152     pub fn insert_seq_10_000(b: &mut Bencher) {
1153         let mut m : VecMap<uint> = VecMap::new();
1154         insert_seq_n(10_000, &mut m, b,
1155                      |m, i| { m.insert(i, 1); },
1156                      |m, i| { m.remove(&i); });
1157     }
1158
1159     // Find rand
1160     #[bench]
1161     pub fn find_rand_100(b: &mut Bencher) {
1162         let mut m : VecMap<uint> = VecMap::new();
1163         find_rand_n(100, &mut m, b,
1164                     |m, i| { m.insert(i, 1); },
1165                     |m, i| { m.get(&i); });
1166     }
1167
1168     #[bench]
1169     pub fn find_rand_10_000(b: &mut Bencher) {
1170         let mut m : VecMap<uint> = VecMap::new();
1171         find_rand_n(10_000, &mut m, b,
1172                     |m, i| { m.insert(i, 1); },
1173                     |m, i| { m.get(&i); });
1174     }
1175
1176     // Find seq
1177     #[bench]
1178     pub fn find_seq_100(b: &mut Bencher) {
1179         let mut m : VecMap<uint> = VecMap::new();
1180         find_seq_n(100, &mut m, b,
1181                    |m, i| { m.insert(i, 1); },
1182                    |m, i| { m.get(&i); });
1183     }
1184
1185     #[bench]
1186     pub fn find_seq_10_000(b: &mut Bencher) {
1187         let mut m : VecMap<uint> = VecMap::new();
1188         find_seq_n(10_000, &mut m, b,
1189                    |m, i| { m.insert(i, 1); },
1190                    |m, i| { m.get(&i); });
1191     }
1192 }