Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demotest Rust Hasher who return the Square Sum of the hashed values
use std::hash::Hasher;
use std::hash::BuildHasher;
struct SquareSumHasher {
state: u64,
}
impl SquareSumHasher {
fn new(state: u64) -> Self {
SquareSumHasher { state }
}
}
impl Hasher for SquareSumHasher {
fn finish(&self) -> u64 {
self.state
}
fn write(&mut self, bytes: &[u8]) {
for i in bytes {
self.write_u8(*i);
}
}
fn write_u8(&mut self, i: u8) { self.state += (i as u64).pow(2); }
fn write_u16(&mut self, i: u16) { self.state += (i as u64).pow(2); }
fn write_u32(&mut self, i: u32) { self.state += (i as u64).pow(2); }
fn write_u64(&mut self, i: u64) { self.state += (i as u64).pow(2); }
fn write_usize(&mut self, i: usize) { self.state += (i as u64).pow(2); }
fn write_i8(&mut self, i: i8) { self.state += (i.abs() as u64).pow(2); }
fn write_i16(&mut self, i: i16) { self.state += (i.abs() as u64).pow(2); }
fn write_i64(&mut self, i: i64) { self.state += (i.abs() as u64).pow(2); }
fn write_i32(&mut self, i: i32) { self.state += (i.abs() as u64).pow(2); }
fn write_isize(&mut self, i: isize) { self.state += (i.abs() as u64).pow(2); }
}
struct BuildSquareSumHasher {}
impl BuildSquareSumHasher {
fn new() -> BuildSquareSumHasher {
BuildSquareSumHasher {}
}
}
impl BuildHasher for BuildSquareSumHasher {
type Hasher = SquareSumHasher;
fn build_hasher(&self) -> Self::Hasher {
Self::Hasher::new(0_u64)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment