Skip to content
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

Include the length in BTree hashes #89443

Merged
merged 1 commit into from
Oct 4, 2021
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions library/alloc/src/collections/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1968,6 +1968,7 @@ impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.len().hash(state);
for elt in self {
elt.hash(state);
}
Expand Down
14 changes: 12 additions & 2 deletions library/alloc/tests/btree_set_hash.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use crate::hash;
use std::collections::BTreeSet;

#[test]
fn test_hash() {
use crate::hash;

let mut x = BTreeSet::new();
let mut y = BTreeSet::new();

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

assert_eq!(hash(&x), hash(&y));
}

#[test]
fn test_prefix_free() {
let x = BTreeSet::from([1, 2, 3]);
let y = BTreeSet::<i32>::new();

// If hashed by iteration alone, `(x, y)` and `(y, x)` would visit the same
// order of elements, resulting in the same hash. But now that we also hash
// the length, they get distinct sequences of hashed data.
assert_ne!(hash(&(&x, &y)), hash(&(&y, &x)));
}