Derive Hash for TrieMap and TrieSet

This commit is contained in:
nham 2014-07-22 16:36:09 -04:00
parent 31c908b7be
commit 9e83d29f30

View File

@ -17,6 +17,7 @@
use core::mem::zeroed; use core::mem::zeroed;
use core::mem; use core::mem;
use core::uint; use core::uint;
use std::hash::{Writer, Hash};
use {Collection, Mutable, Map, MutableMap, Set, MutableSet}; use {Collection, Mutable, Map, MutableMap, Set, MutableSet};
use slice::{Items, MutItems}; use slice::{Items, MutItems};
@ -292,7 +293,16 @@ fn extend<Iter: Iterator<(uint, T)>>(&mut self, mut iter: Iter) {
} }
} }
impl<S: Writer, T: Hash<S>> Hash<S> for TrieMap<T> {
fn hash(&self, state: &mut S) {
for elt in self.iter() {
elt.hash(state);
}
}
}
#[allow(missing_doc)] #[allow(missing_doc)]
#[deriving(Hash)]
pub struct TrieSet { pub struct TrieSet {
map: TrieMap<()> map: TrieMap<()>
} }
@ -1049,6 +1059,7 @@ fn bench_insert_small_low_bits(b: &mut Bencher) {
mod test_set { mod test_set {
use std::prelude::*; use std::prelude::*;
use std::uint; use std::uint;
use std::hash;
use {MutableSet, Set}; use {MutableSet, Set};
use super::TrieSet; use super::TrieSet;
@ -1082,4 +1093,20 @@ fn test_from_iter() {
assert!(set.contains(x)); assert!(set.contains(x));
} }
} }
#[test]
fn test_hash() {
let mut x = TrieSet::new();
let mut y = TrieSet::new();
x.insert(1);
x.insert(2);
x.insert(3);
y.insert(3);
y.insert(2);
y.insert(1);
assert!(hash::hash(&x) == hash::hash(&y));
}
} }