Skip to content

Commit eb27215

Browse files
committed
Add sanity checks with alternate hashers
1 parent 9068eb7 commit eb27215

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

tests/hasher.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//! Sanity check that alternate hashers work correctly.
2+
3+
use hashbrown::HashSet;
4+
use std::hash::{BuildHasher, BuildHasherDefault, Hasher};
5+
6+
fn check<S: BuildHasher + Default>() {
7+
let range = 0..1_000;
8+
9+
let mut set = HashSet::<i32, S>::default();
10+
set.extend(range.clone());
11+
12+
assert!(!set.contains(&i32::min_value()));
13+
assert!(!set.contains(&(range.start - 1)));
14+
for i in range.clone() {
15+
assert!(set.contains(&i));
16+
}
17+
assert!(!set.contains(&range.end));
18+
assert!(!set.contains(&i32::max_value()));
19+
}
20+
21+
/// Use hashbrown's default hasher.
22+
#[test]
23+
fn default() {
24+
check::<hashbrown::hash_map::DefaultHashBuilder>();
25+
}
26+
27+
/// Use std's default hasher.
28+
#[test]
29+
fn random_state() {
30+
check::<std::collections::hash_map::RandomState>();
31+
}
32+
33+
/// Use a constant 0 hash.
34+
#[test]
35+
fn zero() {
36+
#[derive(Default)]
37+
struct ZeroHasher;
38+
39+
impl Hasher for ZeroHasher {
40+
fn finish(&self) -> u64 {
41+
0
42+
}
43+
fn write(&mut self, _: &[u8]) {}
44+
}
45+
46+
check::<BuildHasherDefault<ZeroHasher>>();
47+
}
48+
49+
/// Use a constant maximum hash.
50+
#[test]
51+
fn max() {
52+
#[derive(Default)]
53+
struct MaxHasher;
54+
55+
impl Hasher for MaxHasher {
56+
fn finish(&self) -> u64 {
57+
u64::max_value()
58+
}
59+
fn write(&mut self, _: &[u8]) {}
60+
}
61+
62+
check::<BuildHasherDefault<MaxHasher>>();
63+
}

0 commit comments

Comments
 (0)