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.
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.
11 #![deny(missing_docs)]
13 //! A simple map based on a vector for small integer keys. Space requirements
14 //! are O(highest integer key).
16 // optional serde support
17 #![cfg_attr(feature = "eders", feature(const_fn, custom_derive, plugin))]
18 #![cfg_attr(feature = "eders", plugin(serde_macros))]
19 #[cfg(feature = "eders")]
24 use std
::cmp
::{Ordering, max}
;
26 use std
::hash
::{Hash, Hasher}
;
27 use std
::iter
::{Enumerate, FilterMap, FromIterator}
;
28 use std
::mem
::{replace, swap}
;
29 use std
::ops
::{Index, IndexMut}
;
33 /// A map optimized for small integer keys.
38 /// use vec_map::VecMap;
40 /// let mut months = VecMap::new();
41 /// months.insert(1, "Jan");
42 /// months.insert(2, "Feb");
43 /// months.insert(3, "Mar");
45 /// if !months.contains_key(12) {
46 /// println!("The end is near!");
49 /// assert_eq!(months.get(1), Some(&"Jan"));
51 /// if let Some(value) = months.get_mut(3) {
55 /// assert_eq!(months.get(3), Some(&"Venus"));
57 /// // Print out all months
58 /// for (key, value) in &months {
59 /// println!("month {} is {}", key, value);
63 /// assert!(months.is_empty());
66 #[cfg_attr(feature = "eders", derive(Serialize, Deserialize))]
67 pub struct VecMap
<V
> {
71 /// A view into a single entry in a map, which may either be vacant or occupied.
72 pub enum Entry
<'a
, V
: 'a
> {
74 Vacant(VacantEntry
<'a
, V
>),
77 Occupied(OccupiedEntry
<'a
, V
>),
81 pub struct VacantEntry
<'a
, V
: 'a
> {
82 map
: &'a
mut VecMap
<V
>,
86 /// An occupied Entry.
87 pub struct OccupiedEntry
<'a
, V
: 'a
> {
88 map
: &'a
mut VecMap
<V
>,
92 impl<V
> Default
for VecMap
<V
> {
94 fn default() -> Self { Self::new() }
97 impl<V
: Hash
> Hash
for VecMap
<V
> {
98 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
99 // In order to not traverse the `VecMap` twice, count the elements
101 let mut count
: usize = 0;
111 /// Creates an empty `VecMap`.
116 /// use vec_map::VecMap;
117 /// let mut map: VecMap<&str> = VecMap::new();
119 pub fn new() -> Self { VecMap { v: vec![] }
}
121 /// Creates an empty `VecMap` with space for at least `capacity`
122 /// elements before resizing.
127 /// use vec_map::VecMap;
128 /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
130 pub fn with_capacity(capacity
: usize) -> Self {
131 VecMap { v: Vec::with_capacity(capacity) }
134 /// Returns the number of elements the `VecMap` can hold without
140 /// use vec_map::VecMap;
141 /// let map: VecMap<String> = VecMap::with_capacity(10);
142 /// assert!(map.capacity() >= 10);
145 pub fn capacity(&self) -> usize {
149 /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
150 /// In the case of `VecMap` this means reallocations will not occur as long
151 /// as all inserted keys are less than `len`.
153 /// The collection may reserve more space to avoid frequent reallocations.
158 /// use vec_map::VecMap;
159 /// let mut map: VecMap<&str> = VecMap::new();
160 /// map.reserve_len(10);
161 /// assert!(map.capacity() >= 10);
163 pub fn reserve_len(&mut self, len
: usize) {
164 let cur_len
= self.v
.len();
166 self.v
.reserve(len
- cur_len
);
170 /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
171 /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
172 /// keys are less than `len`.
174 /// Note that the allocator may give the collection more space than it requests.
175 /// Therefore capacity cannot be relied upon to be precisely minimal. Prefer
176 /// `reserve_len` if future insertions are expected.
181 /// use vec_map::VecMap;
182 /// let mut map: VecMap<&str> = VecMap::new();
183 /// map.reserve_len_exact(10);
184 /// assert!(map.capacity() >= 10);
186 pub fn reserve_len_exact(&mut self, len
: usize) {
187 let cur_len
= self.v
.len();
189 self.v
.reserve_exact(len
- cur_len
);
193 /// Returns an iterator visiting all keys in ascending order of the keys.
194 /// The iterator's element type is `usize`.
195 pub fn keys(&self) -> Keys
<V
> {
196 Keys { iter: self.iter() }
199 /// Returns an iterator visiting all values in ascending order of the keys.
200 /// The iterator's element type is `&'r V`.
201 pub fn values(&self) -> Values
<V
> {
202 Values { iter: self.iter() }
205 /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
206 /// The iterator's element type is `(usize, &'r V)`.
211 /// use vec_map::VecMap;
213 /// let mut map = VecMap::new();
214 /// map.insert(1, "a");
215 /// map.insert(3, "c");
216 /// map.insert(2, "b");
218 /// // Print `1: a` then `2: b` then `3: c`
219 /// for (key, value) in map.iter() {
220 /// println!("{}: {}", key, value);
223 pub fn iter(&self) -> Iter
<V
> {
231 /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
232 /// with mutable references to the values.
233 /// The iterator's element type is `(usize, &'r mut V)`.
238 /// use vec_map::VecMap;
240 /// let mut map = VecMap::new();
241 /// map.insert(1, "a");
242 /// map.insert(2, "b");
243 /// map.insert(3, "c");
245 /// for (key, value) in map.iter_mut() {
249 /// for (key, value) in &map {
250 /// assert_eq!(value, &"x");
253 pub fn iter_mut(&mut self) -> IterMut
<V
> {
257 iter
: self.v
.iter_mut()
261 /// Moves all elements from `other` into the map while overwriting existing keys.
266 /// use vec_map::VecMap;
268 /// let mut a = VecMap::new();
269 /// a.insert(1, "a");
270 /// a.insert(2, "b");
272 /// let mut b = VecMap::new();
273 /// b.insert(3, "c");
274 /// b.insert(4, "d");
276 /// a.append(&mut b);
278 /// assert_eq!(a.len(), 4);
279 /// assert_eq!(b.len(), 0);
280 /// assert_eq!(a[1], "a");
281 /// assert_eq!(a[2], "b");
282 /// assert_eq!(a[3], "c");
283 /// assert_eq!(a[4], "d");
285 pub fn append(&mut self, other
: &mut Self) {
286 self.extend(other
.drain());
289 /// Splits the collection into two at the given key.
291 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
292 /// and the returned `Self` contains elements `[at, max_key)`.
294 /// Note that the capacity of `self` does not change.
299 /// use vec_map::VecMap;
301 /// let mut a = VecMap::new();
302 /// a.insert(1, "a");
303 /// a.insert(2, "b");
304 /// a.insert(3, "c");
305 /// a.insert(4, "d");
307 /// let b = a.split_off(3);
309 /// assert_eq!(a[1], "a");
310 /// assert_eq!(a[2], "b");
312 /// assert_eq!(b[3], "c");
313 /// assert_eq!(b[4], "d");
315 pub fn split_off(&mut self, at
: usize) -> Self {
316 let mut other
= VecMap
::new();
319 // Move all elements to other
320 swap(self, &mut other
);
322 } else if at
>= self.v
.len() {
323 // No elements to copy
327 // Look up the index of the first non-None item
328 let first_index
= self.v
.iter().position(|el
| el
.is_some());
329 let start_index
= match first_index
{
330 Some(index
) => max(at
, index
),
332 // self has no elements
337 // Fill the new VecMap with `None`s until `start_index`
338 other
.v
.extend((0..start_index
).map(|_
| None
));
340 // Move elements beginning with `start_index` from `self` into `other`
341 other
.v
.extend(self.v
[start_index
..].iter_mut().map(|el
| el
.take()));
346 /// Returns an iterator visiting all key-value pairs in ascending order of
347 /// the keys, emptying (but not consuming) the original `VecMap`.
348 /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.
353 /// use vec_map::VecMap;
355 /// let mut map = VecMap::new();
356 /// map.insert(1, "a");
357 /// map.insert(3, "c");
358 /// map.insert(2, "b");
360 /// let vec: Vec<(usize, &str)> = map.drain().collect();
362 /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
364 pub fn drain(&mut self) -> Drain
<V
> {
365 fn filter
<A
>((i
, v
): (usize, Option
<A
>)) -> Option
<(usize, A
)> {
368 let filter
: fn((usize, Option
<V
>)) -> Option
<(usize, V
)> = filter
; // coerce to fn ptr
370 Drain { iter: self.v.drain(..).enumerate().filter_map(filter) }
373 /// Returns the number of elements in the map.
378 /// use vec_map::VecMap;
380 /// let mut a = VecMap::new();
381 /// assert_eq!(a.len(), 0);
382 /// a.insert(1, "a");
383 /// assert_eq!(a.len(), 1);
385 pub fn len(&self) -> usize {
386 self.v
.iter().filter(|elt
| elt
.is_some()).count()
389 /// Returns true if the map contains no elements.
394 /// use vec_map::VecMap;
396 /// let mut a = VecMap::new();
397 /// assert!(a.is_empty());
398 /// a.insert(1, "a");
399 /// assert!(!a.is_empty());
401 pub fn is_empty(&self) -> bool
{
402 self.v
.iter().all(|elt
| elt
.is_none())
405 /// Clears the map, removing all key-value pairs.
410 /// use vec_map::VecMap;
412 /// let mut a = VecMap::new();
413 /// a.insert(1, "a");
415 /// assert!(a.is_empty());
417 pub fn clear(&mut self) { self.v.clear() }
419 /// Returns a reference to the value corresponding to the key.
424 /// use vec_map::VecMap;
426 /// let mut map = VecMap::new();
427 /// map.insert(1, "a");
428 /// assert_eq!(map.get(1), Some(&"a"));
429 /// assert_eq!(map.get(2), None);
431 pub fn get(&self, key
: usize) -> Option
<&V
> {
432 if key
< self.v
.len() {
434 Some(ref value
) => Some(value
),
442 /// Returns true if the map contains a value for the specified key.
447 /// use vec_map::VecMap;
449 /// let mut map = VecMap::new();
450 /// map.insert(1, "a");
451 /// assert_eq!(map.contains_key(1), true);
452 /// assert_eq!(map.contains_key(2), false);
455 pub fn contains_key(&self, key
: usize) -> bool
{
456 self.get(key
).is_some()
459 /// Returns a mutable reference to the value corresponding to the key.
464 /// use vec_map::VecMap;
466 /// let mut map = VecMap::new();
467 /// map.insert(1, "a");
468 /// if let Some(x) = map.get_mut(1) {
471 /// assert_eq!(map[1], "b");
473 pub fn get_mut(&mut self, key
: usize) -> Option
<&mut V
> {
474 if key
< self.v
.len() {
475 match *(&mut self.v
[key
]) {
476 Some(ref mut value
) => Some(value
),
484 /// Inserts a key-value pair into the map. If the key already had a value
485 /// present in the map, that value is returned. Otherwise, `None` is returned.
490 /// use vec_map::VecMap;
492 /// let mut map = VecMap::new();
493 /// assert_eq!(map.insert(37, "a"), None);
494 /// assert_eq!(map.is_empty(), false);
496 /// map.insert(37, "b");
497 /// assert_eq!(map.insert(37, "c"), Some("b"));
498 /// assert_eq!(map[37], "c");
500 pub fn insert(&mut self, key
: usize, value
: V
) -> Option
<V
> {
501 let len
= self.v
.len();
503 self.v
.extend((0..key
- len
+ 1).map(|_
| None
));
505 replace(&mut self.v
[key
], Some(value
))
508 /// Removes a key from the map, returning the value at the key if the key
509 /// was previously in the map.
514 /// use vec_map::VecMap;
516 /// let mut map = VecMap::new();
517 /// map.insert(1, "a");
518 /// assert_eq!(map.remove(1), Some("a"));
519 /// assert_eq!(map.remove(1), None);
521 pub fn remove(&mut self, key
: usize) -> Option
<V
> {
522 if key
>= self.v
.len() {
525 let result
= &mut self.v
[key
];
529 /// Gets the given key's corresponding entry in the map for in-place manipulation.
534 /// use vec_map::VecMap;
536 /// let mut count: VecMap<u32> = VecMap::new();
538 /// // count the number of occurrences of numbers in the vec
539 /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4] {
540 /// *count.entry(x).or_insert(0) += 1;
543 /// assert_eq!(count[1], 3);
545 pub fn entry(&mut self, key
: usize) -> Entry
<V
> {
546 // FIXME(Gankro): this is basically the dumbest implementation of
547 // entry possible, because weird non-lexical borrows issues make it
548 // completely insane to do any other way. That said, Entry is a border-line
549 // useless construct on VecMap, so it's hardly a big loss.
550 if self.contains_key(key
) {
551 Occupied(OccupiedEntry
{
564 impl<'a
, V
> Entry
<'a
, V
> {
565 /// Ensures a value is in the entry by inserting the default if empty, and
566 /// returns a mutable reference to the value in the entry.
567 pub fn or_insert(self, default: V
) -> &'a
mut V
{
569 Occupied(entry
) => entry
.into_mut(),
570 Vacant(entry
) => entry
.insert(default),
574 /// Ensures a value is in the entry by inserting the result of the default
575 /// function if empty, and returns a mutable reference to the value in the
577 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
579 Occupied(entry
) => entry
.into_mut(),
580 Vacant(entry
) => entry
.insert(default()),
585 impl<'a
, V
> VacantEntry
<'a
, V
> {
586 /// Sets the value of the entry with the VacantEntry's key,
587 /// and returns a mutable reference to it.
588 pub fn insert(self, value
: V
) -> &'a
mut V
{
589 let index
= self.index
;
590 self.map
.insert(index
, value
);
595 impl<'a
, V
> OccupiedEntry
<'a
, V
> {
596 /// Gets a reference to the value in the entry.
597 pub fn get(&self) -> &V
{
598 let index
= self.index
;
602 /// Gets a mutable reference to the value in the entry.
603 pub fn get_mut(&mut self) -> &mut V
{
604 let index
= self.index
;
608 /// Converts the entry into a mutable reference to its value.
609 pub fn into_mut(self) -> &'a
mut V
{
610 let index
= self.index
;
614 /// Sets the value of the entry with the OccupiedEntry's key,
615 /// and returns the entry's old value.
616 pub fn insert(&mut self, value
: V
) -> V
{
617 let index
= self.index
;
618 self.map
.insert(index
, value
).unwrap()
621 /// Takes the value of the entry out of the map, and returns it.
622 pub fn remove(self) -> V
{
623 let index
= self.index
;
624 self.map
.remove(index
).unwrap()
628 impl<V
: PartialEq
> PartialEq
for VecMap
<V
> {
629 fn eq(&self, other
: &Self) -> bool
{
630 self.iter().eq(other
.iter())
634 impl<V
: Eq
> Eq
for VecMap
<V
> {}
636 impl<V
: PartialOrd
> PartialOrd
for VecMap
<V
> {
638 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
639 self.iter().partial_cmp(other
.iter())
643 impl<V
: Ord
> Ord
for VecMap
<V
> {
645 fn cmp(&self, other
: &Self) -> Ordering
{
646 self.iter().cmp(other
.iter())
650 impl<V
: fmt
::Debug
> fmt
::Debug
for VecMap
<V
> {
651 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
652 f
.debug_map().entries(self).finish()
656 impl<V
> FromIterator
<(usize, V
)> for VecMap
<V
> {
657 fn from_iter
<I
: IntoIterator
<Item
= (usize, V
)>>(iter
: I
) -> Self {
658 let mut map
= Self::new();
664 impl<T
> IntoIterator
for VecMap
<T
> {
665 type Item
= (usize, T
);
666 type IntoIter
= IntoIter
<T
>;
668 /// Returns an iterator visiting all key-value pairs in ascending order of
669 /// the keys, consuming the original `VecMap`.
670 /// The iterator's element type is `(usize, &'r V)`.
675 /// use vec_map::VecMap;
677 /// let mut map = VecMap::new();
678 /// map.insert(1, "a");
679 /// map.insert(3, "c");
680 /// map.insert(2, "b");
682 /// let vec: Vec<(usize, &str)> = map.into_iter().collect();
684 /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
686 fn into_iter(self) -> IntoIter
<T
> {
687 IntoIter { iter: self.v.into_iter().enumerate() }
691 impl<'a
, T
> IntoIterator
for &'a VecMap
<T
> {
692 type Item
= (usize, &'a T
);
693 type IntoIter
= Iter
<'a
, T
>;
695 fn into_iter(self) -> Iter
<'a
, T
> {
700 impl<'a
, T
> IntoIterator
for &'a
mut VecMap
<T
> {
701 type Item
= (usize, &'a
mut T
);
702 type IntoIter
= IterMut
<'a
, T
>;
704 fn into_iter(mut self) -> IterMut
<'a
, T
> {
709 impl<V
> Extend
<(usize, V
)> for VecMap
<V
> {
710 fn extend
<I
: IntoIterator
<Item
= (usize, V
)>>(&mut self, iter
: I
) {
717 impl<'a
, V
: Copy
> Extend
<(usize, &'a V
)> for VecMap
<V
> {
718 fn extend
<I
: IntoIterator
<Item
= (usize, &'a V
)>>(&mut self, iter
: I
) {
719 self.extend(iter
.into_iter().map(|(key
, &value
)| (key
, value
)));
723 impl<V
> Index
<usize> for VecMap
<V
> {
727 fn index(&self, i
: usize) -> &V
{
728 self.get(i
).expect("key not present")
732 impl<'a
, V
> Index
<&'a
usize> for VecMap
<V
> {
736 fn index(&self, i
: &usize) -> &V
{
737 self.get(*i
).expect("key not present")
741 impl<V
> IndexMut
<usize> for VecMap
<V
> {
743 fn index_mut(&mut self, i
: usize) -> &mut V
{
744 self.get_mut(i
).expect("key not present")
748 impl<'a
, V
> IndexMut
<&'a
usize> for VecMap
<V
> {
750 fn index_mut(&mut self, i
: &usize) -> &mut V
{
751 self.get_mut(*i
).expect("key not present")
755 macro_rules
! iterator
{
756 (impl $name
:ident
-> $elem
:ty
, $
($getter
:ident
),+) => {
757 impl<'a
, V
> Iterator
for $name
<'a
, V
> {
761 fn next(&mut self) -> Option
<$elem
> {
762 while self.front
< self.back
{
763 match self.iter
.next() {
765 match elem$
(. $
getter ())+ {
767 let index
= self.front
;
769 return Some((index
, x
));
782 fn size_hint(&self) -> (usize, Option
<usize>) {
783 (0, Some(self.back
- self.front
))
789 macro_rules
! double_ended_iterator
{
790 (impl $name
:ident
-> $elem
:ty
, $
($getter
:ident
),+) => {
791 impl<'a
, V
> DoubleEndedIterator
for $name
<'a
, V
> {
793 fn next_back(&mut self) -> Option
<$elem
> {
794 while self.front
< self.back
{
795 match self.iter
.next_back() {
797 match elem$
(. $
getter ())+ {
800 return Some((self.back
, x
));
815 /// An iterator over the key-value pairs of a map.
816 pub struct Iter
<'a
, V
: 'a
> {
819 iter
: slice
::Iter
<'a
, Option
<V
>>
822 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
823 impl<'a
, V
> Clone
for Iter
<'a
, V
> {
824 fn clone(&self) -> Iter
<'a
, V
> {
828 iter
: self.iter
.clone()
833 iterator
! { impl Iter -> (usize, &'a V), as_ref }
834 double_ended_iterator
! { impl Iter -> (usize, &'a V), as_ref }
836 /// An iterator over the key-value pairs of a map, with the
837 /// values being mutable.
838 pub struct IterMut
<'a
, V
: 'a
> {
841 iter
: slice
::IterMut
<'a
, Option
<V
>>
844 iterator
! { impl IterMut -> (usize, &'a mut V), as_mut }
845 double_ended_iterator
! { impl IterMut -> (usize, &'a mut V), as_mut }
847 /// An iterator over the keys of a map.
848 pub struct Keys
<'a
, V
: 'a
> {
852 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
853 impl<'a
, V
> Clone
for Keys
<'a
, V
> {
854 fn clone(&self) -> Keys
<'a
, V
> {
856 iter
: self.iter
.clone()
861 /// An iterator over the values of a map.
862 pub struct Values
<'a
, V
: 'a
> {
866 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
867 impl<'a
, V
> Clone
for Values
<'a
, V
> {
868 fn clone(&self) -> Values
<'a
, V
> {
870 iter
: self.iter
.clone()
875 /// A consuming iterator over the key-value pairs of a map.
876 pub struct IntoIter
<V
> {
877 iter
: Enumerate
<vec
::IntoIter
<Option
<V
>>>,
880 /// A draining iterator over the key-value pairs of a map.
881 pub struct Drain
<'a
, V
: 'a
> {
883 Enumerate
<vec
::Drain
<'a
, Option
<V
>>>,
884 fn((usize, Option
<V
>)) -> Option
<(usize, V
)>>
887 impl<'a
, V
> Iterator
for Drain
<'a
, V
> {
888 type Item
= (usize, V
);
890 fn next(&mut self) -> Option
<(usize, V
)> { self.iter.next() }
891 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
894 impl<'a
, V
> DoubleEndedIterator
for Drain
<'a
, V
> {
895 fn next_back(&mut self) -> Option
<(usize, V
)> { self.iter.next_back() }
898 impl<'a
, V
> Iterator
for Keys
<'a
, V
> {
901 fn next(&mut self) -> Option
<usize> { self.iter.next().map(|e| e.0) }
902 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
905 impl<'a
, V
> DoubleEndedIterator
for Keys
<'a
, V
> {
906 fn next_back(&mut self) -> Option
<usize> { self.iter.next_back().map(|e| e.0) }
909 impl<'a
, V
> Iterator
for Values
<'a
, V
> {
912 fn next(&mut self) -> Option
<(&'a V
)> { self.iter.next().map(|e| e.1) }
913 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
916 impl<'a
, V
> DoubleEndedIterator
for Values
<'a
, V
> {
917 fn next_back(&mut self) -> Option
<(&'a V
)> { self.iter.next_back().map(|e| e.1) }
920 impl<V
> Iterator
for IntoIter
<V
> {
921 type Item
= (usize, V
);
923 fn next(&mut self) -> Option
<(usize, V
)> {
925 match self.iter
.next() {
927 Some((i
, Some(value
))) => return Some((i
, value
)),
933 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
936 impl<V
> DoubleEndedIterator
for IntoIter
<V
> {
937 fn next_back(&mut self) -> Option
<(usize, V
)> {
939 match self.iter
.next_back() {
941 Some((i
, Some(value
))) => return Some((i
, value
)),
949 fn assert_properties() {
950 fn vec_map_covariant
<'a
, T
>(map
: VecMap
<&'
static T
>) -> VecMap
<&'a T
> { map }
952 fn into_iter_covariant
<'a
, T
>(iter
: IntoIter
<&'
static T
>) -> IntoIter
<&'a T
> { iter }
954 fn iter_covariant
<'i
, 'a
, T
>(iter
: Iter
<'i
, &'
static T
>) -> Iter
<'i
, &'a T
> { iter }
956 fn keys_covariant
<'i
, 'a
, T
>(iter
: Keys
<'i
, &'
static T
>) -> Keys
<'i
, &'a T
> { iter }
958 fn values_covariant
<'i
, 'a
, T
>(iter
: Values
<'i
, &'
static T
>) -> Values
<'i
, &'a T
> { iter }
964 use super::Entry
::{Occupied, Vacant}
;
965 use std
::hash
::{Hash, Hasher, SipHasher}
;
969 let mut m
= VecMap
::new();
970 assert
!(m
.insert(1, 12).is_none());
971 assert
!(m
.insert(2, 8).is_none());
972 assert
!(m
.insert(5, 14).is_none());
975 None
=> panic
!(), Some(x
) => *x
= new
977 assert_eq
!(m
.get(5), Some(&new
));
982 let mut map
= VecMap
::new();
983 assert_eq
!(map
.len(), 0);
984 assert
!(map
.is_empty());
985 assert
!(map
.insert(5, 20).is_none());
986 assert_eq
!(map
.len(), 1);
987 assert
!(!map
.is_empty());
988 assert
!(map
.insert(11, 12).is_none());
989 assert_eq
!(map
.len(), 2);
990 assert
!(!map
.is_empty());
991 assert
!(map
.insert(14, 22).is_none());
992 assert_eq
!(map
.len(), 3);
993 assert
!(!map
.is_empty());
998 let mut map
= VecMap
::new();
999 assert
!(map
.insert(5, 20).is_none());
1000 assert
!(map
.insert(11, 12).is_none());
1001 assert
!(map
.insert(14, 22).is_none());
1003 assert
!(map
.is_empty());
1004 assert
!(map
.get(5).is_none());
1005 assert
!(map
.get(11).is_none());
1006 assert
!(map
.get(14).is_none());
1011 let mut m
= VecMap
::new();
1012 assert_eq
!(m
.insert(1, 2), None
);
1013 assert_eq
!(m
.insert(1, 3), Some(2));
1014 assert_eq
!(m
.insert(1, 4), Some(3));
1019 let mut m
= VecMap
::new();
1021 assert_eq
!(m
.remove(1), Some(2));
1022 assert_eq
!(m
.remove(1), None
);
1027 let mut map
= VecMap
::new();
1031 let keys
: Vec
<_
> = map
.keys().collect();
1032 assert_eq
!(keys
.len(), 3);
1033 assert
!(keys
.contains(&1));
1034 assert
!(keys
.contains(&2));
1035 assert
!(keys
.contains(&3));
1040 let mut map
= VecMap
::new();
1044 let values
: Vec
<_
> = map
.values().cloned().collect();
1045 assert_eq
!(values
.len(), 3);
1046 assert
!(values
.contains(&'a'
));
1047 assert
!(values
.contains(&'b'
));
1048 assert
!(values
.contains(&'c'
));
1052 fn test_iterator() {
1053 let mut m
= VecMap
::new();
1055 assert
!(m
.insert(0, 1).is_none());
1056 assert
!(m
.insert(1, 2).is_none());
1057 assert
!(m
.insert(3, 5).is_none());
1058 assert
!(m
.insert(6, 10).is_none());
1059 assert
!(m
.insert(10, 11).is_none());
1061 let mut it
= m
.iter();
1062 assert_eq
!(it
.size_hint(), (0, Some(11)));
1063 assert_eq
!(it
.next().unwrap(), (0, &1));
1064 assert_eq
!(it
.size_hint(), (0, Some(10)));
1065 assert_eq
!(it
.next().unwrap(), (1, &2));
1066 assert_eq
!(it
.size_hint(), (0, Some(9)));
1067 assert_eq
!(it
.next().unwrap(), (3, &5));
1068 assert_eq
!(it
.size_hint(), (0, Some(7)));
1069 assert_eq
!(it
.next().unwrap(), (6, &10));
1070 assert_eq
!(it
.size_hint(), (0, Some(4)));
1071 assert_eq
!(it
.next().unwrap(), (10, &11));
1072 assert_eq
!(it
.size_hint(), (0, Some(0)));
1073 assert
!(it
.next().is_none());
1077 fn test_iterator_size_hints() {
1078 let mut m
= VecMap
::new();
1080 assert
!(m
.insert(0, 1).is_none());
1081 assert
!(m
.insert(1, 2).is_none());
1082 assert
!(m
.insert(3, 5).is_none());
1083 assert
!(m
.insert(6, 10).is_none());
1084 assert
!(m
.insert(10, 11).is_none());
1086 assert_eq
!(m
.iter().size_hint(), (0, Some(11)));
1087 assert_eq
!(m
.iter().rev().size_hint(), (0, Some(11)));
1088 assert_eq
!(m
.iter_mut().size_hint(), (0, Some(11)));
1089 assert_eq
!(m
.iter_mut().rev().size_hint(), (0, Some(11)));
1093 fn test_mut_iterator() {
1094 let mut m
= VecMap
::new();
1096 assert
!(m
.insert(0, 1).is_none());
1097 assert
!(m
.insert(1, 2).is_none());
1098 assert
!(m
.insert(3, 5).is_none());
1099 assert
!(m
.insert(6, 10).is_none());
1100 assert
!(m
.insert(10, 11).is_none());
1102 for (k
, v
) in &mut m
{
1106 let mut it
= m
.iter();
1107 assert_eq
!(it
.next().unwrap(), (0, &1));
1108 assert_eq
!(it
.next().unwrap(), (1, &3));
1109 assert_eq
!(it
.next().unwrap(), (3, &8));
1110 assert_eq
!(it
.next().unwrap(), (6, &16));
1111 assert_eq
!(it
.next().unwrap(), (10, &21));
1112 assert
!(it
.next().is_none());
1116 fn test_rev_iterator() {
1117 let mut m
= VecMap
::new();
1119 assert
!(m
.insert(0, 1).is_none());
1120 assert
!(m
.insert(1, 2).is_none());
1121 assert
!(m
.insert(3, 5).is_none());
1122 assert
!(m
.insert(6, 10).is_none());
1123 assert
!(m
.insert(10, 11).is_none());
1125 let mut it
= m
.iter().rev();
1126 assert_eq
!(it
.next().unwrap(), (10, &11));
1127 assert_eq
!(it
.next().unwrap(), (6, &10));
1128 assert_eq
!(it
.next().unwrap(), (3, &5));
1129 assert_eq
!(it
.next().unwrap(), (1, &2));
1130 assert_eq
!(it
.next().unwrap(), (0, &1));
1131 assert
!(it
.next().is_none());
1135 fn test_mut_rev_iterator() {
1136 let mut m
= VecMap
::new();
1138 assert
!(m
.insert(0, 1).is_none());
1139 assert
!(m
.insert(1, 2).is_none());
1140 assert
!(m
.insert(3, 5).is_none());
1141 assert
!(m
.insert(6, 10).is_none());
1142 assert
!(m
.insert(10, 11).is_none());
1144 for (k
, v
) in m
.iter_mut().rev() {
1148 let mut it
= m
.iter();
1149 assert_eq
!(it
.next().unwrap(), (0, &1));
1150 assert_eq
!(it
.next().unwrap(), (1, &3));
1151 assert_eq
!(it
.next().unwrap(), (3, &8));
1152 assert_eq
!(it
.next().unwrap(), (6, &16));
1153 assert_eq
!(it
.next().unwrap(), (10, &21));
1154 assert
!(it
.next().is_none());
1158 fn test_move_iter() {
1159 let mut m
: VecMap
<Box
<_
>> = VecMap
::new();
1160 m
.insert(1, Box
::new(2));
1161 let mut called
= false;
1166 assert_eq
!(v
, Box
::new(2));
1172 fn test_drain_iterator() {
1173 let mut map
= VecMap
::new();
1178 let vec
: Vec
<_
> = map
.drain().collect();
1180 assert_eq
!(vec
, [(1, "a"), (2, "b"), (3, "c")]);
1181 assert_eq
!(map
.len(), 0);
1186 let mut a
= VecMap
::new();
1191 let mut b
= VecMap
::new();
1192 b
.insert(3, "d"); // Overwrite element from a
1198 assert_eq
!(a
.len(), 5);
1199 assert_eq
!(b
.len(), 0);
1200 // Capacity shouldn't change for possible reuse
1201 assert
!(b
.capacity() >= 4);
1203 assert_eq
!(a
[1], "a");
1204 assert_eq
!(a
[2], "b");
1205 assert_eq
!(a
[3], "d");
1206 assert_eq
!(a
[4], "e");
1207 assert_eq
!(a
[5], "f");
1211 fn test_split_off() {
1212 // Split within the key range
1213 let mut a
= VecMap
::new();
1219 let b
= a
.split_off(3);
1221 assert_eq
!(a
.len(), 2);
1222 assert_eq
!(b
.len(), 2);
1224 assert_eq
!(a
[1], "a");
1225 assert_eq
!(a
[2], "b");
1227 assert_eq
!(b
[3], "c");
1228 assert_eq
!(b
[4], "d");
1237 let b
= a
.split_off(0);
1239 assert_eq
!(a
.len(), 0);
1240 assert_eq
!(b
.len(), 4);
1241 assert_eq
!(b
[1], "a");
1242 assert_eq
!(b
[2], "b");
1243 assert_eq
!(b
[3], "c");
1244 assert_eq
!(b
[4], "d");
1246 // Split behind max_key
1253 let b
= a
.split_off(5);
1255 assert_eq
!(a
.len(), 4);
1256 assert_eq
!(b
.len(), 0);
1257 assert_eq
!(a
[1], "a");
1258 assert_eq
!(a
[2], "b");
1259 assert_eq
!(a
[3], "c");
1260 assert_eq
!(a
[4], "d");
1265 let mut map
= VecMap
::new();
1266 let empty
= VecMap
::<i32>::new();
1271 let map_str
= format
!("{:?}", map
);
1272 assert
!(map_str
== "{1: 2, 3: 4}" || map_str
== "{3: 4, 1: 2}");
1273 assert_eq
!(format
!("{:?}", empty
), "{}");
1278 let mut a
= VecMap
::new();
1284 assert_eq
!(a
.clone().iter().collect
::<Vec
<_
>>(), [(1, &'x'
), (4, &'y'
), (6, &'z'
)]);
1289 let mut a
= VecMap
::new();
1290 let mut b
= VecMap
::new();
1293 assert
!(a
.insert(0, 5).is_none());
1295 assert
!(b
.insert(0, 4).is_none());
1297 assert
!(a
.insert(5, 19).is_none());
1299 assert
!(!b
.insert(0, 5).is_none());
1301 assert
!(b
.insert(5, 19).is_none());
1305 b
= VecMap
::with_capacity(1);
1311 let mut a
= VecMap
::new();
1312 let mut b
= VecMap
::new();
1314 assert
!(!(a
< b
) && !(b
< a
));
1315 assert
!(b
.insert(2, 5).is_none());
1317 assert
!(a
.insert(2, 7).is_none());
1318 assert
!(!(a
< b
) && b
< a
);
1319 assert
!(b
.insert(1, 0).is_none());
1321 assert
!(a
.insert(0, 6).is_none());
1323 assert
!(a
.insert(6, 2).is_none());
1324 assert
!(a
< b
&& !(b
< a
));
1329 let mut a
= VecMap
::new();
1330 let mut b
= VecMap
::new();
1332 assert
!(a
<= b
&& a
>= b
);
1333 assert
!(a
.insert(1, 1).is_none());
1334 assert
!(a
> b
&& a
>= b
);
1335 assert
!(b
< a
&& b
<= a
);
1336 assert
!(b
.insert(2, 2).is_none());
1337 assert
!(b
> a
&& b
>= a
);
1338 assert
!(a
< b
&& a
<= b
);
1343 fn hash
<T
: Hash
>(t
: &T
) -> u64 {
1344 let mut s
= SipHasher
::new();
1349 let mut x
= VecMap
::new();
1350 let mut y
= VecMap
::new();
1352 assert
!(hash(&x
) == hash(&y
));
1361 assert
!(hash(&x
) == hash(&y
));
1363 x
.insert(1000, 'd'
);
1366 assert
!(hash(&x
) == hash(&y
));
1370 fn test_from_iter() {
1371 let xs
= [(1, 'a'
), (2, 'b'
), (3, 'c'
), (4, 'd'
), (5, 'e'
)];
1373 let map
: VecMap
<_
> = xs
.iter().cloned().collect();
1375 for &(k
, v
) in &xs
{
1376 assert_eq
!(map
.get(k
), Some(&v
));
1382 let mut map
= VecMap
::new();
1388 assert_eq
!(map
[3], 4);
1393 fn test_index_nonexistent() {
1394 let mut map
= VecMap
::new();
1405 let xs
= [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1407 let mut map
: VecMap
<_
> = xs
.iter().cloned().collect();
1409 // Existing key (insert)
1410 match map
.entry(1) {
1411 Vacant(_
) => unreachable
!(),
1412 Occupied(mut view
) => {
1413 assert_eq
!(view
.get(), &10);
1414 assert_eq
!(view
.insert(100), 10);
1418 assert_eq
!(map
.get(1).unwrap(), &100);
1419 assert_eq
!(map
.len(), 6);
1421 // Existing key (update)
1422 match map
.entry(2) {
1423 Vacant(_
) => unreachable
!(),
1424 Occupied(mut view
) => {
1425 let v
= view
.get_mut();
1430 assert_eq
!(map
.get(2).unwrap(), &200);
1431 assert_eq
!(map
.len(), 6);
1433 // Existing key (take)
1434 match map
.entry(3) {
1435 Vacant(_
) => unreachable
!(),
1437 assert_eq
!(view
.remove(), 30);
1441 assert_eq
!(map
.get(3), None
);
1442 assert_eq
!(map
.len(), 5);
1444 // Inexistent key (insert)
1445 match map
.entry(10) {
1446 Occupied(_
) => unreachable
!(),
1448 assert_eq
!(*view
.insert(1000), 1000);
1452 assert_eq
!(map
.get(10).unwrap(), &1000);
1453 assert_eq
!(map
.len(), 6);
1457 fn test_extend_ref() {
1458 let mut a
= VecMap
::new();
1460 let mut b
= VecMap
::new();
1462 b
.insert(3, "three");
1466 assert_eq
!(a
.len(), 3);
1467 assert_eq
!(a
[&1], "one");
1468 assert_eq
!(a
[&2], "two");
1469 assert_eq
!(a
[&3], "three");
1473 #[cfg(feature = "eders")]
1475 use serde
::{Serialize, Deserialize}
;
1476 fn impls_serde_traits
<S
: Serialize
+ Deserialize
>() {}
1478 impls_serde_traits
::<VecMap
<u32>>();