From e583ca1936eeaf4b4b5778b3499e30a50edc1a88 Mon Sep 17 00:00:00 2001 From: Hesam Pakdaman <14890379+hesampakdaman@users.noreply.github.com> Date: Wed, 15 May 2024 22:45:36 +0200 Subject: [PATCH] Tweak hash (#14) --- src/weather/key.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/weather/key.rs b/src/weather/key.rs index a588991..885f8d2 100644 --- a/src/weather/key.rs +++ b/src/weather/key.rs @@ -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 + ) } }