Skip to content

Instantly share code, notes, and snippets.

@charterchap
Last active February 28, 2017 02:04
Show Gist options
  • Save charterchap/f99da88639b2710d9931470c8d8bf9bf to your computer and use it in GitHub Desktop.
Save charterchap/f99da88639b2710d9931470c8d8bf9bf to your computer and use it in GitHub Desktop.
fnv1_32 and fnv1a_32 in rust
// see libhashkit/fnv_32.cc from memcached
// Just using this as excuse to test out the Rust lang
// be warned on correctness, completeness, etc
// Should match libhashkit
// should also match https://www.nitrxgen.net/hashgen/
// FNV hash'es lifted from Dustin Sallings work
const FNV_32_INIT: u32 = 2166136261;
const FNV_32_PRIME: u32 = 16777619;
fn main()
{
gut_check();
}
fn hashkit_fnv1a_32(key: &Vec<u8>) -> u32
{
let mut hash = FNV_32_INIT;
for byte in key.iter() {
let val = *byte as u32;
hash ^= val;
hash = hash.wrapping_mul(FNV_32_PRIME);
}
return hash;
}
fn hashkit_fnv1_32(key: &Vec<u8>) -> u32
{
let mut hash = FNV_32_INIT;
for byte in key.iter() {
let val = *byte as u32;
hash = hash.wrapping_mul(FNV_32_PRIME);
hash ^= val;
}
return hash;
}
fn gut_check() {
assert_eq!( hashkit_fnv1a_32( &String::from("helloworld").into_bytes() ), 0x3B9F5C61 );
assert_eq!( hashkit_fnv1_32 ( &String::from("helloworld").into_bytes() ), 0x944d07a1 );
assert_eq!( hashkit_fnv1a_32( &String::from("rollmostar").into_bytes() ), 0xdbdccafa );
assert_eq!( hashkit_fnv1_32 ( &String::from("rollmostar").into_bytes() ), 0x32220158 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment