Skip to content

Commit c080d26

Browse files
committed
auto merge of #15902 : nham/rust/hash_triemap, r=alexcrichton
cc #15294
2 parents 826b835 + 366c66e commit c080d26

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/libcollections/trie.rs

+55
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use core::default::Default;
1717
use core::mem::zeroed;
1818
use core::mem;
1919
use core::uint;
20+
use std::hash::{Writer, Hash};
2021

2122
use {Collection, Mutable, Map, MutableMap, Set, MutableSet};
2223
use slice::{Items, MutItems};
@@ -40,6 +41,15 @@ pub struct TrieMap<T> {
4041
length: uint
4142
}
4243

44+
impl<T: PartialEq> PartialEq for TrieMap<T> {
45+
fn eq(&self, other: &TrieMap<T>) -> bool {
46+
self.len() == other.len() &&
47+
self.iter().zip(other.iter()).all(|(a, b)| a == b)
48+
}
49+
}
50+
51+
impl<T: Eq> Eq for TrieMap<T> {}
52+
4353
impl<T> Collection for TrieMap<T> {
4454
/// Return the number of elements in the map
4555
#[inline]
@@ -292,7 +302,16 @@ impl<T> Extendable<(uint, T)> for TrieMap<T> {
292302
}
293303
}
294304

305+
impl<S: Writer, T: Hash<S>> Hash<S> for TrieMap<T> {
306+
fn hash(&self, state: &mut S) {
307+
for elt in self.iter() {
308+
elt.hash(state);
309+
}
310+
}
311+
}
312+
295313
#[allow(missing_doc)]
314+
#[deriving(Hash, PartialEq, Eq)]
296315
pub struct TrieSet {
297316
map: TrieMap<()>
298317
}
@@ -661,6 +680,7 @@ mod test_map {
661680
use std::prelude::*;
662681
use std::iter::range_step;
663682
use std::uint;
683+
use std::hash;
664684

665685
use {MutableMap, Map};
666686
use super::{TrieMap, TrieNode, Internal, External, Nothing};
@@ -933,6 +953,41 @@ mod test_map {
933953
assert!(m_lower.iter().all(|(_, &x)| x == 0));
934954
assert!(m_upper.iter().all(|(_, &x)| x == 0));
935955
}
956+
957+
#[test]
958+
fn test_eq() {
959+
let mut a = TrieMap::new();
960+
let mut b = TrieMap::new();
961+
962+
assert!(a == b);
963+
assert!(a.insert(0, 5i));
964+
assert!(a != b);
965+
assert!(b.insert(0, 4i));
966+
assert!(a != b);
967+
assert!(a.insert(5, 19));
968+
assert!(a != b);
969+
assert!(!b.insert(0, 5));
970+
assert!(a != b);
971+
assert!(b.insert(5, 19));
972+
assert!(a == b);
973+
}
974+
975+
#[test]
976+
fn test_hash() {
977+
let mut x = TrieMap::new();
978+
let mut y = TrieMap::new();
979+
980+
assert!(hash::hash(&x) == hash::hash(&y));
981+
x.insert(1, 'a');
982+
x.insert(2, 'b');
983+
x.insert(3, 'c');
984+
985+
y.insert(3, 'c');
986+
y.insert(2, 'b');
987+
y.insert(1, 'a');
988+
989+
assert!(hash::hash(&x) == hash::hash(&y));
990+
}
936991
}
937992

938993
#[cfg(test)]

0 commit comments

Comments
 (0)