ihash 0.1.2

World's fastest high-quality non-cryptographic hash, deterministic cross-platform XOF, and seekable stream cipher
Documentation
use core::slice::{from_raw_parts, from_raw_parts_mut};

use crate::{
  Stream, hash_xof as root_hash_xof, hash32 as root_hash32, hash64 as root_hash64,
  hash128 as root_hash128, hash256 as root_hash256,
  seed::{hash_xof, hash32, hash64, hash128, hash256, stream},
};

/// C-compatible 128-bit digest split into little-endian low and high halves.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IhashU128 {
  /// Low 64 bits of the 128-bit digest.
  pub lo: u64,
  /// High 64 bits of the 128-bit digest.
  pub hi: u64,
}

#[inline(always)]
const fn pack_c_u128(digest: u128) -> IhashU128 {
  IhashU128 {
    lo: digest as u64,
    hi: (digest >> 64) as u64,
  }
}

#[inline(always)]
unsafe fn slice_from_raw<'a>(data: *const u8, len: usize) -> &'a [u8] {
  if len == 0 || data.is_null() {
    &[]
  } else {
    // SAFETY: caller ensures data points to len readable bytes.
    unsafe { from_raw_parts(data, len) }
  }
}

#[inline(always)]
unsafe fn slice_mut_from_raw<'a>(out: *mut u8, len: usize) -> Option<&'a mut [u8]> {
  if len == 0 || out.is_null() {
    None
  } else {
    // SAFETY: caller ensures out points to len writable bytes.
    Some(unsafe { from_raw_parts_mut(out, len) })
  }
}

#[inline(always)]
unsafe fn with_io_slices(
  src: *const u8,
  src_len: usize,
  dst: *mut u8,
  dst_len: usize,
  f: impl FnOnce(&[u8], &mut [u8]),
) {
  // SAFETY: forwarded from caller contract guaranteeing dst_len writable bytes at dst.
  let Some(out) = (unsafe { slice_mut_from_raw(dst, dst_len) }) else {
    return;
  };
  // SAFETY: forwarded from caller contract guaranteeing src_len readable bytes at src.
  f(unsafe { slice_from_raw(src, src_len) }, out);
}

#[inline(always)]
unsafe fn write_digest<const N: usize>(
  data: *const u8,
  len: usize,
  out: *mut u8,
  f: impl FnOnce(&[u8]) -> [u8; N],
) {
  // SAFETY: forwarded from caller contract guaranteeing N writable bytes at out.
  unsafe { with_io_slices(data, len, out, N, |d, dst| dst.copy_from_slice(&f(d))) };
}

/// Computes a 32-bit hash over `len` bytes starting at `data`.
///
/// # Safety
///
/// When `len > 0` and `!data.is_null()`, `data` must point to at least `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash32(data: *const u8, len: usize) -> u32 {
  // SAFETY: forwarded from caller contract.
  root_hash32(unsafe { slice_from_raw(data, len) })
}

/// Computes a seeded 32-bit hash over `len` bytes starting at `data`.
///
/// # Safety
///
/// When `len > 0` and `!data.is_null()`, `data` must point to at least `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash32_seed(data: *const u8, len: usize, seed: u64) -> u32 {
  // SAFETY: forwarded from caller contract.
  hash32(unsafe { slice_from_raw(data, len) }, seed)
}

/// Computes a 64-bit hash over `len` bytes starting at `data`.
///
/// # Safety
///
/// When `len > 0` and `!data.is_null()`, `data` must point to at least `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash64(data: *const u8, len: usize) -> u64 {
  // SAFETY: forwarded from caller contract.
  root_hash64(unsafe { slice_from_raw(data, len) })
}

/// Computes a seeded 64-bit hash over `len` bytes starting at `data`.
///
/// # Safety
///
/// When `len > 0` and `!data.is_null()`, `data` must point to at least `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash64_seed(data: *const u8, len: usize, seed: u64) -> u64 {
  // SAFETY: forwarded from caller contract.
  hash64(unsafe { slice_from_raw(data, len) }, seed)
}

/// Computes a 128-bit hash over `len` bytes starting at `data`.
///
/// # Safety
///
/// When `len > 0` and `!data.is_null()`, `data` must point to at least `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash128(data: *const u8, len: usize) -> IhashU128 {
  // SAFETY: forwarded from caller contract.
  pack_c_u128(root_hash128(unsafe { slice_from_raw(data, len) }))
}

