lib_jsl_information/operators/
crc32.rs1use std::sync::OnceLock;
6
7pub const POLY_IEEE: u32 = 0xEDB8_8320;
9pub const POLY_CASTAGNOLI: u32 = 0x82F6_3B78;
11
12fn build_table(poly: u32) -> [u32; 256] {
13 let mut table = [0u32; 256];
14 for (i, entry) in table.iter_mut().enumerate() {
15 let mut c = i as u32;
16 for _ in 0..8 {
17 c = if c & 1 != 0 { (c >> 1) ^ poly } else { c >> 1 };
18 }
19 *entry = c;
20 }
21 table
22}
23
24fn table(poly: u32) -> &'static [u32; 256] {
25 static IEEE: OnceLock<[u32; 256]> = OnceLock::new();
26 static CASTAGNOLI: OnceLock<[u32; 256]> = OnceLock::new();
27 match poly {
28 POLY_IEEE => IEEE.get_or_init(|| build_table(POLY_IEEE)),
29 _ => CASTAGNOLI.get_or_init(|| build_table(POLY_CASTAGNOLI)),
30 }
31}
32
33#[derive(Clone, Debug)]
35pub struct Crc32 {
36 state: u32,
37 poly: u32,
38}
39
40impl Crc32 {
41 pub fn new() -> Self {
43 Crc32 { state: 0xFFFF_FFFF, poly: POLY_IEEE }
44 }
45
46 pub fn castagnoli() -> Self {
48 Crc32 { state: 0xFFFF_FFFF, poly: POLY_CASTAGNOLI }
49 }
50
51 pub fn update(&mut self, data: &[u8]) {
53 let t = table(self.poly);
55 for &b in data {
56 self.state = t[((self.state ^ b as u32) & 0xFF) as usize] ^ (self.state >> 8);
57 }
58 }
60
61 pub fn finalize(&self) -> u32 {
63 !self.state
64 }
65}
66
67impl Default for Crc32 {
68 fn default() -> Self {
69 Self::new()
70 }
71}
72
73pub fn crc32(data: &[u8]) -> u32 {
75 let mut c = Crc32::new();
76 c.update(data);
77 c.finalize()
78}
79
80pub fn crc32c(data: &[u8]) -> u32 {
82 let mut c = Crc32::castagnoli();
83 c.update(data);
84 c.finalize()
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90
91 #[test]
92 fn check_values() {
93 assert_eq!(crc32(b""), 0);
94 assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
95 assert_eq!(crc32(b"The quick brown fox jumps over the lazy dog"), 0x414F_A339);
96 assert_eq!(crc32c(b"123456789"), 0xE306_9283);
97 assert_eq!(crc32c(&[0u8; 32]), 0x8A91_36AA);
98 }
99
100 #[test]
101 fn incremental_matches_one_shot() {
102 let data: Vec<u8> = (0..1000u32).map(|i| (i * 31 % 251) as u8).collect();
103 let mut c = Crc32::new();
104 for chunk in data.chunks(77) {
105 c.update(chunk);
106 }
107 assert_eq!(c.finalize(), crc32(&data));
108 }
109
110 #[test]
111 fn appending_crc_gives_residue() {
112 let mut msg = b"hello world".to_vec();
114 msg.extend_from_slice(&crc32(&msg).to_le_bytes());
115 assert_eq!(crc32(&msg), 0x2144_DF1C);
116 }
117}