msg_tool\utils/
crc32.rs

1//! Crc32 Utility
2use lazy_static::lazy_static;
3
4fn get_crc32normal_table() -> [u32; 256] {
5    let mut table = [0; 256];
6    for i in 0..256u32 {
7        let mut c = i << 24;
8        for _ in 0..8 {
9            if c & 0x80000000 != 0 {
10                c = (c << 1) ^ 0x04C11DB7; // Polynomial for CRC-32
11            } else {
12                c <<= 1;
13            }
14        }
15        table[i as usize] = c;
16    }
17    table
18}
19
20lazy_static! {
21    /// CRC32 Normal Table
22    pub static ref CRC32NORMAL_TABLE: [u32; 256] = get_crc32normal_table();
23}
24
25/// A CRC32 Normal implementation.
26pub struct Crc32Normal {
27    crc: u32,
28}
29
30impl Crc32Normal {
31    /// Creates a new Crc32Normal instance with an initial CRC value.
32    pub fn new() -> Self {
33        Crc32Normal { crc: 0xFFFFFFFF }
34    }
35
36    /// Creates a new Crc32Normal instance with a specified initial CRC value.
37    pub fn update_crc(init_crc: u32, data: &[u8]) -> u32 {
38        let mut crc = init_crc;
39        for &byte in data {
40            let index = ((crc >> 24) ^ byte as u32) & 0xFF;
41            crc = (crc << 8) ^ CRC32NORMAL_TABLE[index as usize];
42        }
43        crc ^ 0xFFFFFFFF
44    }
45
46    /// Updates the CRC value with new data.
47    pub fn update(&mut self, data: &[u8]) {
48        self.crc = Self::update_crc(self.crc, data);
49    }
50
51    /// Returns the current CRC value.
52    pub fn value(&self) -> u32 {
53        self.crc
54    }
55}