crc32_v2/lib.rs
1//! # CRC32 V2
2//!
3//! This crate provides a simple CRC32 implementation in Rust.
4//!
5//! ## Usage
6//!
7//! To use this crate, add the following to your `Cargo.toml` file:
8//!
9//! ```toml
10//! [dependencies]
11//! crc32_v2 = "0.0.4"
12//! ```
13//!
14//! Then, you can use the `crc32` or `crc32_little` functions to calculate the CRC32 checksum of a byte buffer.
15//!
16//! ## Example
17//!
18//! ```rust
19//! use crc32_v2::byfour::crc32_little;
20//! use crc32_v2::crc32;
21//!
22//! let crc = crc32(0, &[0u8, 1u8, 2u8, 3u8]);
23//! assert_eq!(crc, 0x8BB98613);
24//! let crc_little = crc32_little(crc, &[0u8, 1u8, 2u8, 3u8]);
25//! assert_eq!(crc, 0x8BB98613);
26//! ```
27//!
28//! ## Implementation Details
29//!
30//! The CRC32 algorithm is implemented using a standard polynomial and lookup tables for optimization.
31//!
32//! The `crc32` function takes two parameters:
33//!
34//! - `start_crc`: the initial CRC32 value (usually 0)
35//! - `buf`: a slice containing the input bytes
36//!
37//! It returns a `u32`, which is the CRC32 checksum of the input buffer.
38
39pub mod byfour;
40pub mod crc32tables;
41
42use crate::crc32tables::CRC_TABLE;
43
44/// This function calculates the CRC32 checksum of a byte buffer using a standard CRC32 algorithm.
45///
46/// # Arguments
47/// * `start_crc` - the initial CRC32 value (usually 0)
48/// * `buf` - a slice containing the input bytes
49///
50/// # Returns
51/// (`u32`): the CRC32 checksum of the input buffer
52///
53/// # Examples
54/// ```
55/// use crc32_v2::crc32;
56///
57/// let crc = crc32(0, &[0u8, 1u8, 2u8, 3u8]);
58/// assert_eq!(crc, 0x8BB98613);
59/// ```
60#[inline]
61pub fn crc32(start_crc: u32, buf: &[u8]) -> u32 {
62 // Initialize variables
63 let len = buf.len();
64 // XOR with 0xffffffff as specified in CRC32 algorithm
65 let mut crc = start_crc ^ 0xffffffff;
66 let mut bufpos: usize = 0;
67 let mut remaining_bytes = len;
68
69 // Reference to the first CRC table for faster access
70 let t0 = &CRC_TABLE[0];
71
72 // Process each byte in the buffer
73 while remaining_bytes > 0 {
74 let b = buf[bufpos];
75 let b32 = b as u32;
76 let b_index = (crc ^ b32) & 0xff;
77 let t = t0[b_index as usize];
78 crc = t ^ (crc >> 8);
79 bufpos += 1;
80 remaining_bytes -= 1;
81 }
82
83 // XOR again with 0xffffffff as specified in CRC32 algorithm
84 crc ^ 0xffffffff
85}