pub(crate) fn crc32c(data: &[u8]) -> u32 {
crc32c_append(0, data)
}
pub(crate) fn crc32c_append(crc: u32, data: &[u8]) -> u32 {
match hw::append(crc, data) {
Some(crc) => crc,
None => crc32c::crc32c_append(crc, data),
}
}
#[cfg_attr(
any(miri, not(any(target_arch = "aarch64", target_arch = "x86_64"))),
allow(dead_code)
)]
const LANES: [usize; 2] = [256, 64];
#[cfg_attr(
any(miri, not(any(target_arch = "aarch64", target_arch = "x86_64"))),
allow(dead_code)
)]
type ShiftTables = [[[u32; 256]; 4]; 2];
#[cfg_attr(
any(miri, not(any(target_arch = "aarch64", target_arch = "x86_64"))),
allow(dead_code)
)]
#[inline]
fn shift(table: &[[u32; 256]; 4], crc: u32) -> u32 {
table[0][(crc & 0xff) as usize]
^ table[1][((crc >> 8) & 0xff) as usize]
^ table[2][((crc >> 16) & 0xff) as usize]
^ table[3][(crc >> 24) as usize]
}
#[cfg_attr(
any(miri, not(any(target_arch = "aarch64", target_arch = "x86_64"))),
allow(dead_code)
)]
#[inline]
fn word(bytes: &[u8]) -> u64 {
let mut w = [0u8; 8];
w.copy_from_slice(bytes);
u64::from_le_bytes(w)
}
#[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), not(miri)))]
macro_rules! three_lane_crc {
($feature:literal) => {
fn tables() -> &'static super::ShiftTables {
static TABLES: std::sync::OnceLock<Box<super::ShiftTables>> =
std::sync::OnceLock::new();
TABLES.get_or_init(|| unsafe { build_tables() })
}
#[target_feature(enable = $feature)]
#[allow(unused_unsafe)]
unsafe fn build_tables() -> Box<super::ShiftTables> {
let mut tables = Box::new([[[0u32; 256]; 4]; 2]);
for (table, lane) in tables.iter_mut().zip(super::LANES) {
for (j, row) in table.iter_mut().enumerate() {
for (b, entry) in row.iter_mut().enumerate() {
let mut crc = (b as u32) << (8 * j);
for _ in 0..lane / 8 {
crc = unsafe { step(crc, 0) };
}
*entry = crc;
}
}
}
tables
}
#[target_feature(enable = $feature)]
#[allow(unused_unsafe)]
unsafe fn update(
mut crc: u32,
mut data: &[u8],
tables: Option<&super::ShiftTables>,
) -> u32 {
for (table, lane) in tables.into_iter().flatten().zip(super::LANES) {
let mut blocks = data.chunks_exact(3 * lane);
for block in &mut blocks {
let (a, rest) = block.split_at(lane);
let (b, c) = rest.split_at(lane);
let (mut c0, mut c1, mut c2) = (crc, 0u32, 0u32);
for ((x, y), z) in a
.chunks_exact(8)
.zip(b.chunks_exact(8))
.zip(c.chunks_exact(8))
{
unsafe {
c0 = step(c0, super::word(x));
c1 = step(c1, super::word(y));
c2 = step(c2, super::word(z));
}
}
crc = super::shift(table, super::shift(table, c0) ^ c1) ^ c2;
}
data = blocks.remainder();
}
let mut words = data.chunks_exact(8);
for w in &mut words {
crc = unsafe { step(crc, super::word(w)) };
}
for &byte in words.remainder() {
crc = unsafe { step_byte(crc, byte) };
}
crc
}
};
}
#[cfg(all(target_arch = "aarch64", not(miri)))]
mod hw {
use std::arch::aarch64::{__crc32cb, __crc32cd};
three_lane_crc!("crc");
pub(super) fn append(crc: u32, data: &[u8]) -> Option<u32> {
if !std::arch::is_aarch64_feature_detected!("crc") {
return None;
}
let tables = (data.len() >= 3 * super::LANES[1]).then(tables);
Some(!unsafe { update(!crc, data, tables) })
}
#[target_feature(enable = "crc")]
#[inline]
#[allow(unused_unsafe)]
unsafe fn step(crc: u32, word: u64) -> u32 {
unsafe { __crc32cd(crc, word) }
}
#[target_feature(enable = "crc")]
#[inline]
#[allow(unused_unsafe)]
unsafe fn step_byte(crc: u32, byte: u8) -> u32 {
unsafe { __crc32cb(crc, byte) }
}
}
#[cfg(all(target_arch = "x86_64", not(miri)))]
mod hw {
use std::arch::x86_64::{_mm_crc32_u8, _mm_crc32_u64};
three_lane_crc!("sse4.2");
pub(super) fn append(crc: u32, data: &[u8]) -> Option<u32> {
if !std::arch::is_x86_feature_detected!("sse4.2") {
return None;
}
let tables = (data.len() >= 3 * super::LANES[1]).then(tables);
Some(!unsafe { update(!crc, data, tables) })
}
#[target_feature(enable = "sse4.2")]
#[inline]
#[allow(unused_unsafe)]
unsafe fn step(crc: u32, word: u64) -> u32 {
unsafe { _mm_crc32_u64(u64::from(crc), word) as u32 }
}
#[target_feature(enable = "sse4.2")]
#[inline]
#[allow(unused_unsafe)]
unsafe fn step_byte(crc: u32, byte: u8) -> u32 {
unsafe { _mm_crc32_u8(crc, byte) }
}
}
#[cfg(any(miri, not(any(target_arch = "aarch64", target_arch = "x86_64"))))]
mod hw {
pub(super) fn append(_crc: u32, _data: &[u8]) -> Option<u32> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn check_value() {
assert_eq!(crc32c(b"123456789"), 0xE306_9283);
assert_eq!(crc32c(&[0; 32]), 0x8A91_36AA);
assert_eq!(crc32c(&[0xff; 32]), 0x62A8_AB43);
assert_eq!(crc32c(b""), 0);
}
#[test]
fn every_length_through_the_lane_sizes_matches_the_crate() {
const MAX: usize = 2 * 3 * (256 + 64) + 64;
let mut x = 0x9e37_79b9_7f4a_7c15u64;
let data: Vec<u8> = (0..MAX + 7)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x as u8
})
.collect();
let step = if cfg!(miri) { 61 } else { 1 };
for len in (0..=MAX).step_by(step) {
for start in 0..8 {
let slice = &data[start..start + len];
assert_eq!(
crc32c(slice),
crc32c::crc32c(slice),
"len {len} start {start}"
);
}
}
}
#[cfg(not(miri))]
#[test]
fn hardware_path_is_used_when_available() {
let used = hw::append(0, b"x").is_some();
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
assert!(used);
#[cfg(target_arch = "x86_64")]
assert_eq!(used, std::arch::is_x86_feature_detected!("sse4.2"));
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
assert_eq!(used, std::arch::is_aarch64_feature_detected!("crc"));
let _ = used;
}
fn property_config() -> ProptestConfig {
let mut config = ProptestConfig::default();
if cfg!(miri) {
config.cases = 2;
config.failure_persistence = None;
}
config
}
proptest! {
#![proptest_config(property_config())]
#[test]
fn matches_the_crate(init in any::<u32>(), data in proptest::collection::vec(any::<u8>(), 0..5000)) {
prop_assert_eq!(crc32c_append(init, &data), crc32c::crc32c_append(init, &data));
}
#[test]
fn appending_in_pieces_matches_one_pass(data in proptest::collection::vec(any::<u8>(), 0..5000), cut in any::<usize>()) {
let cut = cut % (data.len() + 1);
prop_assert_eq!(crc32c_append(crc32c(&data[..cut]), &data[cut..]), crc32c(&data));
}
}
}