#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
any::TypeId,
hash::{BuildHasher, Hash, Hasher},
};
#[cfg(feature = "no_std")]
pub type StraightHashMap<V> = hashbrown::HashMap<u64, V, StraightHasherBuilder>;
#[cfg(not(feature = "no_std"))]
pub type StraightHashMap<V> = std::collections::HashMap<u64, V, StraightHasherBuilder>;
pub const ALT_ZERO_HASH: u64 = 42;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct StraightHasher(u64);
impl Hasher for StraightHasher {
#[inline(always)]
fn finish(&self) -> u64 {
self.0
}
#[inline(always)]
fn write(&mut self, _bytes: &[u8]) {
panic!("StraightHasher can only hash u64 values");
}
#[inline(always)]
fn write_u64(&mut self, i: u64) {
if i == 0 {
self.0 = ALT_ZERO_HASH;
} else {
self.0 = i;
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct StraightHasherBuilder;
impl BuildHasher for StraightHasherBuilder {
type Hasher = StraightHasher;
#[inline(always)]
fn build_hasher(&self) -> Self::Hasher {
StraightHasher(ALT_ZERO_HASH)
}
}
#[inline(always)]
#[must_use]
pub fn get_hasher() -> ahash::AHasher {
ahash::AHasher::default()
}
#[inline]
#[must_use]
pub fn calc_var_hash<'a>(
modules: impl IntoIterator<Item = &'a str, IntoIter = impl ExactSizeIterator<Item = &'a str>>,
var_name: &str,
) -> u64 {
let s = &mut get_hasher();
let iter = modules.into_iter();
let len = iter.len();
iter.skip(1).for_each(|m| m.hash(s));
len.hash(s);
var_name.hash(s);
match s.finish() {
0 => ALT_ZERO_HASH,
r => r,
}
}
#[inline]
#[must_use]
pub fn calc_fn_hash<'a>(
namespace: impl IntoIterator<Item = &'a str, IntoIter = impl ExactSizeIterator<Item = &'a str>>,
fn_name: &str,
num: usize,
) -> u64 {
let s = &mut get_hasher();
let iter = namespace.into_iter();
let len = iter.len();
iter.skip(1).for_each(|m| m.hash(s));
len.hash(s);
fn_name.hash(s);
num.hash(s);
match s.finish() {
0 => ALT_ZERO_HASH,
r => r,
}
}
#[inline]
#[must_use]
pub fn calc_fn_params_hash(
params: impl IntoIterator<Item = TypeId, IntoIter = impl ExactSizeIterator<Item = TypeId>>,
) -> u64 {
let s = &mut get_hasher();
let iter = params.into_iter();
let len = iter.len();
iter.for_each(|t| {
t.hash(s);
});
len.hash(s);
match s.finish() {
0 => ALT_ZERO_HASH,
r => r,
}
}
#[inline(always)]
#[must_use]
pub const fn combine_hashes(a: u64, b: u64) -> u64 {
match a ^ b {
0 => ALT_ZERO_HASH,
r => r,
}
}