Skip to content

Commit 20eaf16

Browse files
committed
Add a proper Hash implementation for VecMap
Also re-add the previously deleted test with an additional test that would have failed before, when the hash function depended on the capacity.
1 parent 67ae3a4 commit 20eaf16

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/libcollections/vec_map.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use core::iter;
2121
use core::iter::{Enumerate, FilterMap};
2222
use core::mem::replace;
2323

24+
use hash::{Hash, Writer};
2425
use {vec, slice};
2526
use vec::Vec;
2627

@@ -81,6 +82,19 @@ impl<V:Clone> Clone for VecMap<V> {
8182
}
8283
}
8384

85+
impl<S: Writer, V: Hash<S>> Hash<S> for VecMap<V> {
86+
fn hash(&self, state: &mut S) {
87+
// In order to not traverse the `VecMap` twice, count the elements
88+
// during iteration.
89+
let mut count: uint = 0;
90+
for elt in self.iter() {
91+
elt.hash(state);
92+
count += 1;
93+
}
94+
count.hash(state);
95+
}
96+
}
97+
8498
impl<V> VecMap<V> {
8599
/// Creates an empty `VecMap`.
86100
///
@@ -605,6 +619,7 @@ pub type MoveItems<V> =
605619
mod test_map {
606620
use std::prelude::*;
607621
use vec::Vec;
622+
use hash::hash;
608623

609624
use super::VecMap;
610625

@@ -918,6 +933,28 @@ mod test_map {
918933
assert!(a < b && a <= b);
919934
}
920935

936+
#[test]
937+
fn test_hash() {
938+
let mut x = VecMap::new();
939+
let mut y = VecMap::new();
940+
941+
assert!(hash(&x) == hash(&y));
942+
x.insert(1, 'a');
943+
x.insert(2, 'b');
944+
x.insert(3, 'c');
945+
946+
y.insert(3, 'c');
947+
y.insert(2, 'b');
948+
y.insert(1, 'a');
949+
950+
assert!(hash(&x) == hash(&y));
951+
952+
x.insert(1000, 'd');
953+
x.remove(&1000);
954+
955+
assert!(hash(&x) == hash(&y));
956+
}
957+
921958
#[test]
922959
fn test_from_iter() {
923960
let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];

0 commit comments

Comments
 (0)