Skip to content

Commit

Permalink
stir the hash state a little to avoid prefix collisions
Browse files Browse the repository at this point in the history
  • Loading branch information
the8472 committed Jul 3, 2024
1 parent dd509c7 commit c28cc9a
Showing 1 changed file with 9 additions and 4 deletions.
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 = 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 += 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 += 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

0 comments on commit c28cc9a

Please sign in to comment.