Skip to content

Commit

Permalink
Implement Hash trait for TreeSet and TreeMap.
Browse files Browse the repository at this point in the history
  • Loading branch information
nham committed Jul 13, 2014
1 parent ad7ef8c commit a54dc54
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/libcollections/treemap.rs
Expand Up @@ -22,6 +22,7 @@ use core::iter::Peekable;
use core::iter;
use core::mem::{replace, swap};
use core::ptr;
use std::hash::{Writer, Hash};

use {Collection, Mutable, Set, MutableSet, MutableMap, Map};
use vec::Vec;
Expand Down Expand Up @@ -1055,6 +1056,14 @@ impl<K: Ord, V> Extendable<(K, V)> for TreeMap<K, V> {
}
}

impl<S: Writer, K: Ord + Hash<S>, V: Hash<S>> Hash<S> for TreeMap<K, V> {
fn hash(&self, state: &mut S) {
for elt in self.iter() {
elt.hash(state);
}
}
}

impl<T: Ord> FromIterator<T> for TreeSet<T> {
fn from_iter<Iter: Iterator<T>>(iter: Iter) -> TreeSet<T> {
let mut set = TreeSet::new();
Expand All @@ -1072,6 +1081,14 @@ impl<T: Ord> Extendable<T> for TreeSet<T> {
}
}

impl<S: Writer, T: Ord + Hash<S>> Hash<S> for TreeSet<T> {
fn hash(&self, state: &mut S) {
for elt in self.iter() {
elt.hash(state);
}
}
}

#[cfg(test)]
mod test_treemap {
use std::prelude::*;
Expand Down Expand Up @@ -1608,6 +1625,7 @@ mod bench {
#[cfg(test)]
mod test_set {
use std::prelude::*;
use std::hash;

use {Set, MutableSet, Mutable, MutableMap};
use super::{TreeMap, TreeSet};
Expand Down Expand Up @@ -1748,6 +1766,22 @@ mod test_set {
assert!(m.clone() == m);
}

#[test]
fn test_hash() {
let mut x = TreeSet::new();
let mut y = TreeSet::new();

x.insert(1i);
x.insert(2);
x.insert(3);

y.insert(3i);
y.insert(2);
y.insert(1);

assert!(hash::hash(&x) == hash::hash(&y));
}

fn check(a: &[int],
b: &[int],
expected: &[int],
Expand Down

5 comments on commit a54dc54

@bors
Copy link
Contributor

@bors bors commented on a54dc54 Jul 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from alexcrichton
at nham@a54dc54

@bors
Copy link
Contributor

@bors bors commented on a54dc54 Jul 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging nham/rust/hash_treeset = a54dc54 into auto

@bors
Copy link
Contributor

@bors bors commented on a54dc54 Jul 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nham/rust/hash_treeset = a54dc54 merged ok, testing candidate = 88231a9

@bors
Copy link
Contributor

@bors bors commented on a54dc54 Jul 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = 88231a9

Please sign in to comment.