feat: implement crc32 (cyclic redundancy check)

This commit is contained in:
leonhard committed 2026-10-23 13:04:02 +02:00
1 parent ac313d1a7d
commit b40a156b13
2 files changed
+40

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
use std::mem::{self, MaybeUninit};
pub struct Crc(u64);
pub struct Crc32Encoder {
crc_table: [Crc; 256],
}
impl Crc32Encoder {
pub fn new() -> Self {
// SAFETY: the values will be initialized in the correct order in the following for-loop
let mut crc_table: [MaybeUninit<Crc>; 256] = unsafe { MaybeUninit::uninit().assume_init() };
for n in 0u8..=255 {
let mut c: u64 = n.into();
for _ in 0..8 {
if c & 1 == 0 {
c = 0xedb88320 ^ (c >> 1);
} else {
c = c >> 1;
}
}
crc_table[n as usize] = MaybeUninit::new(Crc(c));
}
let crc_table = unsafe { mem::transmute(crc_table) };
Self { crc_table }
}
pub fn update(&self, crc: &Crc, mut buffer: impl Iterator<Item = u8>) -> Crc {
let mut c = crc.0 ^ 0xffffffff;
while let Some(n) = buffer.next() {
c = self.crc_table[((c ^ n as u64) & 0xff) as usize].0 ^ (c >> 8);
}
Crc(c ^ 0xffffffff)
}
pub fn encode(&self, buffer: impl Iterator<Item = u8>) -> Crc {
self.update(&Crc(0), buffer)
}
}
+1
View File
@@ -1,3 +1,4 @@
mod crc32;
mod header; mod header;
struct GzipFile { struct GzipFile {