ihash 0.1.2

World's fastest high-quality non-cryptographic hash, deterministic cross-platform XOF, and seekable stream cipher
Documentation
mod ctr;
mod lane;
mod sbox;
mod tbl;

use ctr::{ctr_simd, ctr_soft};
use fearless_simd::{Level, dispatch};
use lane::{vperm_hash_hi, vperm_hash_lo};

use super::seed::hash64_with_level;
use crate::{arch::soft, backend::DigestBackend, state::BLOCK_LEN};

#[derive(Clone, Copy)]
pub(super) struct CpuBackend(pub(super) Level);

impl DigestBackend for CpuBackend {
  #[inline(always)]
  fn hash64(self, data: &[u8], seed: u64) -> u64 {
    hash64_with_level(data, seed, self.0)
  }

  #[inline(always)]
  fn ctr<const XOR: bool>(self, root: &[u8; 32], blk: u64, buf: &mut [u8]) {
    ctr_with_level::<XOR>(root, blk, buf, self.0);
  }
}

/// Detects the active `fearless_simd::Level` for pure-CPU vector execution.
#[inline(always)]
pub(super) fn detect_level() -> Level {
  Level::try_detect().unwrap_or_else(Level::baseline)
}

#[cold]
#[inline]
pub(super) fn compress_lo<const SEED0: bool>(data: &[u8], seed: u64, level: Level) -> u128 {
  if level.is_fallback() {
    return soft::compress_128::<SEED0>(data, seed);
  }
  dispatch!(level, simd => vperm_hash_lo::<_, SEED0>(simd, data, seed))
}

#[cold]
#[inline]
pub(super) fn compress_hi<const SEED0: bool>(data: &[u8], seed: u64, level: Level) -> [u8; 32] {
  if level.is_fallback() {
    return soft::compress_256::<SEED0>(data, seed);
  }
  dispatch!(level, simd => vperm_hash_hi::<_, SEED0>(simd, data, seed))
}

#[inline]
pub(super) fn ctr_with_level<const XOR: bool>(
  root: &[u8; 32],
  blk: u64,
  buf: &mut [u8],
  level: Level,
) {
  debug_assert!(buf.len().is_multiple_of(BLOCK_LEN));
  if buf.is_empty() {
    return;
  }
  if buf.len() >= 64 && !level.is_fallback() {
    dispatch!(level, simd => ctr_simd::<_, XOR>(simd, root, blk, buf));
    return;
  }
  ctr_soft::<XOR>(root, blk, buf);
}