Skip to main content

crc32/
lib.rs

1//! Fast, SIMD-accelerated CRC32 (IEEE) checksum computation.
2//!
3//! ## Usage
4//!
5//! ### Simple usage
6//!
7//! For simple use-cases, you can call the [`hash()`] convenience function to
8//! directly compute the CRC32 checksum for a given byte slice:
9//!
10//! ```rust
11//! let checksum = crc32::hash(b"foo bar baz");
12//! ```
13//!
14//! ### Advanced usage
15//!
16//! For use-cases that require more flexibility or performance, for example when
17//! processing large amounts of data, you can create and manipulate a [`Hasher`]:
18//!
19//! ```rust
20//! use crc32::Hasher;
21//!
22//! let mut hasher = Hasher::new();
23//! hasher.update(b"foo bar baz");
24//! let checksum = hasher.finalize();
25//! ```
26//!
27//! ## Performance
28//!
29//! This crate contains multiple CRC32 implementations:
30//!
31//! - A fast baseline implementation which processes up to 16 bytes per iteration
32//! - An optimized implementation for modern `x86` using `sse` and `pclmulqdq` instructions
33//! - An optimized implementation for `aarch64` using the `crc32` instructions
34//!
35//! Calling the [`Hasher::new`] constructor at runtime will perform a feature
36//! detection to select the most optimal implementation for the current CPU
37//! feature set.
38//!
39//! ## Memory safety
40//!
41//! Due to the use of SIMD intrinsics for the optimized implementations, this
42//! crate contains some amount of `unsafe` code. The baseline implementation is
43//! safe, and the specialized implementations are exercised by the crate's
44//! tests, which are only compiled when the `std` feature is enabled.
45//!
46//! ## Feature flags
47//!
48//! ### `std` (default: enabled)
49//!
50//! The crate can be built without the Rust `std` library, which is useful for
51//! low-level use-cases such as embedded where no operating system is available.
52//! To build the crate in a `no_std` context, disable the default `std` feature.
53//!
54//! Because runtime CPU feature detection requires OS support, the specialized
55//! SIMD implementations are unavailable when the `std` feature is disabled.
56//!
57//! ### `nightly` (default: disabled)
58//!
59//! Enables unstable features that are only available on the `nightly` channel.
60//! Enabling it makes the optimized `aarch64` implementation available.
61
62#![cfg_attr(not(feature = "std"), no_std)]
63
64// #[deny(missing_docs)]
65// #[cfg(test)]
66// #[macro_use]
67// extern crate quickcheck;
68
69use core::{fmt, hash};
70#[cfg(feature = "std")]
71use std as core;
72
73mod baseline;
74mod combine;
75mod specialized;
76mod table;
77
78/// Computes the CRC32 hash of a byte slice.
79///
80/// Check out [`Hasher`] for more advanced use-cases.
81pub fn hash(buf: &[u8]) -> u32 {
82    let mut h = Hasher::new();
83    h.update(buf);
84    h.finalize()
85}
86
87#[derive(Clone)]
88enum State {
89    Baseline(baseline::State),
90    Specialized(specialized::State),
91}
92
93#[derive(Clone)]
94/// Represents an in-progress CRC32 computation.
95pub struct Hasher {
96    amount: u64,
97    state: State,
98}
99
100const DEFAULT_INIT_STATE: u32 = 0;
101
102impl Hasher {
103    /// Create a new `Hasher`.
104    ///
105    /// This will perform a CPU feature detection at runtime to select the most
106    /// optimal implementation for the current processor architecture.
107    pub fn new() -> Self {
108        Self::new_with_initial(DEFAULT_INIT_STATE)
109    }
110
111    /// Create a new `Hasher` with an initial CRC32 state.
112    ///
113    /// This works just like `Hasher::new`, except that it allows for an initial
114    /// CRC32 state to be passed in.
115    pub fn new_with_initial(init: u32) -> Self {
116        Self::new_with_initial_len(init, 0)
117    }
118
119    /// Create a new `Hasher` with an initial CRC32 state.
120    ///
121    /// As `new_with_initial`, but also accepts a length (in bytes). The
122    /// resulting object can then be used with `combine` to compute `crc(a ||
123    /// b)` from `crc(a)`, `crc(b)`, and `len(b)`.
124    pub fn new_with_initial_len(init: u32, amount: u64) -> Self {
125        Self::internal_new_specialized(init, amount).unwrap_or_else(|| Self::internal_new_baseline(init, amount))
126    }
127
128    #[doc(hidden)]
129    // Internal-only API. Don't use.
130    pub fn internal_new_baseline(init: u32, amount: u64) -> Self {
131        Hasher {
132            amount,
133            state: State::Baseline(baseline::State::new(init)),
134        }
135    }
136
137    #[doc(hidden)]
138    // Internal-only API. Don't use.
139    pub fn internal_new_specialized(init: u32, amount: u64) -> Option<Self> {
140        {
141            if let Some(state) = specialized::State::new(init) {
142                return Some(Hasher {
143                    amount,
144                    state: State::Specialized(state),
145                });
146            }
147        }
148        None
149    }
150
151    /// Process the given byte slice and update the hash state.
152    pub fn update(&mut self, buf: &[u8]) {
153        self.amount += buf.len() as u64;
154        match self.state {
155            State::Baseline(ref mut state) => state.update(buf),
156            State::Specialized(ref mut state) => state.update(buf),
157        }
158    }
159
160    /// Finalize the hash state and return the computed CRC32 value.
161    pub fn finalize(self) -> u32 {
162        match self.state {
163            State::Baseline(state) => state.finalize(),
164            State::Specialized(state) => state.finalize(),
165        }
166    }
167
168    /// Reset the hash state.
169    pub fn reset(&mut self) {
170        self.amount = 0;
171        match self.state {
172            State::Baseline(ref mut state) => state.reset(),
173            State::Specialized(ref mut state) => state.reset(),
174        }
175    }
176
177    /// Combine the hash state with the hash state for the subsequent block of bytes.
178    pub fn combine(&mut self, other: &Self) {
179        self.amount += other.amount;
180        let other_crc = other.clone().finalize();
181        match self.state {
182            State::Baseline(ref mut state) => state.combine(other_crc, other.amount),
183            State::Specialized(ref mut state) => state.combine(other_crc, other.amount),
184        }
185    }
186}
187
188impl fmt::Debug for Hasher {
189    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190        f.debug_struct("crc32::Hasher").finish()
191    }
192}
193
194impl Default for Hasher {
195    fn default() -> Self {
196        Self::new()
197    }
198}
199
200impl hash::Hasher for Hasher {
201    fn write(&mut self, bytes: &[u8]) {
202        self.update(bytes)
203    }
204
205    fn finish(&self) -> u64 {
206        u64::from(self.clone().finalize())
207    }
208}
209
210#[cfg(all(test, feature = "std"))]
211mod test {
212    use rand::{TryRng, rngs::SysRng};
213
214    use super::Hasher;
215
216    #[test]
217    fn combine() {
218        let mut rand_generator = SysRng;
219
220        let mut bytes_1 = vec![100];
221        rand_generator.try_fill_bytes(&mut bytes_1).unwrap();
222
223        let mut bytes_2 = vec![200];
224        rand_generator.try_fill_bytes(&mut bytes_2).unwrap();
225
226        let mut hash_a = Hasher::new();
227        hash_a.update(&bytes_1);
228        hash_a.update(&bytes_2);
229        let mut hash_b = Hasher::new();
230        hash_b.update(&bytes_2);
231        let mut hash_c = Hasher::new();
232        hash_c.update(&bytes_1);
233        hash_c.combine(&hash_b);
234
235        assert_eq!(hash_a.finalize(), hash_c.finalize());
236    }
237
238    #[test]
239    fn combine_from_len() {
240        let mut rand_generator = SysRng;
241
242        let mut bytes_1 = vec![200];
243        rand_generator.try_fill_bytes(&mut bytes_1).unwrap();
244
245        let mut bytes_2 = vec![100];
246        rand_generator.try_fill_bytes(&mut bytes_2).unwrap();
247
248        let mut hash_a = Hasher::new();
249        hash_a.update(&bytes_1);
250        let a = hash_a.finalize();
251
252        let mut hash_b = Hasher::new();
253        hash_b.update(&bytes_2);
254        let b = hash_b.finalize();
255
256        let mut hash_ab = Hasher::new();
257        hash_ab.update(&bytes_1);
258        hash_ab.update(&bytes_2);
259        let ab = hash_ab.finalize();
260
261        let mut reconstructed = Hasher::new_with_initial_len(a, bytes_1.len() as u64);
262        let hash_b_reconstructed = Hasher::new_with_initial_len(b, bytes_2.len() as u64);
263
264        reconstructed.combine(&hash_b_reconstructed);
265
266        assert_eq!(reconstructed.finalize(), ab);
267    }
268}