Skip to main content

ironwork_rt/module/
crc.rs

1//! CRC-32: the IEEE polynomial, reflected, initial and final XOR `0xFFFFFFFF` (load-module.md ยง3.3).
2
3const TABLE: [u32; 256] = table();
4
5const fn table() -> [u32; 256] {
6    let mut table = [0u32; 256];
7    let mut n = 0;
8    while n < 256 {
9        let mut c = n as u32;
10        let mut bit = 0;
11        while bit < 8 {
12            c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
13            bit += 1;
14        }
15        table[n] = c;
16        n += 1;
17    }
18    table
19}
20
21pub fn crc32(bytes: &[u8]) -> u32 {
22    extend(0, bytes)
23}
24
25/// The checksum of the bytes `crc` was computed over, followed by `bytes`.
26pub fn extend(crc: u32, bytes: &[u8]) -> u32 {
27    let mut c = !crc;
28    for &byte in bytes {
29        c = TABLE[usize::from(c as u8 ^ byte)] ^ (c >> 8);
30    }
31    !c
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn the_ieee_check_values() {
40        assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
41        assert_eq!(crc32(b""), 0);
42        assert_eq!(crc32(b"a"), 0xE8B7_BE43);
43        assert_eq!(crc32(b"The quick brown fox jumps over the lazy dog"), 0x414F_A339);
44    }
45
46    #[test]
47    fn extending_equals_one_pass() {
48        let text = b"The quick brown fox jumps over the lazy dog";
49        for split in 0..=text.len() {
50            assert_eq!(extend(crc32(&text[..split]), &text[split..]), crc32(text));
51        }
52    }
53}