Skip to content

Implement Hash for TreeSet #15633

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 13, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/libcollections/treemap.rs
Original file line number Diff line number Diff line change
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