Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Created November 6, 2024 20:32
Show Gist options
  • Save MikuroXina/17a9d0253b7fe32c1873b9665e952010 to your computer and use it in GitHub Desktop.
Save MikuroXina/17a9d0253b7fe32c1873b9665e952010 to your computer and use it in GitHub Desktop.
Example implementation of CRC-32 with Rust.
#[derive(Debug, Clone)]
pub struct Crc32 {
table: [u32; 256],
}
impl Crc32 {
pub const SOURCE: u32 = 0xedb8_8320;
pub fn new() -> Self {
let mut table = [0u32; 256];
for i in 0..256 {
let mut c = i;
for _ in 0..8 {
if c % 2 != 0 {
c = Self::SOURCE ^ (c >> 1);
} else {
c >>= 1;
}
}
table[i as usize] = c;
}
Self { table }
}
pub fn digest(&self, bytes: &[u8]) -> u32 {
let mut c = 0xffff_ffff;
for &byte in bytes {
c = self.table[((c ^ byte as u32) & 0xff) as usize] ^ (c >> 8);
}
c ^ 0xffff_ffff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment