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

Improve std::Path's Hash quality by avoiding prefix collisions #127297

Merged
merged 3 commits into from
Jul 7, 2024
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
13 changes: 9 additions & 4 deletions library/std/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3098,15 +3098,19 @@ impl Hash for Path {
let bytes = &bytes[prefix_len..];

let mut component_start = 0;
let mut bytes_hashed = 0;
// track some extra state to avoid prefix collisions.
// ["foo", "bar"] and ["foobar"], will have the same payload bytes
// but result in different chunk_bits
let mut chunk_bits: usize = 0;

for i in 0..bytes.len() {
let is_sep = if verbatim { is_verbatim_sep(bytes[i]) } else { is_sep_byte(bytes[i]) };
if is_sep {
if i > component_start {
let to_hash = &bytes[component_start..i];
chunk_bits = chunk_bits.wrapping_add(to_hash.len());
chunk_bits = chunk_bits.rotate_right(2);
h.write(to_hash);
bytes_hashed += to_hash.len();
}

// skip over separator and optionally a following CurDir item
Expand All @@ -3127,11 +3131,12 @@ impl Hash for Path {

if component_start < bytes.len() {
let to_hash = &bytes[component_start..];
chunk_bits = chunk_bits.wrapping_add(to_hash.len());
chunk_bits = chunk_bits.rotate_right(2);
h.write(to_hash);
bytes_hashed += to_hash.len();
}

h.write_usize(bytes_hashed);
h.write_usize(chunk_bits);
}
}

Expand Down
35 changes: 35 additions & 0 deletions library/std/src/path/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1545,6 +1545,20 @@ pub fn test_compare() {
relative_from: Some("")
);

tc!("foo//", "foo",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);

tc!("foo///", "foo",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);

tc!("foo/.", "foo",
eq: true,
starts_with: true,
Expand All @@ -1559,13 +1573,34 @@ pub fn test_compare() {
relative_from: Some("")
);

tc!("foo/.//bar", "foo/bar",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);

tc!("foo//./bar", "foo/bar",
eq: true,
starts_with: true,
ends_with: true,
relative_from: Some("")
);

tc!("foo/bar", "foo",
eq: false,
starts_with: true,
ends_with: false,
relative_from: Some("bar")
);

tc!("foo/bar", "foobar",
eq: false,
starts_with: false,
ends_with: false,
relative_from: None
);

tc!("foo/bar/baz", "foo/bar",
eq: false,
starts_with: true,
Expand Down
Loading