ihash 0.1.2

World's fastest high-quality non-cryptographic hash, deterministic cross-platform XOF, and seekable stream cipher
Documentation
use crate::{
  backend::aes128::Aes128,
  const_fn::{M_CTR, STREAM_FIN_LI, STREAM_KEY_LI},
  state::BLOCK_LEN,
};

/// CTR keystream block generator implemented by scalar, 8-lane 128-bit, and wide VAES backends.
pub(crate) trait CtrKernel: Copy {
  unsafe fn ctr<const XOR: bool>(self, root: &[u8; 32], blk: u64, buf: &mut [u8]);
}

/// Derives 4 vector AES-CTR round keys from the 256-bit root digest.
#[inline(always)]
pub(crate) unsafe fn split_root<L: Aes128>(ctx: L, root: &[u8; 32]) -> [L::V; 4] {
  // SAFETY: caller satisfies target features and root holds 32 bytes.
  unsafe {
    let rk0 = ctx.ld(root.as_ptr());
    let rk1 = ctx.ld(root.as_ptr().add(BLOCK_LEN));
    let rk2 = ctx.xor(rk0, ctx.ld(STREAM_KEY_LI.as_ptr()));
    let rk3 = ctx.xor(rk1, ctx.ld(STREAM_FIN_LI.as_ptr()));
    [rk0, rk1, rk2, rk3]
  }
}

/// Generates or XORs trailing 16-byte AES-CTR keystream blocks one block at a time.
#[inline(always)]
pub(crate) unsafe fn ctr_1x128<L: Aes128, const XOR: bool>(
  ctx: L,
  rk_li: [L::V; 4],
  mut blk: u64,
  mut ptr: *mut u8,
  mut rem: usize,
) {
  debug_assert!(rem.is_multiple_of(BLOCK_LEN));
  // SAFETY: caller satisfies target features and ptr holds rem writable/readable bytes.
  unsafe {
    while rem >= BLOCK_LEN {
      let c = ctx.pair_v(blk, blk.wrapping_mul(M_CTR));
      let x = ctx.ctr_prep_1(c, rk_li[0]);
      let x = ctx.ctr_mid_1(x, rk_li[1]);
      let x = ctx.ctr_mid_1(x, rk_li[2]);
      let k = ctx.ctr_fin_1(x, rk_li[3], rk_li[0]);
      if XOR {
        ctx.st(ptr, ctx.xor(ctx.ld(ptr), k));
      } else {
        ctx.st(ptr, k);
      }
      ptr = ptr.add(BLOCK_LEN);
      rem -= BLOCK_LEN;
      blk = blk.wrapping_add(1);
    }
  }
}