Created
April 4, 2020 03:15
-
-
Save thyeem/67da36d2f64c45eacbb121cd0ebb6c4e to your computer and use it in GitHub Desktop.
with a manual BuildHasher
This file contains hidden or 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
use std::hash::{BuildHasher, Hasher}; | |
use std::collections::HashMap; | |
fn bytes_to_int(bytes: &[u8]) -> usize { | |
let l = bytes.len(); | |
(0..l).fold(0, |sum, i| { | |
sum + (1 << ((l - i - 1) * 8)) * bytes[i] as usize | |
}) | |
} | |
pub struct MonoHasher { | |
state: u64, | |
} | |
impl MonoHasher { | |
pub fn new(state: u64) -> Self { | |
MonoHasher { state } | |
} | |
} | |
impl Hasher for MonoHasher { | |
fn finish(&self) -> u64 { | |
self.state | |
} | |
fn write(&mut self, bytes: &[u8]) { | |
let state: u64 = if bytes.len() > 8 { | |
bytes_to_int(&bytes[..]) | |
} else { | |
bytes_to_int(bytes) | |
}; | |
self.state += state; | |
} | |
} | |
pub struct BuildMonoHasher {} | |
impl BuildMonoHasher { | |
pub fn new() -> Self { | |
BuildMonoHasher {} | |
} | |
} | |
impl BuildHasher for BuildMonoHasher { | |
type Hasher = MonoHasher; | |
fn build_hasher(&self) -> Self::Hasher { | |
Self::Hasher::new(65536_u64) | |
} | |
} | |
fn main { | |
let s = BuildMonoHasher::new(); | |
let q = HashMap::<&str, u32, BuildMonoHasher>::with_hasher(s); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment