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.
This commit is contained in:
Tobias Bucher 2014-12-09 20:05:51 +01:00
parent 67ae3a49e4
commit 20eaf168c5

View File

@ -21,6 +21,7 @@ use core::iter;
use core::iter::{Enumerate, FilterMap};
use core::mem::replace;
use hash::{Hash, Writer};
use {vec, slice};
use vec::Vec;
@ -81,6 +82,19 @@ impl<V:Clone> Clone for VecMap<V> {
}
}
impl<S: Writer, V: Hash<S>> Hash<S> for VecMap<V> {
fn hash(&self, state: &mut S) {
// In order to not traverse the `VecMap` twice, count the elements
// during iteration.
let mut count: uint = 0;
for elt in self.iter() {
elt.hash(state);
count += 1;
}
count.hash(state);
}
}
impl<V> VecMap<V> {
/// Creates an empty `VecMap`.
///
@ -605,6 +619,7 @@ pub type MoveItems<V> =
mod test_map {
use std::prelude::*;
use vec::Vec;
use hash::hash;
use super::VecMap;
@ -918,6 +933,28 @@ mod test_map {
assert!(a < b && a <= b);
}
#[test]
fn test_hash() {
let mut x = VecMap::new();
let mut y = VecMap::new();
assert!(hash(&x) == hash(&y));
x.insert(1, 'a');
x.insert(2, 'b');
x.insert(3, 'c');
y.insert(3, 'c');
y.insert(2, 'b');
y.insert(1, 'a');
assert!(hash(&x) == hash(&y));
x.insert(1000, 'd');
x.remove(&1000);
assert!(hash(&x) == hash(&y));
}
#[test]
fn test_from_iter() {
let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];