40 lines
1.0 KiB
Rust
40 lines
1.0 KiB
Rust
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)
|
|
}
|
|
}
|