/// Computes a seeded 128-bit hash over `len` bytes starting at `data`.
///
/// # Safety
///
/// When `len > 0` and `!data.is_null()`, `data` must point to at least `len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash128_seed(data: *const u8, len: usize, seed: u64) -> IhashU128 {
  // SAFETY: forwarded from caller contract.
  pack_c_u128(hash128(unsafe { slice_from_raw(data, len) }, seed))
}

/// Computes a 128-bit hash and writes 16 little-endian bytes to `out`.
///
/// # Safety
///
/// `data` must be readable for `len` bytes when non-null, and `out` must be writable for 16 bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash128_out(data: *const u8, len: usize, out: *mut u8) {
  // SAFETY: forwarded from caller contract guaranteeing 16 writable bytes at out.
  unsafe { write_digest(data, len, out, |d| root_hash128(d).to_le_bytes()) };
}

/// Computes a seeded 128-bit hash and writes 16 little-endian bytes to `out`.
///
/// # Safety
///
/// `data` must be readable for `len` bytes when non-null, and `out` must be writable for 16 bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash128_out_seed(
  data: *const u8,
  len: usize,
  seed: u64,
  out: *mut u8,
) {
  // SAFETY: forwarded from caller contract guaranteeing 16 writable bytes at out.
  unsafe { write_digest(data, len, out, |d| hash128(d, seed).to_le_bytes()) };
}

/// Computes a 256-bit hash and writes 32 little-endian bytes to `out`.
///
/// # Safety
///
/// `data` must be readable for `len` bytes when non-null, and `out` must be writable for 32 bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash256(data: *const u8, len: usize, out: *mut u8) {
  // SAFETY: forwarded from caller contract guaranteeing 32 writable bytes at out.
  unsafe { write_digest(data, len, out, root_hash256) };
}

/// Computes a seeded 256-bit hash and writes 32 little-endian bytes to `out`.
///
/// # Safety
///
/// `data` must be readable for `len` bytes when non-null, and `out` must be writable for 32 bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash256_seed(data: *const u8, len: usize, seed: u64, out: *mut u8) {
  // SAFETY: forwarded from caller contract guaranteeing 32 writable bytes at out.
  unsafe { write_digest(data, len, out, |d| hash256(d, seed)) };
}

/// Fills `out[..out_len]` with an arbitrary-length XOF digest of `data[..len]`.
///
/// # Safety
///
/// `data` must be readable for `len` bytes when non-null, and `out` writable for `out_len` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash_xof(data: *const u8, len: usize, out: *mut u8, out_len: usize) {
  // SAFETY: forwarded from caller contract guaranteeing out_len writable bytes at out.
  unsafe { with_io_slices(data, len, out, out_len, root_hash_xof) };
}

/// Fills `out[..out_len]` with a seeded arbitrary-length XOF digest of `data[..len]`.
///
/// # Safety
///
/// `data` must be readable for `len` bytes when non-null, and `out` writable for `out_len` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_hash_xof_seed(
  data: *const u8,
  len: usize,
  seed: u64,
  out: *mut u8,
  out_len: usize,
) {
  // SAFETY: forwarded from caller contract guaranteeing out_len writable bytes at out.
  unsafe { with_io_slices(data, len, out, out_len, |d, dst| hash_xof(d, seed, dst)) };
}

/// XORs `buf[..buf_len]` in place with the seekable keystream derived from `key` at `offset`.
///
/// # Safety
///
/// `key` must be readable for `key_len` bytes when non-null, and `buf` writable for `buf_len` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_xor_stream(
  key: *const u8,
  key_len: usize,
  offset: u64,
  buf: *mut u8,
  buf_len: usize,
) {
  // SAFETY: forwarded from caller contract guaranteeing buf_len writable bytes at buf.
  unsafe {
    with_io_slices(key, key_len, buf, buf_len, |k, dst| {
      Stream::new(k).seek(offset).xor_keystream(dst);
    });
  }
}

/// XORs `buf[..buf_len]` in place with the seekable keystream derived from `(key, seed)` at `offset`.
///
/// # Safety
///
/// `key` must be readable for `key_len` bytes when non-null, and `buf` writable for `buf_len` bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ihash_xor_stream_seed(
  key: *const u8,
  key_len: usize,
  seed: u64,
  offset: u64,
  buf: *mut u8,
  buf_len: usize,
) {
  // SAFETY: forwarded from caller contract guaranteeing buf_len writable bytes at buf.
  unsafe {
    with_io_slices(key, key_len, buf, buf_len, |k, dst| {
      stream(k, seed).seek(offset).xor_keystream(dst);
    });
  }
}