#![cfg_attr(feature = "kernel", no_std)]
#![warn(missing_docs)]
#[cfg(feature = "kernel")]
extern crate alloc;
#[cfg(feature = "kernel")]
use alloc::vec::Vec;
#[cfg(not(feature = "kernel"))]
use std::vec::Vec;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
pub mod ct;
pub mod hex;
mod keccak;
#[cfg(not(feature = "kernel"))]
pub mod io;
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
mod simd_avx512;
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
mod simd_parallel;
pub use hex::Sha3Digest;
#[cfg(any(not(target_arch = "x86_64"), feature = "kernel"))]
use keccak::keccak_f1600;
#[cfg(test)]
static AVX512_PATH_CALLS: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
#[cfg(test)]
static SCALAR_PATH_CALLS: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
#[inline]
fn permute(state: &mut [u64; 25], use_avx512: bool) {
#[cfg(test)]
{
use core::sync::atomic::Ordering;
if use_avx512 && is_x86_feature_detected!("avx512f") {
AVX512_PATH_CALLS.fetch_add(1, Ordering::Relaxed);
} else {
SCALAR_PATH_CALLS.fetch_add(1, Ordering::Relaxed);
}
}
simd_avx512::keccak_f1600_dispatch(state, use_avx512);
}
#[cfg(any(not(target_arch = "x86_64"), feature = "kernel"))]
#[inline]
fn permute(state: &mut [u64; 25], _use_avx512: bool) {
#[cfg(test)]
{
use core::sync::atomic::Ordering;
SCALAR_PATH_CALLS.fetch_add(1, Ordering::Relaxed);
}
keccak_f1600(state);
}
const SHA3_512_RATE: usize = 72;
const SHA3_DOMAIN_BYTE: u8 = 0x06;
pub struct Sha3_512Kernel {
state: Sha3_512State,
features: SimdFeatures,
config: PerformanceConfig,
}
#[derive(Debug, Clone, Copy)]
pub struct SimdFeatures {
pub avx512_available: bool,
pub avx2_available: bool,
pub sse42_available: bool,
pub bmi2_available: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct PerformanceConfig {
pub use_avx512: bool,
pub use_avx2: bool,
pub prefetch_data: bool,
pub parallel_chunks: bool,
pub chunk_size: usize,
}
impl Default for PerformanceConfig {
fn default() -> Self {
Self {
use_avx512: false,
use_avx2: true,
prefetch_data: true,
parallel_chunks: true,
chunk_size: 1024,
}
}
}
#[repr(C, align(64))]
#[derive(Debug, Clone)]
pub struct Sha3_512State {
pub state: [u64; 25],
pub pos: usize,
pub rate: usize,
pub buffer: [u8; 200],
}
#[cfg(feature = "serde")]
mod state_serde {
use super::Sha3_512State;
use core::fmt;
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "kernel")]
use alloc::vec::Vec;
#[cfg(not(feature = "kernel"))]
use std::vec::Vec;
impl Serialize for Sha3_512State {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut s = serializer.serialize_struct("Sha3_512State", 4)?;
s.serialize_field("state", &self.state.as_slice())?;
s.serialize_field("pos", &self.pos)?;
s.serialize_field("rate", &self.rate)?;
s.serialize_field("buffer", &self.buffer.as_slice())?;
s.end()
}
}
impl<'de> Deserialize<'de> for Sha3_512State {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
State,
Pos,
Rate,
Buffer,
}
struct StateVisitor;
impl<'de> Visitor<'de> for StateVisitor {
type Value = Sha3_512State;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("struct Sha3_512State")
}
fn visit_map<M: MapAccess<'de>>(
self,
mut map: M,
) -> Result<Sha3_512State, M::Error> {
let mut state_lanes: Option<Vec<u64>> = None;
let mut pos: Option<usize> = None;
let mut rate: Option<usize> = None;
let mut buffer_vec: Option<Vec<u8>> = None;
while let Some(key) = map.next_key::<Field>()? {
match key {
Field::State => {
state_lanes = Some(map.next_value::<Vec<u64>>()?);
}
Field::Pos => {
pos = Some(map.next_value::<usize>()?);
}
Field::Rate => {
rate = Some(map.next_value::<usize>()?);
}
Field::Buffer => {
buffer_vec = Some(map.next_value::<Vec<u8>>()?);
}
}
}
let sv = state_lanes.ok_or_else(|| de::Error::missing_field("state"))?;
let pv = pos.ok_or_else(|| de::Error::missing_field("pos"))?;
let rv = rate.ok_or_else(|| de::Error::missing_field("rate"))?;
let bv = buffer_vec.ok_or_else(|| de::Error::missing_field("buffer"))?;
let mut state = [0u64; 25];
if sv.len() != 25 {
return Err(de::Error::invalid_length(sv.len(), &"25"));
}
state.copy_from_slice(&sv);
let mut buffer = [0u8; 200];
if bv.len() != 200 {
return Err(de::Error::invalid_length(bv.len(), &"200"));
}
buffer.copy_from_slice(&bv);
Ok(Sha3_512State {
state,
pos: pv,
rate: rv,
buffer,
})
}
}
deserializer.deserialize_struct(
"Sha3_512State",
&["state", "pos", "rate", "buffer"],
StateVisitor,
)
}
}
}
pub type Sha3_512Hash = [u8; 64];
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MemoryRegion {
pub base_address: u64,
pub size: usize,
pub is_readable: bool,
pub is_writable: bool,
pub is_executable: bool,
}
pub const MAX_HASH_SIZE: usize = 256 * 1024 * 1024;
pub const DEFAULT_CHUNK_SIZE: usize = 1024;
impl Sha3_512Kernel {
pub fn new() -> Self {
Self::with_config(PerformanceConfig::default())
}
pub fn with_config(config: PerformanceConfig) -> Self {
let features = Self::detect_simd_features();
Self {
state: Sha3_512State::new(),
features,
config,
}
}
pub fn hash(&mut self, data: &[u8]) -> Sha3_512Hash {
self.state.reset();
self.state.absorb(data, self.config.use_avx512);
self.state.finalize(self.config.use_avx512)
}
pub fn hash_memory_region(&mut self, base_address: u64, size: usize) -> Sha3_512Hash {
if size == 0 || size > MAX_HASH_SIZE {
return [0u8; 64];
}
let memory_slice = unsafe { core::slice::from_raw_parts(base_address as *const u8, size) };
self.hash(memory_slice)
}
pub fn hash_memory_regions(&mut self, regions: &[MemoryRegion]) -> Vec<Sha3_512Hash> {
regions
.iter()
.filter(|r| r.is_readable && r.size > 0 && r.size <= MAX_HASH_SIZE)
.map(|region| self.hash_memory_region(region.base_address, region.size))
.collect()
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
pub fn hash_many(&self, messages: &[&[u8]]) -> Vec<Sha3_512Hash> {
let width = if self.config.use_avx512 && is_x86_feature_detected!("avx512f") {
8
} else if self.config.use_avx2 && is_x86_feature_detected!("avx2") {
4
} else {
1
};
let mut results = Vec::with_capacity(messages.len());
for chunk in messages.chunks(width.max(1)) {
match width {
8 => results.extend(hash_batch_x8(chunk)),
4 => results.extend(hash_batch_x4(chunk)),
_ => {
for m in chunk {
results.push(Sha3_512Kernel::new().hash(m));
}
}
}
}
results
}
#[cfg(all(target_arch = "x86_64", not(feature = "kernel")))]
fn detect_simd_features() -> SimdFeatures {
SimdFeatures {
avx512_available: is_x86_feature_detected!("avx512f")
&& is_x86_feature_detected!("avx512bw")
&& is_x86_feature_detected!("avx512dq"),
avx2_available: is_x86_feature_detected!("avx2") && is_x86_feature_detected!("bmi2"),
sse42_available: is_x86_feature_detected!("sse4.2"),
bmi2_available: is_x86_feature_detected!("bmi2"),
}
}
#[cfg(any(not(target_arch = "x86_64"), feature = "kernel"))]
fn detect_simd_features() -> SimdFeatures {
SimdFeatures {
avx512_available: false,
avx2_available: false,
sse42_available: false,
bmi2_available: false,
}
}
pub fn simd_features(&self) -> SimdFeatures {
self.features
}
pub fn config(&self) -> PerformanceConfig {
self.config
}
pub fn update_config(&mut self, config: PerformanceConfig) {
self.config = config;
}
pub fn hash_digest(&mut self, data: &[u8]) -> Sha3Digest {
Sha3Digest::new(self.hash(data))
}
pub fn finalize(&mut self) -> Sha3_512Hash {
self.state.finalize(self.config.use_avx512)
}
pub fn finalize_digest(&mut self) -> Sha3Digest {
Sha3Digest::new(self.finalize())
}
pub fn reset(&mut self) {
self.state.reset();
}
pub fn update(&mut self, data: &[u8]) {
self.state.absorb(data, self.config.use_avx512);
}
}
impl Default for Sha3_512Kernel {
fn default() -> Self {
Self::new()
}
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn pad_message(msg: &[u8]) -> Vec<u8> {
let rate = SHA3_512_RATE;
let full_blocks = msg.len() / rate;
let total_len = (full_blocks + 1) * rate;
let mut buf = vec![0u8; total_len];
buf[..msg.len()].copy_from_slice(msg);
buf[msg.len()] = SHA3_DOMAIN_BYTE;
let last = total_len - 1;
buf[last] |= 0x80;
buf
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn xor_block_into(state: &mut [u64; 25], block: &[u8]) {
let words = SHA3_512_RATE / 8;
for (i, lane) in state.iter_mut().enumerate().take(words) {
let off = i * 8;
let word = u64::from_le_bytes([
block[off],
block[off + 1],
block[off + 2],
block[off + 3],
block[off + 4],
block[off + 5],
block[off + 6],
block[off + 7],
]);
*lane ^= word;
}
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn squeeze(state: &[u64; 25]) -> Sha3_512Hash {
let mut hash = [0u8; 64];
for i in 0..8 {
hash[i * 8..(i + 1) * 8].copy_from_slice(&state[i].to_le_bytes());
}
hash
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn hash_batch_x8(chunk: &[&[u8]]) -> Vec<Sha3_512Hash> {
debug_assert!(chunk.len() <= 8);
let padded: Vec<Vec<u8>> = chunk.iter().map(|m| pad_message(m)).collect();
let num_blocks: Vec<usize> = padded.iter().map(|p| p.len() / SHA3_512_RATE).collect();
let max_blocks = num_blocks.iter().copied().max().unwrap_or(0);
let mut states = [[0u64; 25]; 8];
let mut results = vec![[0u8; 64]; chunk.len()];
for block_idx in 0..max_blocks {
for i in 0..chunk.len() {
if block_idx < num_blocks[i] {
let start = block_idx * SHA3_512_RATE;
xor_block_into(&mut states[i], &padded[i][start..start + SHA3_512_RATE]);
}
}
unsafe { simd_parallel::keccak_f1600_x8_avx512(&mut states) };
for i in 0..chunk.len() {
if block_idx == num_blocks[i] - 1 {
results[i] = squeeze(&states[i]);
}
}
}
results
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn hash_batch_x4(chunk: &[&[u8]]) -> Vec<Sha3_512Hash> {
debug_assert!(chunk.len() <= 4);
let padded: Vec<Vec<u8>> = chunk.iter().map(|m| pad_message(m)).collect();
let num_blocks: Vec<usize> = padded.iter().map(|p| p.len() / SHA3_512_RATE).collect();
let max_blocks = num_blocks.iter().copied().max().unwrap_or(0);
let mut states = [[0u64; 25]; 4];
let mut results = vec![[0u8; 64]; chunk.len()];
for block_idx in 0..max_blocks {
for i in 0..chunk.len() {
if block_idx < num_blocks[i] {
let start = block_idx * SHA3_512_RATE;
xor_block_into(&mut states[i], &padded[i][start..start + SHA3_512_RATE]);
}
}
unsafe { simd_parallel::keccak_f1600_x4_avx2(&mut states) };
for i in 0..chunk.len() {
if block_idx == num_blocks[i] - 1 {
results[i] = squeeze(&states[i]);
}
}
}
results
}
impl Default for Sha3_512State {
fn default() -> Self {
Self {
state: [0u64; 25],
pos: 0,
rate: SHA3_512_RATE,
buffer: [0u8; 200],
}
}
}
impl Sha3_512State {
pub fn new() -> Self {
Self::default()
}
pub fn reset(&mut self) {
self.state = [0u64; 25];
self.pos = 0;
self.buffer = [0u8; 200];
}
fn absorb(&mut self, data: &[u8], use_avx512: bool) {
let mut offset = 0;
let len = data.len();
if self.pos > 0 {
let remaining = self.rate - self.pos;
let to_copy = core::cmp::min(remaining, len);
self.buffer[self.pos..self.pos + to_copy].copy_from_slice(&data[..to_copy]);
self.pos += to_copy;
offset += to_copy;
if self.pos == self.rate {
self.xor_block_into_state();
permute(&mut self.state, use_avx512);
self.pos = 0;
}
}
while offset + self.rate <= len {
let block = &data[offset..offset + self.rate];
let words = self.rate / 8; for i in 0..words {
let off = i * 8;
let word = u64::from_le_bytes([
block[off],
block[off + 1],
block[off + 2],
block[off + 3],
block[off + 4],
block[off + 5],
block[off + 6],
block[off + 7],
]);
self.state[i] ^= word;
}
permute(&mut self.state, use_avx512);
offset += self.rate;
}
let tail = len - offset;
if tail > 0 {
self.buffer[..tail].copy_from_slice(&data[offset..]);
self.pos = tail;
}
}
fn finalize(&mut self, use_avx512: bool) -> Sha3_512Hash {
for i in self.pos..self.rate {
self.buffer[i] = 0;
}
self.buffer[self.pos] = SHA3_DOMAIN_BYTE;
self.buffer[self.rate - 1] |= 0x80;
self.xor_block_into_state();
permute(&mut self.state, use_avx512);
let mut hash = [0u8; 64];
for i in 0..8 {
hash[i * 8..(i + 1) * 8].copy_from_slice(&self.state[i].to_le_bytes());
}
hash
}
#[inline]
fn xor_block_into_state(&mut self) {
let words = self.rate / 8; for i in 0..words {
let off = i * 8;
let word = u64::from_le_bytes([
self.buffer[off],
self.buffer[off + 1],
self.buffer[off + 2],
self.buffer[off + 3],
self.buffer[off + 4],
self.buffer[off + 5],
self.buffer[off + 6],
self.buffer[off + 7],
]);
self.state[i] ^= word;
}
}
}
pub mod kernel_safe {
#[cfg(target_arch = "x86_64")]
pub unsafe fn save_processor_state() -> ProcessorState {
ProcessorState::save()
}
#[cfg(target_arch = "x86_64")]
pub unsafe fn restore_processor_state(state: ProcessorState) {
state.restore();
}
#[cfg(target_arch = "x86_64")]
#[repr(C)]
pub struct ProcessorState {
simd_registers: [u8; 512],
control_registers: [u64; 8],
}
#[cfg(target_arch = "x86_64")]
impl ProcessorState {
pub unsafe fn save() -> Self {
Self {
simd_registers: [0u8; 512],
control_registers: [0u64; 8],
}
}
pub unsafe fn restore(self) {
}
}
#[cfg(not(target_arch = "x86_64"))]
pub struct ProcessorState;
#[cfg(not(target_arch = "x86_64"))]
pub unsafe fn save_processor_state() -> ProcessorState {
ProcessorState
}
#[cfg(not(target_arch = "x86_64"))]
pub unsafe fn restore_processor_state(_state: ProcessorState) {
}
}
#[cfg(not(feature = "kernel"))]
pub mod performance {
use super::*;
pub fn benchmark_hasher<F>(hasher_fn: F, data: &[u8]) -> BenchmarkResult
where
F: Fn(&[u8]) -> Sha3_512Hash,
{
let start = std::time::Instant::now();
let hash = hasher_fn(data);
let duration = start.elapsed();
BenchmarkResult {
hash,
duration,
throughput: (data.len() as f64) / duration.as_secs_f64(),
}
}
#[derive(Debug)]
pub struct BenchmarkResult {
pub hash: Sha3_512Hash,
pub duration: std::time::Duration,
pub throughput: f64,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bytes_to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
#[test]
fn test_nist_sha3_512_empty() {
let expected = "a69f73cca23a9ac5c8b567dc185a756e\
97c982164fe25859e0d1dcc1475c80a6\
15b2123af1f5f94c11e3e9402c3ac558\
f500199d95b6d3e301758586281dcd26";
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash(b"");
assert_eq!(
bytes_to_hex(&hash),
expected,
"SHA3-512('') must match NIST CAVP vector"
);
}
#[test]
fn test_nist_sha3_512_one_byte_cc() {
let expected = "3939fcc8b57b63612542da31a834e5dc\
c36e2ee0f652ac72e02624fa2e5adeec\
c7dd6bb3580224b4d6138706fc6e8059\
7b528051230b00621cc2b22999eaa205";
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash(&[0xCC]);
assert_eq!(
bytes_to_hex(&hash),
expected,
"SHA3-512(0xCC) must match NIST CAVP vector"
);
}
#[test]
fn test_nist_sha3_512_two_bytes() {
let expected = "aa092865a40694d91754dbc767b5202c\
546e226877147a95cb8b4c8f8709fe8c\
d6905256b089da37896ea5ca19d2cd9a\
b94c7192fc39f7cd4d598975a3013c69";
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash(&[0x41, 0xFB]);
assert_eq!(
bytes_to_hex(&hash),
expected,
"SHA3-512(0x41FB) must match NIST CAVP vector"
);
}
#[test]
fn test_nist_sha3_512_200_bytes_a3() {
let expected = "e76dfad22084a8b1467fcf2ffa58361b\
ec7628edf5f3fdc0e4805dc48caeeca8\
1b7c13c30adf52a3659584739a2df46b\
e589c51ca1a4a8416df6545a1ce8ba00";
let input = vec![0xA3u8; 200];
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash(&input);
assert_eq!(
bytes_to_hex(&hash),
expected,
"SHA3-512(0xA3 × 200) must match NIST CAVP vector"
);
}
#[test]
fn test_incremental_matches_oneshot() {
let data = b"The quick brown fox jumps over the lazy dog";
let mut oneshot = Sha3_512Kernel::new();
let expected = oneshot.hash(data);
let mut incremental = Sha3_512Kernel::new();
incremental.reset();
incremental.update(&data[..10]);
incremental.update(&data[10..30]);
incremental.update(&data[30..]);
let result = incremental.finalize();
assert_eq!(result, expected, "Incremental must match oneshot");
}
#[test]
fn test_incremental_byte_at_a_time() {
let data = b"abcdefghijklmnopqrstuvwxyz";
let mut oneshot = Sha3_512Kernel::new();
let expected = oneshot.hash(data);
let mut inc = Sha3_512Kernel::new();
inc.reset();
for &b in data.iter() {
inc.update(&[b]);
}
let result = inc.finalize();
assert_eq!(result, expected, "Byte-at-a-time must match oneshot");
}
#[test]
fn test_deterministic() {
let mut hasher = Sha3_512Kernel::new();
let data = b"Bunker SHA3-512 determinism test";
let h1 = hasher.hash(data);
let h2 = hasher.hash(data);
assert_eq!(h1, h2, "Hash must be deterministic");
}
#[test]
fn test_avalanche() {
let mut hasher = Sha3_512Kernel::new();
let h1 = hasher.hash(b"input_a");
let h2 = hasher.hash(b"input_b");
assert_ne!(h1, h2, "Different inputs must avalanche");
}
#[test]
fn test_empty_not_zero() {
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash(b"");
assert_ne!(hash, [0u8; 64], "SHA3-512('') must not be all-zero");
}
#[test]
fn test_exact_rate_block() {
let data = vec![0x42u8; 72];
let mut hasher = Sha3_512Kernel::new();
let h1 = hasher.hash(&data);
let h2 = hasher.hash(&data);
assert_eq!(h1, h2);
assert_ne!(h1, [0u8; 64]);
}
#[test]
fn test_rate_plus_one() {
let data_72 = vec![0x42u8; 72];
let data_73 = vec![0x42u8; 73];
let mut hasher = Sha3_512Kernel::new();
let h72 = hasher.hash(&data_72);
let h73 = hasher.hash(&data_73);
assert_ne!(h72, h73, "72 vs 73 bytes must differ");
}
#[test]
fn test_large_payload() {
let data = vec![0u8; 1024 * 1024];
let mut hasher = Sha3_512Kernel::new();
let h1 = hasher.hash(&data);
let h2 = hasher.hash(&data);
assert_eq!(h1, h2);
assert_ne!(h1, [0u8; 64]);
}
#[test]
fn test_simd_detection() {
let hasher = Sha3_512Kernel::new();
let features = hasher.simd_features();
#[cfg(target_arch = "x86_64")]
{
assert!(
features.sse42_available || features.avx2_available || features.avx512_available,
"At least one SIMD tier must be detected on x86_64"
);
}
}
#[test]
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn hash_dispatches_to_avx512_path_when_configured_and_available() {
if !is_x86_feature_detected!("avx512f") {
eprintln!("skipping: no avx512f on this host");
return;
}
AVX512_PATH_CALLS.store(0, core::sync::atomic::Ordering::Relaxed);
let mut hasher = Sha3_512Kernel::with_config(PerformanceConfig {
use_avx512: true,
..PerformanceConfig::default()
});
let vector_digest = hasher.hash(b"the quick brown fox jumps over the lazy dog");
assert!(
AVX512_PATH_CALLS.load(core::sync::atomic::Ordering::Relaxed) > 0,
"hash() with use_avx512: true must actually invoke the AVX-512 \
permutation path on hardware that supports it, not just store \
the flag"
);
let mut scalar_hasher = Sha3_512Kernel::with_config(PerformanceConfig {
use_avx512: false,
..PerformanceConfig::default()
});
let scalar_digest = scalar_hasher.hash(b"the quick brown fox jumps over the lazy dog");
assert_eq!(
vector_digest, scalar_digest,
"AVX-512-dispatched hash() must match scalar-dispatched hash() bit for bit"
);
}
#[test]
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn hash_dispatches_to_scalar_path_when_use_avx512_is_false() {
SCALAR_PATH_CALLS.store(0, core::sync::atomic::Ordering::Relaxed);
let mut hasher = Sha3_512Kernel::with_config(PerformanceConfig {
use_avx512: false,
..PerformanceConfig::default()
});
hasher.hash(b"some data");
assert!(
SCALAR_PATH_CALLS.load(core::sync::atomic::Ordering::Relaxed) > 0,
"hash() with use_avx512: false must take the scalar path"
);
}
#[test]
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
fn incremental_update_also_uses_configured_dispatch() {
if !is_x86_feature_detected!("avx512f") {
eprintln!("skipping: no avx512f on this host");
return;
}
AVX512_PATH_CALLS.store(0, core::sync::atomic::Ordering::Relaxed);
let mut hasher = Sha3_512Kernel::with_config(PerformanceConfig {
use_avx512: true,
..PerformanceConfig::default()
});
let data = vec![0xABu8; 72 * 5 + 13]; hasher.update(&data[..72 * 3]);
hasher.update(&data[72 * 3..]);
let vector_digest = hasher.finalize_digest();
let mut scalar_hasher = Sha3_512Kernel::with_config(PerformanceConfig {
use_avx512: false,
..PerformanceConfig::default()
});
let scalar_digest = scalar_hasher.hash_digest(&data);
assert!(
AVX512_PATH_CALLS.load(core::sync::atomic::Ordering::Relaxed) >= 5,
"expected at least 5 AVX-512 permutation calls (one per full \
rate-block plus finalize), got {}",
AVX512_PATH_CALLS.load(core::sync::atomic::Ordering::Relaxed)
);
assert_eq!(vector_digest, scalar_digest);
}
#[test]
fn test_memory_hashing() {
let mut hasher = Sha3_512Kernel::new();
let data = vec![0u8; 1024];
let h1 = hasher.hash(&data);
let h2 = hasher.hash_memory_region(data.as_ptr() as u64, data.len());
assert_eq!(h1, h2, "Memory region hash must match slice hash");
}
#[test]
fn test_memory_hashing_zero_size() {
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash_memory_region(0x1000, 0);
assert_eq!(hash, [0u8; 64], "Zero-size region must return zero hash");
}
#[test]
fn test_memory_hashing_oversized() {
let mut hasher = Sha3_512Kernel::new();
let hash = hasher.hash_memory_region(0x1000, MAX_HASH_SIZE + 1);
assert_eq!(hash, [0u8; 64], "Oversized region must return zero hash");
}
#[test]
fn test_cross_validate_vs_sha3_crate() {
use sha3::{Digest, Sha3_512 as RefSha3_512};
let test_lengths: &[usize] = &[
0, 1, 2, 31, 32, 63, 64, 71, 72, 73, 100, 143, 144, 145, 200, 255, 256, 512, 1000, 4096,
];
let mut hasher = Sha3_512Kernel::new();
for &len in test_lengths {
let data: Vec<u8> = (0..len).map(|i| (i & 0xFF) as u8).collect();
let our_hash = hasher.hash(&data);
let mut ref_hasher = RefSha3_512::new();
ref_hasher.update(&data);
let ref_hash = ref_hasher.finalize();
assert_eq!(
&our_hash[..],
&ref_hash[..],
"Mismatch vs sha3 crate at len={}",
len
);
}
}
#[cfg(all(not(feature = "kernel"), target_arch = "x86_64"))]
mod hash_many_tests {
use super::*;
fn force(use_avx512: bool, use_avx2: bool) -> Sha3_512Kernel {
Sha3_512Kernel::with_config(PerformanceConfig {
use_avx512,
use_avx2,
..PerformanceConfig::default()
})
}
#[test]
fn hash_many_matches_hash_for_every_length_0_to_300() {
let lengths: Vec<usize> = (0..=300).collect();
let messages: Vec<Vec<u8>> = lengths
.iter()
.map(|&len| (0..len).map(|i| (i & 0xFF) as u8).collect())
.collect();
let refs: Vec<&[u8]> = messages.iter().map(|m| m.as_slice()).collect();
let mut scalar_hasher = Sha3_512Kernel::new();
let expected: Vec<Sha3_512Hash> =
messages.iter().map(|m| scalar_hasher.hash(m)).collect();
for (label, hasher) in [
("avx512", force(true, false)),
("avx2", force(false, true)),
("scalar", force(false, false)),
] {
if label == "avx512" && !is_x86_feature_detected!("avx512f") {
eprintln!("skipping hash_many({label}): no avx512f on this host");
continue;
}
if label == "avx2" && !is_x86_feature_detected!("avx2") {
eprintln!("skipping hash_many({label}): no avx2 on this host");
continue;
}
let results = hasher.hash_many(&refs);
assert_eq!(results.len(), messages.len());
for (i, &len) in lengths.iter().enumerate() {
assert_eq!(
results[i], expected[i],
"hash_many({label}) mismatch at message length {len}"
);
}
}
}
#[test]
fn hash_many_handles_mixed_lengths_in_one_batch() {
let batch: Vec<Vec<u8>> = vec![
vec![], vec![0xAB; 5], vec![0xCD; 72], vec![0xEF; 72 * 3 + 17], b"the quick brown fox".to_vec(), ];
let refs: Vec<&[u8]> = batch.iter().map(|m| m.as_slice()).collect();
let mut scalar_hasher = Sha3_512Kernel::new();
let expected: Vec<Sha3_512Hash> = batch.iter().map(|m| scalar_hasher.hash(m)).collect();
if is_x86_feature_detected!("avx512f") {
let results = force(true, false).hash_many(&refs);
assert_eq!(results, expected, "AVX-512x8 mixed-length batch mismatch");
}
if is_x86_feature_detected!("avx2") {
let results = force(false, true).hash_many(&refs);
assert_eq!(results, expected, "AVX2x4 mixed-length batch mismatch");
}
}
#[test]
fn hash_many_handles_batches_larger_than_simd_width() {
let batch: Vec<Vec<u8>> = (0..37)
.map(|i| (0..(i * 3 + 1)).map(|b| (b & 0xFF) as u8).collect())
.collect();
let refs: Vec<&[u8]> = batch.iter().map(|m| m.as_slice()).collect();
let mut scalar_hasher = Sha3_512Kernel::new();
let expected: Vec<Sha3_512Hash> = batch.iter().map(|m| scalar_hasher.hash(m)).collect();
let results = Sha3_512Kernel::new().hash_many(&refs);
assert_eq!(results, expected);
}
#[test]
fn hash_many_empty_input_returns_empty() {
let results = Sha3_512Kernel::new().hash_many(&[]);
assert!(results.is_empty());
}
}
}
#[cfg(feature = "benchmarks")]
#[allow(missing_docs)]
pub mod benchmarks {
use super::*;
#[cfg(feature = "kernel")]
use alloc::vec;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
#[cfg(not(feature = "kernel"))]
use std::vec;
fn bench_sha3_512(c: &mut Criterion) {
let mut hasher = Sha3_512Kernel::new();
let data = vec![0u8; 1024 * 1024];
c.bench_function("sha3_512_hash", |b| {
b.iter(|| black_box(hasher.hash(&data)))
});
}
criterion_group!(benches, bench_sha3_512);
criterion_main!(benches);
}