]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec_map.rs
Merge pull request #20510 from tshepang/patch-6
[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};
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]
70 impl<V> Default for VecMap<V> {
71     #[stable]
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, 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]
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]
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]
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]
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]
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 by the keys.
190     /// The iterator's element type is `uint`.
191     #[stable]
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 by the keys.
200     /// The iterator's element type is `&'r V`.
201     #[stable]
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 by 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]
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 by 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]
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 by
268     /// the keys, emptying (but not 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     /// // Not possible with .iter()
282     /// let vec: Vec<(uint, &str)> = map.into_iter().collect();
283     ///
284     /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
285     /// ```
286     #[stable]
287     pub fn into_iter(&mut self) -> IntoIter<V> {
288         fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
289             v.map(|v| (i, v))
290         }
291         let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
292
293         let values = replace(&mut self.v, vec!());
294         IntoIter { iter: values.into_iter().enumerate().filter_map(filter) }
295     }
296
297     /// Return the number of elements in the map.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::collections::VecMap;
303     ///
304     /// let mut a = VecMap::new();
305     /// assert_eq!(a.len(), 0);
306     /// a.insert(1, "a");
307     /// assert_eq!(a.len(), 1);
308     /// ```
309     #[stable]
310     pub fn len(&self) -> uint {
311         self.v.iter().filter(|elt| elt.is_some()).count()
312     }
313
314     /// Return true if the map contains no elements.
315     ///
316     /// # Examples
317     ///
318     /// ```
319     /// use std::collections::VecMap;
320     ///
321     /// let mut a = VecMap::new();
322     /// assert!(a.is_empty());
323     /// a.insert(1, "a");
324     /// assert!(!a.is_empty());
325     /// ```
326     #[stable]
327     pub fn is_empty(&self) -> bool {
328         self.v.iter().all(|elt| elt.is_none())
329     }
330
331     /// Clears the map, removing all key-value pairs.
332     ///
333     /// # Examples
334     ///
335     /// ```
336     /// use std::collections::VecMap;
337     ///
338     /// let mut a = VecMap::new();
339     /// a.insert(1, "a");
340     /// a.clear();
341     /// assert!(a.is_empty());
342     /// ```
343     #[stable]
344     pub fn clear(&mut self) { self.v.clear() }
345
346     /// Returns a reference to the value corresponding to the key.
347     ///
348     /// # Examples
349     ///
350     /// ```
351     /// use std::collections::VecMap;
352     ///
353     /// let mut map = VecMap::new();
354     /// map.insert(1, "a");
355     /// assert_eq!(map.get(&1), Some(&"a"));
356     /// assert_eq!(map.get(&2), None);
357     /// ```
358     #[stable]
359     pub fn get(&self, key: &uint) -> Option<&V> {
360         if *key < self.v.len() {
361             match self.v[*key] {
362               Some(ref value) => Some(value),
363               None => None
364             }
365         } else {
366             None
367         }
368     }
369
370     /// Returns true if the map contains a value for the specified key.
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// use std::collections::VecMap;
376     ///
377     /// let mut map = VecMap::new();
378     /// map.insert(1, "a");
379     /// assert_eq!(map.contains_key(&1), true);
380     /// assert_eq!(map.contains_key(&2), false);
381     /// ```
382     #[inline]
383     #[stable]
384     pub fn contains_key(&self, key: &uint) -> bool {
385         self.get(key).is_some()
386     }
387
388     /// Returns a mutable reference to the value corresponding to the key.
389     ///
390     /// # Examples
391     ///
392     /// ```
393     /// use std::collections::VecMap;
394     ///
395     /// let mut map = VecMap::new();
396     /// map.insert(1, "a");
397     /// match map.get_mut(&1) {
398     ///     Some(x) => *x = "b",
399     ///     None => (),
400     /// }
401     /// assert_eq!(map[1], "b");
402     /// ```
403     #[stable]
404     pub fn get_mut(&mut self, key: &uint) -> Option<&mut V> {
405         if *key < self.v.len() {
406             match *(&mut self.v[*key]) {
407               Some(ref mut value) => Some(value),
408               None => None
409             }
410         } else {
411             None
412         }
413     }
414
415     /// Inserts a key-value pair from the map. If the key already had a value
416     /// present in the map, that value is returned. Otherwise, `None` is returned.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// use std::collections::VecMap;
422     ///
423     /// let mut map = VecMap::new();
424     /// assert_eq!(map.insert(37, "a"), None);
425     /// assert_eq!(map.is_empty(), false);
426     ///
427     /// map.insert(37, "b");
428     /// assert_eq!(map.insert(37, "c"), Some("b"));
429     /// assert_eq!(map[37], "c");
430     /// ```
431     #[stable]
432     pub fn insert(&mut self, key: uint, value: V) -> Option<V> {
433         let len = self.v.len();
434         if len <= key {
435             self.v.extend(range(0, key - len + 1).map(|_| None));
436         }
437         replace(&mut self.v[key], Some(value))
438     }
439
440     /// Removes a key from the map, returning the value at the key if the key
441     /// was previously in the map.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// use std::collections::VecMap;
447     ///
448     /// let mut map = VecMap::new();
449     /// map.insert(1, "a");
450     /// assert_eq!(map.remove(&1), Some("a"));
451     /// assert_eq!(map.remove(&1), None);
452     /// ```
453     #[stable]
454     pub fn remove(&mut self, key: &uint) -> Option<V> {
455         if *key >= self.v.len() {
456             return None;
457         }
458         self.v[*key].take()
459     }
460 }
461
462 #[stable]
463 impl<V: PartialEq> PartialEq for VecMap<V> {
464     fn eq(&self, other: &VecMap<V>) -> bool {
465         iter::order::eq(self.iter(), other.iter())
466     }
467 }
468
469 #[stable]
470 impl<V: Eq> Eq for VecMap<V> {}
471
472 #[stable]
473 impl<V: PartialOrd> PartialOrd for VecMap<V> {
474     #[inline]
475     fn partial_cmp(&self, other: &VecMap<V>) -> Option<Ordering> {
476         iter::order::partial_cmp(self.iter(), other.iter())
477     }
478 }
479
480 #[stable]
481 impl<V: Ord> Ord for VecMap<V> {
482     #[inline]
483     fn cmp(&self, other: &VecMap<V>) -> Ordering {
484         iter::order::cmp(self.iter(), other.iter())
485     }
486 }
487
488 #[stable]
489 impl<V: fmt::Show> fmt::Show for VecMap<V> {
490     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491         try!(write!(f, "{{"));
492
493         for (i, (k, v)) in self.iter().enumerate() {
494             if i != 0 { try!(write!(f, ", ")); }
495             try!(write!(f, "{}: {}", k, *v));
496         }
497
498         write!(f, "}}")
499     }
500 }
501
502 #[stable]
503 impl<V> FromIterator<(uint, V)> for VecMap<V> {
504     fn from_iter<Iter: Iterator<Item=(uint, V)>>(iter: Iter) -> VecMap<V> {
505         let mut map = VecMap::new();
506         map.extend(iter);
507         map
508     }
509 }
510
511 #[stable]
512 impl<V> Extend<(uint, V)> for VecMap<V> {
513     fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, mut iter: Iter) {
514         for (k, v) in iter {
515             self.insert(k, v);
516         }
517     }
518 }
519
520 // NOTE(stage0): remove impl after a snapshot
521 #[cfg(stage0)]
522 #[stable]
523 impl<V> Index<uint, V> for VecMap<V> {
524     #[inline]
525     fn index<'a>(&'a self, i: &uint) -> &'a V {
526         self.get(i).expect("key not present")
527     }
528 }
529
530 #[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
531 impl<V> Index<uint> for VecMap<V> {
532     type Output = V;
533
534     #[inline]
535     fn index<'a>(&'a self, i: &uint) -> &'a V {
536         self.get(i).expect("key not present")
537     }
538 }
539
540 // NOTE(stage0): remove impl after a snapshot
541 #[cfg(stage0)]
542 #[stable]
543 impl<V> IndexMut<uint, V> for VecMap<V> {
544     #[inline]
545     fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
546         self.get_mut(i).expect("key not present")
547     }
548 }
549
550 #[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
551 #[stable]
552 impl<V> IndexMut<uint> for VecMap<V> {
553     type Output = V;
554
555     #[inline]
556     fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
557         self.get_mut(i).expect("key not present")
558     }
559 }
560
561 macro_rules! iterator {
562     (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
563         #[stable]
564         impl<'a, V> Iterator for $name<'a, V> {
565             type Item = $elem;
566
567             #[inline]
568             fn next(&mut self) -> Option<$elem> {
569                 while self.front < self.back {
570                     match self.iter.next() {
571                         Some(elem) => {
572                             match elem$(. $getter ())+ {
573                                 Some(x) => {
574                                     let index = self.front;
575                                     self.front += 1;
576                                     return Some((index, x));
577                                 },
578                                 None => {},
579                             }
580                         }
581                         _ => ()
582                     }
583                     self.front += 1;
584                 }
585                 None
586             }
587
588             #[inline]
589             fn size_hint(&self) -> (uint, Option<uint>) {
590                 (0, Some(self.back - self.front))
591             }
592         }
593     }
594 }
595
596 macro_rules! double_ended_iterator {
597     (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
598         #[stable]
599         impl<'a, V> DoubleEndedIterator for $name<'a, V> {
600             #[inline]
601             fn next_back(&mut self) -> Option<$elem> {
602                 while self.front < self.back {
603                     match self.iter.next_back() {
604                         Some(elem) => {
605                             match elem$(. $getter ())+ {
606                                 Some(x) => {
607                                     self.back -= 1;
608                                     return Some((self.back, x));
609                                 },
610                                 None => {},
611                             }
612                         }
613                         _ => ()
614                     }
615                     self.back -= 1;
616                 }
617                 None
618             }
619         }
620     }
621 }
622
623 /// An iterator over the key-value pairs of a map.
624 #[stable]
625 pub struct Iter<'a, V:'a> {
626     front: uint,
627     back: uint,
628     iter: slice::Iter<'a, Option<V>>
629 }
630
631 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
632 impl<'a, V> Clone for Iter<'a, V> {
633     fn clone(&self) -> Iter<'a, V> {
634         Iter {
635             front: self.front,
636             back: self.back,
637             iter: self.iter.clone()
638         }
639     }
640 }
641
642 iterator! { impl Iter -> (uint, &'a V), as_ref }
643 double_ended_iterator! { impl Iter -> (uint, &'a V), as_ref }
644
645 /// An iterator over the key-value pairs of a map, with the
646 /// values being mutable.
647 #[stable]
648 pub struct IterMut<'a, V:'a> {
649     front: uint,
650     back: uint,
651     iter: slice::IterMut<'a, Option<V>>
652 }
653
654 iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
655 double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
656
657 /// An iterator over the keys of a map.
658 #[stable]
659 pub struct Keys<'a, V: 'a> {
660     iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint>
661 }
662
663 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
664 impl<'a, V> Clone for Keys<'a, V> {
665     fn clone(&self) -> Keys<'a, V> {
666         Keys {
667             iter: self.iter.clone()
668         }
669     }
670 }
671
672 /// An iterator over the values of a map.
673 #[stable]
674 pub struct Values<'a, V: 'a> {
675     iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
676 }
677
678 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
679 impl<'a, V> Clone for Values<'a, V> {
680     fn clone(&self) -> Values<'a, V> {
681         Values {
682             iter: self.iter.clone()
683         }
684     }
685 }
686
687 /// A consuming iterator over the key-value pairs of a map.
688 #[stable]
689 pub struct IntoIter<V> {
690     iter: FilterMap<
691     (uint, Option<V>),
692     (uint, V),
693     Enumerate<vec::IntoIter<Option<V>>>,
694     fn((uint, Option<V>)) -> Option<(uint, V)>>
695 }
696
697 #[stable]
698 impl<'a, V> Iterator for Keys<'a, V> {
699     type Item = uint;
700
701     fn next(&mut self) -> Option<uint> { self.iter.next() }
702     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
703 }
704 #[stable]
705 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
706     fn next_back(&mut self) -> Option<uint> { self.iter.next_back() }
707 }
708
709 #[stable]
710 impl<'a, V> Iterator for Values<'a, V> {
711     type Item = &'a V;
712
713     fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
714     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
715 }
716 #[stable]
717 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
718     fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
719 }
720
721 #[stable]
722 impl<V> Iterator for IntoIter<V> {
723     type Item = (uint, V);
724
725     fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
726     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
727 }
728 #[stable]
729 impl<V> DoubleEndedIterator for IntoIter<V> {
730     fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
731 }
732
733 #[cfg(test)]
734 mod test_map {
735     use prelude::*;
736     use core::hash::hash;
737
738     use super::VecMap;
739
740     #[test]
741     fn test_get_mut() {
742         let mut m = VecMap::new();
743         assert!(m.insert(1, 12i).is_none());
744         assert!(m.insert(2, 8).is_none());
745         assert!(m.insert(5, 14).is_none());
746         let new = 100;
747         match m.get_mut(&5) {
748             None => panic!(), Some(x) => *x = new
749         }
750         assert_eq!(m.get(&5), Some(&new));
751     }
752
753     #[test]
754     fn test_len() {
755         let mut map = VecMap::new();
756         assert_eq!(map.len(), 0);
757         assert!(map.is_empty());
758         assert!(map.insert(5, 20i).is_none());
759         assert_eq!(map.len(), 1);
760         assert!(!map.is_empty());
761         assert!(map.insert(11, 12).is_none());
762         assert_eq!(map.len(), 2);
763         assert!(!map.is_empty());
764         assert!(map.insert(14, 22).is_none());
765         assert_eq!(map.len(), 3);
766         assert!(!map.is_empty());
767     }
768
769     #[test]
770     fn test_clear() {
771         let mut map = VecMap::new();
772         assert!(map.insert(5, 20i).is_none());
773         assert!(map.insert(11, 12).is_none());
774         assert!(map.insert(14, 22).is_none());
775         map.clear();
776         assert!(map.is_empty());
777         assert!(map.get(&5).is_none());
778         assert!(map.get(&11).is_none());
779         assert!(map.get(&14).is_none());
780     }
781
782     #[test]
783     fn test_insert() {
784         let mut m = VecMap::new();
785         assert_eq!(m.insert(1, 2i), None);
786         assert_eq!(m.insert(1, 3i), Some(2));
787         assert_eq!(m.insert(1, 4i), Some(3));
788     }
789
790     #[test]
791     fn test_remove() {
792         let mut m = VecMap::new();
793         m.insert(1, 2i);
794         assert_eq!(m.remove(&1), Some(2));
795         assert_eq!(m.remove(&1), None);
796     }
797
798     #[test]
799     fn test_keys() {
800         let mut map = VecMap::new();
801         map.insert(1, 'a');
802         map.insert(2, 'b');
803         map.insert(3, 'c');
804         let keys = map.keys().collect::<Vec<uint>>();
805         assert_eq!(keys.len(), 3);
806         assert!(keys.contains(&1));
807         assert!(keys.contains(&2));
808         assert!(keys.contains(&3));
809     }
810
811     #[test]
812     fn test_values() {
813         let mut map = VecMap::new();
814         map.insert(1, 'a');
815         map.insert(2, 'b');
816         map.insert(3, 'c');
817         let values = map.values().map(|&v| v).collect::<Vec<char>>();
818         assert_eq!(values.len(), 3);
819         assert!(values.contains(&'a'));
820         assert!(values.contains(&'b'));
821         assert!(values.contains(&'c'));
822     }
823
824     #[test]
825     fn test_iterator() {
826         let mut m = VecMap::new();
827
828         assert!(m.insert(0, 1i).is_none());
829         assert!(m.insert(1, 2).is_none());
830         assert!(m.insert(3, 5).is_none());
831         assert!(m.insert(6, 10).is_none());
832         assert!(m.insert(10, 11).is_none());
833
834         let mut it = m.iter();
835         assert_eq!(it.size_hint(), (0, Some(11)));
836         assert_eq!(it.next().unwrap(), (0, &1));
837         assert_eq!(it.size_hint(), (0, Some(10)));
838         assert_eq!(it.next().unwrap(), (1, &2));
839         assert_eq!(it.size_hint(), (0, Some(9)));
840         assert_eq!(it.next().unwrap(), (3, &5));
841         assert_eq!(it.size_hint(), (0, Some(7)));
842         assert_eq!(it.next().unwrap(), (6, &10));
843         assert_eq!(it.size_hint(), (0, Some(4)));
844         assert_eq!(it.next().unwrap(), (10, &11));
845         assert_eq!(it.size_hint(), (0, Some(0)));
846         assert!(it.next().is_none());
847     }
848
849     #[test]
850     fn test_iterator_size_hints() {
851         let mut m = VecMap::new();
852
853         assert!(m.insert(0, 1i).is_none());
854         assert!(m.insert(1, 2).is_none());
855         assert!(m.insert(3, 5).is_none());
856         assert!(m.insert(6, 10).is_none());
857         assert!(m.insert(10, 11).is_none());
858
859         assert_eq!(m.iter().size_hint(), (0, Some(11)));
860         assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
861         assert_eq!(m.iter_mut().size_hint(), (0, Some(11)));
862         assert_eq!(m.iter_mut().rev().size_hint(), (0, Some(11)));
863     }
864
865     #[test]
866     fn test_mut_iterator() {
867         let mut m = VecMap::new();
868
869         assert!(m.insert(0, 1i).is_none());
870         assert!(m.insert(1, 2).is_none());
871         assert!(m.insert(3, 5).is_none());
872         assert!(m.insert(6, 10).is_none());
873         assert!(m.insert(10, 11).is_none());
874
875         for (k, v) in m.iter_mut() {
876             *v += k as int;
877         }
878
879         let mut it = m.iter();
880         assert_eq!(it.next().unwrap(), (0, &1));
881         assert_eq!(it.next().unwrap(), (1, &3));
882         assert_eq!(it.next().unwrap(), (3, &8));
883         assert_eq!(it.next().unwrap(), (6, &16));
884         assert_eq!(it.next().unwrap(), (10, &21));
885         assert!(it.next().is_none());
886     }
887
888     #[test]
889     fn test_rev_iterator() {
890         let mut m = VecMap::new();
891
892         assert!(m.insert(0, 1i).is_none());
893         assert!(m.insert(1, 2).is_none());
894         assert!(m.insert(3, 5).is_none());
895         assert!(m.insert(6, 10).is_none());
896         assert!(m.insert(10, 11).is_none());
897
898         let mut it = m.iter().rev();
899         assert_eq!(it.next().unwrap(), (10, &11));
900         assert_eq!(it.next().unwrap(), (6, &10));
901         assert_eq!(it.next().unwrap(), (3, &5));
902         assert_eq!(it.next().unwrap(), (1, &2));
903         assert_eq!(it.next().unwrap(), (0, &1));
904         assert!(it.next().is_none());
905     }
906
907     #[test]
908     fn test_mut_rev_iterator() {
909         let mut m = VecMap::new();
910
911         assert!(m.insert(0, 1i).is_none());
912         assert!(m.insert(1, 2).is_none());
913         assert!(m.insert(3, 5).is_none());
914         assert!(m.insert(6, 10).is_none());
915         assert!(m.insert(10, 11).is_none());
916
917         for (k, v) in m.iter_mut().rev() {
918             *v += k as int;
919         }
920
921         let mut it = m.iter();
922         assert_eq!(it.next().unwrap(), (0, &1));
923         assert_eq!(it.next().unwrap(), (1, &3));
924         assert_eq!(it.next().unwrap(), (3, &8));
925         assert_eq!(it.next().unwrap(), (6, &16));
926         assert_eq!(it.next().unwrap(), (10, &21));
927         assert!(it.next().is_none());
928     }
929
930     #[test]
931     fn test_move_iter() {
932         let mut m = VecMap::new();
933         m.insert(1, box 2i);
934         let mut called = false;
935         for (k, v) in m.into_iter() {
936             assert!(!called);
937             called = true;
938             assert_eq!(k, 1);
939             assert_eq!(v, box 2i);
940         }
941         assert!(called);
942         m.insert(2, box 1i);
943     }
944
945     #[test]
946     fn test_show() {
947         let mut map = VecMap::new();
948         let empty = VecMap::<int>::new();
949
950         map.insert(1, 2i);
951         map.insert(3, 4i);
952
953         let map_str = map.to_string();
954         assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
955         assert_eq!(format!("{}", empty), "{}");
956     }
957
958     #[test]
959     fn test_clone() {
960         let mut a = VecMap::new();
961
962         a.insert(1, 'x');
963         a.insert(4, 'y');
964         a.insert(6, 'z');
965
966         assert!(a.clone() == a);
967     }
968
969     #[test]
970     fn test_eq() {
971         let mut a = VecMap::new();
972         let mut b = VecMap::new();
973
974         assert!(a == b);
975         assert!(a.insert(0, 5i).is_none());
976         assert!(a != b);
977         assert!(b.insert(0, 4i).is_none());
978         assert!(a != b);
979         assert!(a.insert(5, 19).is_none());
980         assert!(a != b);
981         assert!(!b.insert(0, 5).is_none());
982         assert!(a != b);
983         assert!(b.insert(5, 19).is_none());
984         assert!(a == b);
985
986         a = VecMap::new();
987         b = VecMap::with_capacity(1);
988         assert!(a == b);
989     }
990
991     #[test]
992     fn test_lt() {
993         let mut a = VecMap::new();
994         let mut b = VecMap::new();
995
996         assert!(!(a < b) && !(b < a));
997         assert!(b.insert(2u, 5i).is_none());
998         assert!(a < b);
999         assert!(a.insert(2, 7).is_none());
1000         assert!(!(a < b) && b < a);
1001         assert!(b.insert(1, 0).is_none());
1002         assert!(b < a);
1003         assert!(a.insert(0, 6).is_none());
1004         assert!(a < b);
1005         assert!(a.insert(6, 2).is_none());
1006         assert!(a < b && !(b < a));
1007     }
1008
1009     #[test]
1010     fn test_ord() {
1011         let mut a = VecMap::new();
1012         let mut b = VecMap::new();
1013
1014         assert!(a <= b && a >= b);
1015         assert!(a.insert(1u, 1i).is_none());
1016         assert!(a > b && a >= b);
1017         assert!(b < a && b <= a);
1018         assert!(b.insert(2, 2).is_none());
1019         assert!(b > a && b >= a);
1020         assert!(a < b && a <= b);
1021     }
1022
1023     #[test]
1024     fn test_hash() {
1025         let mut x = VecMap::new();
1026         let mut y = VecMap::new();
1027
1028         assert!(hash(&x) == hash(&y));
1029         x.insert(1, 'a');
1030         x.insert(2, 'b');
1031         x.insert(3, 'c');
1032
1033         y.insert(3, 'c');
1034         y.insert(2, 'b');
1035         y.insert(1, 'a');
1036
1037         assert!(hash(&x) == hash(&y));
1038
1039         x.insert(1000, 'd');
1040         x.remove(&1000);
1041
1042         assert!(hash(&x) == hash(&y));
1043     }
1044
1045     #[test]
1046     fn test_from_iter() {
1047         let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
1048
1049         let map: VecMap<char> = xs.iter().map(|&x| x).collect();
1050
1051         for &(k, v) in xs.iter() {
1052             assert_eq!(map.get(&k), Some(&v));
1053         }
1054     }
1055
1056     #[test]
1057     fn test_index() {
1058         let mut map: VecMap<int> = VecMap::new();
1059
1060         map.insert(1, 2);
1061         map.insert(2, 1);
1062         map.insert(3, 4);
1063
1064         assert_eq!(map[3], 4);
1065     }
1066
1067     #[test]
1068     #[should_fail]
1069     fn test_index_nonexistent() {
1070         let mut map: VecMap<int> = VecMap::new();
1071
1072         map.insert(1, 2);
1073         map.insert(2, 1);
1074         map.insert(3, 4);
1075
1076         map[4];
1077     }
1078 }
1079
1080 #[cfg(test)]
1081 mod bench {
1082     use test::Bencher;
1083     use super::VecMap;
1084     use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1085
1086     #[bench]
1087     pub fn insert_rand_100(b: &mut Bencher) {
1088         let mut m : VecMap<uint> = VecMap::new();
1089         insert_rand_n(100, &mut m, b,
1090                       |m, i| { m.insert(i, 1); },
1091                       |m, i| { m.remove(&i); });
1092     }
1093
1094     #[bench]
1095     pub fn insert_rand_10_000(b: &mut Bencher) {
1096         let mut m : VecMap<uint> = VecMap::new();
1097         insert_rand_n(10_000, &mut m, b,
1098                       |m, i| { m.insert(i, 1); },
1099                       |m, i| { m.remove(&i); });
1100     }
1101
1102     // Insert seq
1103     #[bench]
1104     pub fn insert_seq_100(b: &mut Bencher) {
1105         let mut m : VecMap<uint> = VecMap::new();
1106         insert_seq_n(100, &mut m, b,
1107                      |m, i| { m.insert(i, 1); },
1108                      |m, i| { m.remove(&i); });
1109     }
1110
1111     #[bench]
1112     pub fn insert_seq_10_000(b: &mut Bencher) {
1113         let mut m : VecMap<uint> = VecMap::new();
1114         insert_seq_n(10_000, &mut m, b,
1115                      |m, i| { m.insert(i, 1); },
1116                      |m, i| { m.remove(&i); });
1117     }
1118
1119     // Find rand
1120     #[bench]
1121     pub fn find_rand_100(b: &mut Bencher) {
1122         let mut m : VecMap<uint> = VecMap::new();
1123         find_rand_n(100, &mut m, b,
1124                     |m, i| { m.insert(i, 1); },
1125                     |m, i| { m.get(&i); });
1126     }
1127
1128     #[bench]
1129     pub fn find_rand_10_000(b: &mut Bencher) {
1130         let mut m : VecMap<uint> = VecMap::new();
1131         find_rand_n(10_000, &mut m, b,
1132                     |m, i| { m.insert(i, 1); },
1133                     |m, i| { m.get(&i); });
1134     }
1135
1136     // Find seq
1137     #[bench]
1138     pub fn find_seq_100(b: &mut Bencher) {
1139         let mut m : VecMap<uint> = VecMap::new();
1140         find_seq_n(100, &mut m, b,
1141                    |m, i| { m.insert(i, 1); },
1142                    |m, i| { m.get(&i); });
1143     }
1144
1145     #[bench]
1146     pub fn find_seq_10_000(b: &mut Bencher) {
1147         let mut m : VecMap<uint> = VecMap::new();
1148         find_seq_n(10_000, &mut m, b,
1149                    |m, i| { m.insert(i, 1); },
1150                    |m, i| { m.get(&i); });
1151     }
1152 }