Last active
February 28, 2017 02:04
-
-
Save charterchap/f99da88639b2710d9931470c8d8bf9bf to your computer and use it in GitHub Desktop.
fnv1_32 and fnv1a_32 in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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