use core::hash::{BuildHasher, Hash, Hasher};
use fearless_simd::Level;
use super::vperm::{CpuBackend, detect_level};
use crate::hasher::{HasherCore, impl_ihasher, init_build_seed, random_or_zero_seed};
#[derive(Clone, Debug)]
pub struct IHasher {
core: HasherCore,
level: Level,
}
impl IHasher {
#[must_use]
#[inline]
pub fn new() -> Self {
Self::with_seed(0)
}
#[must_use]
#[inline]
pub const fn with_level(level: Level) -> Self {
Self::with_seed_and_level(0, level)
}
#[must_use]
#[inline]
pub(super) fn with_seed(seed: u64) -> Self {
Self::with_seed_and_level(seed, detect_level())
}
#[must_use]
#[inline]
pub(super) const fn with_seed_and_level(seed: u64, level: Level) -> Self {
Self {
core: HasherCore::with_seed(seed),
level,
}
}
#[inline(always)]
const fn from_raw(raw_seed: u64, level: Level) -> Self {
Self {
core: HasherCore(raw_seed),
level,
}
}
#[must_use]
#[inline]
pub fn finish_u128(&self) -> u128 {
self.core.finish_u128()
}
#[inline(always)]
const fn backend(&self) -> CpuBackend {
CpuBackend(self.level)
}
}
impl Default for IHasher {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl_ihasher!(IHasher, core);
#[derive(Clone, Copy, Debug)]
pub struct IBuildHasher {
seed: u64,
level: Level,
}
impl IBuildHasher {
#[must_use]
#[inline]
pub fn new() -> Self {
Self::default()
}
#[must_use]
#[inline]
pub fn with_level(level: Level) -> Self {
Self::with_seed_and_level(random_or_zero_seed(), level)
}
#[must_use]
#[inline]
pub(super) fn with_seed(seed: u64) -> Self {
Self::with_seed_and_level(seed, detect_level())
}
#[must_use]
#[inline]
pub(super) const fn with_seed_and_level(seed: u64, level: Level) -> Self {
Self {
seed: init_build_seed(seed),
level,
}
}
}
impl Default for IBuildHasher {
#[inline]
fn default() -> Self {
Self::with_seed(random_or_zero_seed())
}
}
impl BuildHasher for IBuildHasher {
type Hasher = IHasher;
#[inline(always)]
fn build_hasher(&self) -> Self::Hasher {
IHasher::from_raw(self.seed, self.level)
}
#[inline(always)]
fn hash_one<T: Hash>(&self, x: T) -> u64 {
let mut hasher = IHasher::from_raw(self.seed, self.level);
x.hash(&mut hasher);
hasher.finish()
}
}