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