Skip to content

Instantly share code, notes, and snippets.

@ExpHP
Created Apr 4, 2018
Embed
What would you like to do?
pub mod id_hash {
use ::std::collections::{HashSet, HashMap};
use ::std::hash::{Hasher, BuildHasherDefault};
/// Hashes u64s to themselves, assuming they already come from
/// a uniform distribution.
///
/// THIS IS PROBABLY A BAD IDEA.
#[derive(Debug, Default)]
pub struct IdHasher(Option<u64>);
pub type Set<K> = HashSet<K, BuildHasherDefault<IdHasher>>;
pub type Map<K, V> = HashMap<K, V, BuildHasherDefault<IdHasher>>;
const ERR_WRONG: &'static str = "Only a single u64 may be written to IdentityHasher";
const ERR_NOTHING: &'static str = "A single u64 must be written to IdentityHasher";
impl Hasher for IdHasher {
#[inline(always)]
fn finish(&self) -> u64 {
self.0.expect(ERR_NOTHING)
}
#[inline(always)]
fn write(&mut self, bytes: &[u8]) {
assert_eq!(bytes.len(), 8, "{}", ERR_WRONG);
let int_ptr = bytes.as_ptr() as *const u64;
self.write_u64(unsafe { *int_ptr });
}
#[inline(always)]
fn write_u64(&mut self, i: u64) {
assert!(self.0.is_none(), "{}", ERR_WRONG);
self.0 = Some(i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment