diff --git a/crates/hashing/src/crc32.rs b/crates/hashing/src/crc32.rs index db4a3935..cc040afe 100644 --- a/crates/hashing/src/crc32.rs +++ b/crates/hashing/src/crc32.rs @@ -10,6 +10,10 @@ //! This implementation is optimized for modern CPUs by using hardware acceleration //! when available. Current support includes only CRC for aarch64. +use boytacean_common::error::Error; + +use crate::hash::Hash; + #[cfg(all(feature = "simd", target_arch = "aarch64"))] use std::arch::is_aarch64_feature_detected; @@ -112,6 +116,17 @@ impl Crc32 { } } +impl Hash for Crc32 { + type Options = (); + + fn hash(data: &[u8], _options: &Self::Options) -> Result, Error> { + let mut crc32 = Crc32::new(); + crc32.update(data); + let result = crc32.finalize(); + Ok(result.to_le_bytes().to_vec()) + } +} + impl Default for Crc32 { fn default() -> Self { Self::new() @@ -126,7 +141,9 @@ pub fn crc32(data: &[u8]) -> u32 { #[cfg(test)] mod tests { - use super::crc32; + use crate::hash::Hash; + + use super::{crc32, Crc32}; #[test] fn test_crc32_empty() { @@ -151,4 +168,11 @@ mod tests { let data: Vec = vec![0xff; 1000]; assert_eq!(crc32(&data), 0xe0533230); } + + #[test] + fn test_crc32_hash() { + let data: Vec = vec![0xff; 1000]; + let result = Crc32::hash(&data, &()).unwrap(); + assert_eq!(result, [0x30, 0x32, 0x53, 0xe0]); + } } diff --git a/crates/hashing/src/crc32c.rs b/crates/hashing/src/crc32c.rs index 378b2a40..2f884290 100644 --- a/crates/hashing/src/crc32c.rs +++ b/crates/hashing/src/crc32c.rs @@ -10,6 +10,10 @@ //! This implementation is optimized for modern CPUs by using hardware acceleration //! when available. Current support includes SSE4.2 for x86_64 and CRC for aarch64. +use boytacean_common::error::Error; + +use crate::hash::Hash; + #[cfg(all(feature = "simd", target_arch = "x86_64"))] use std::arch::is_x86_feature_detected; @@ -152,6 +156,17 @@ impl Crc32C { } } +impl Hash for Crc32C { + type Options = (); + + fn hash(data: &[u8], _options: &Self::Options) -> Result, Error> { + let mut crc32c: Crc32C = Crc32C::new(); + crc32c.update(data); + let result = crc32c.finalize(); + Ok(result.to_le_bytes().to_vec()) + } +} + impl Default for Crc32C { fn default() -> Self { Self::new() @@ -166,7 +181,9 @@ pub fn crc32c(data: &[u8]) -> u32 { #[cfg(test)] mod tests { - use super::crc32c; + use crate::hash::Hash; + + use super::{crc32c, Crc32C}; #[test] fn test_crc32c_empty() { @@ -191,4 +208,11 @@ mod tests { let data: Vec = vec![0xff; 1000]; assert_eq!(crc32c(&data), 0x7b72068d); } + + #[test] + fn test_crc32c_hash() { + let data: Vec = vec![0xff; 1000]; + let result = Crc32C::hash(&data, &()).unwrap(); + assert_eq!(result, [0x8d, 0x06, 0x72, 0x7b]); + } }