Skip to content

Commit

Permalink
Tweak hash (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
hesampakdaman authored May 15, 2024
1 parent 9820f33 commit e583ca1
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/weather/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,19 @@ impl Key {
pub fn new(bytes: &[u8]) -> Self {
// djb2 hash fn
// hash(0) = 5381
// hash(i) = hash(i-1) * 33 ^ byte[i]
let hash_fn = |hash, byte: &u8| (hash * 33) ^ u64::from(*byte);
Self(bytes.iter().fold(5381, hash_fn))
// hash(i) = hash(i-1) * 33 + byte[i]
let hash_fn = |hash: u64, &byte| hash.wrapping_mul(33).wrapping_add(byte as u64);

let len = bytes.len();
let first = &bytes[..len.min(8)];
let last = if len > 8 { &bytes[len - 8..] } else { &[] };
Self(
first
.iter()
.chain(last)
.fold(5381, hash_fn)
.wrapping_mul(len as u64), // multiply with the length of input to ensure no collisions
)
}
}

Expand Down

0 comments on commit e583ca1

Please sign in to comment.