Skip to content

Commit 337ad5b

Browse files
authoredOct 4, 2021
Rollup merge of rust-lang#89443 - cuviper:btree-hash-len, r=dtolnay
Include the length in BTree hashes This change makes it consistent with `Hash` for all other collections.
2 parents 54f9a67 + d6fde80 commit 337ad5b

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed
 

‎library/alloc/src/collections/btree/map.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1968,6 +1968,7 @@ impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
19681968
#[stable(feature = "rust1", since = "1.0.0")]
19691969
impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
19701970
fn hash<H: Hasher>(&self, state: &mut H) {
1971+
self.len().hash(state);
19711972
for elt in self {
19721973
elt.hash(state);
19731974
}

‎library/alloc/tests/btree_set_hash.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1+
use crate::hash;
12
use std::collections::BTreeSet;
23

34
#[test]
45
fn test_hash() {
5-
use crate::hash;
6-
76
let mut x = BTreeSet::new();
87
let mut y = BTreeSet::new();
98

@@ -17,3 +16,14 @@ fn test_hash() {
1716

1817
assert_eq!(hash(&x), hash(&y));
1918
}
19+
20+
#[test]
21+
fn test_prefix_free() {
22+
let x = BTreeSet::from([1, 2, 3]);
23+
let y = BTreeSet::<i32>::new();
24+
25+
// If hashed by iteration alone, `(x, y)` and `(y, x)` would visit the same
26+
// order of elements, resulting in the same hash. But now that we also hash
27+
// the length, they get distinct sequences of hashed data.
28+
assert_ne!(hash(&(&x, &y)), hash(&(&y, &x)));
29+
}

0 commit comments

Comments
 (0)
Please sign in to comment.