#![no_std]
pub const fn hash(bytes: &[u8]) -> u32 {
hash_with_initial(5381u32, bytes)
}
pub const fn hash_with_initial(init: u32, bytes: &[u8]) -> u32 {
let mut hash = init;
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
hash = (hash << 5).wrapping_add(hash) ^ (c as u32);
i += 1;
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty() {
let hash = hash(b"");
assert_eq!(hash, 5381);
}
#[test]
fn test_null() {
let hash = hash(&[0]);
assert_eq!(hash, (5381 << 5) + 5381);
}
#[test]
fn test_hello_world() {
let hash = hash(b"Ohai world!");
assert_eq!(hash, 3256904681u32);
}
#[test]
fn test_u32_max() {
let hash = hash(&u32::MAX.to_be_bytes());
assert_eq!(hash, 2083728837);
}
#[test]
fn test_append_more() {
let all_at_once = hash(b"foobar");
let first = hash(b"foo");
let second = hash_with_initial(first, b"bar");
assert_eq!(all_at_once, second);
}
}