Debian Codegraph @

third_party/rust/zlib-rs/src/crc32/braid.rs

raw
1 // Several implementations of CRC-32:
2 // * A naive byte-granularity approach
3 // * A word-sized approach that processes a usize word at a time
4 // * A "braid" implementation that processes a block of N words
5 // at a time, based on the algorithm in section 4.11 from
6 // https://github.com/zlib-ng/zlib-ng/blob/develop/doc/crc-doc.1.0.pdf.
7
8 // The binary encoding of the CRC-32 polynomial.
9 // We are assuming little-endianness so we process the input
10 // LSB-first. We need to use the "reversed" value from e.g
11 // https://en.wikipedia.org/wiki/Cyclic_redundancy_check#Polynomial_representations.
12 pub(crate) const CRC32_LSB_POLY: usize = 0xedb8_8320usize;
13
14 const W: usize = core::mem::size_of::<usize>();
15
16 // The logic assumes that W >= sizeof(u32).
17 // In Rust, this is generally true.
18 const _: () = assert!(W >= core::mem::size_of::<u32>());
19
20 // Pre-computed tables for the CRC32 algorithm.
21 // CRC32_BYTE_TABLE corresponds to MulByXPowD from the paper.
22 static CRC32_BYTE_TABLE: [[u32; 256]; 1] = build_crc32_table::<256, 1, 1>();
23 // CRC32_WORD_TABLE is MulWordByXpowD.
24 static CRC32_WORD_TABLE: [[u32; 256]; W] = build_crc32_table::<256, W, 1>();
25
26 // Work-around for not being able to define generic consts or statics
27 // Crc32BraidTable::<N>::TABLE is the generic table for any braid size N.
28 struct Crc32BraidTable<const N: usize>;
29
30 impl<const N: usize> Crc32BraidTable<N> {
31 const TABLE: [[u32; 256]; W] = build_crc32_table::<256, W, N>();
32 }
33
34 // Build the CRC32 tables using a more efficient and simpler approach
35 // than the combination of Multiply and XpowN (which implement polynomial
36 // multiplication and exponentiation, respectively) from the paper,
37 // but with identical results. This function is const, so it should be
38 // fully evaluated at compile time.
39 const fn build_crc32_table<const A: usize, const W: usize, const N: usize>() -> [[u32; A]; W] {
40 let mut arr = [[0u32; A]; W];
41 let mut i = 0;
42 while i < W {
43 let mut j = 0;
44 while j < A {
45 let mut c = j;
46 let mut k = 0;
47 while k < 8 * (W * N - i) {
48 if c & 1 != 0 {
49 c = CRC32_LSB_POLY ^ (c >> 1);
50 } else {
51 c >>= 1;
52 }
53 k += 1;
54 }
55 arr[i][j] = c as u32;
56 j += 1;
57 }
58 i += 1;
59 }
60 arr
61 }
62
63 fn crc32_naive_inner(data: &[u8], start: u32) -> u32 {
64 data.iter().fold(start, |crc, val| {
65 let crc32_lsb = crc.to_le_bytes()[0];
66 CRC32_BYTE_TABLE[0][usize::from(crc32_lsb ^ *val)] ^ (crc >> 8)
67 })
68 }
69
70 fn crc32_words_inner(words: &[usize], start: u32, per_word_crcs: &[u32]) -> u32 {
71 words.iter().enumerate().fold(start, |crc, (i, word)| {
72 let value = word.to_le() ^ (crc ^ per_word_crcs.get(i).unwrap_or(&0)) as usize;
73 value
74 .to_le_bytes()
75 .into_iter()
76 .zip(CRC32_WORD_TABLE)
77 .fold(0u32, |crc, (b, tab)| crc ^ tab[usize::from(b)])
78 })
79 }
80
81 pub fn crc32_braid<const N: usize>(start: u32, data: &[u8]) -> u32 {
82 // Get a word-aligned sub-slice of the input data
83 // SAFETY: it is safe to transmute a slice of u8 into a usize.
84 let (prefix, words, suffix) = unsafe { data.align_to::<usize>() };
85 let crc = !start;
86 let crc = crc32_naive_inner(prefix, crc);
87
88 let mut crcs = [0u32; N];
89 crcs[0] = crc;
90
91 // TODO: this would normally use words.chunks_exact(N), but
92 // we need to pass the last full block to crc32_words_inner
93 // because we accumulate partial crcs in the array and we
94 // need to roll those into the final value. The last call to
95 // crc32_words_inner does that for us with its per_word_crcs
96 // argument.
97 let blocks = words.len() / N;
98 let blocks = blocks.saturating_sub(1);
99 for i in 0..blocks {
100 // Load the next N words.
101 let mut buffer: [usize; N] =
102 core::array::from_fn(|j| usize::to_le(words[i * N + j]) ^ (crcs[j] as usize));
103
104 crcs.fill(0);
105 for j in 0..W {
106 for k in 0..N {
107 crcs[k] ^= Crc32BraidTable::<N>::TABLE[j][buffer[k] & 0xff];
108 buffer[k] >>= 8;
109 }
110 }
111 }
112
113 let crc = core::mem::take(&mut crcs[0]);
114 let crc = crc32_words_inner(&words[blocks * N..], crc, &crcs);
115 let crc = crc32_naive_inner(suffix, crc);
116 !crc
117 }
118
119 #[cfg(test)]
120 mod test {
121 use super::*;
122
123 fn crc32_naive(data: &[u8], start: u32) -> u32 {
124 let crc = !start;
125 let crc = crc32_naive_inner(data, crc);
126 !crc
127 }
128
129 fn crc32_words(data: &[u8], start: u32) -> u32 {
130 // Get a word-aligned sub-slice of the input data
131 let (prefix, words, suffix) = unsafe { data.align_to::<usize>() };
132 let crc = !start;
133 let crc = crc32_naive_inner(prefix, crc);
134 let crc = crc32_words_inner(words, crc, &[]);
135 let crc = crc32_naive_inner(suffix, crc);
136 !crc
137 }
138
139 #[test]
140 fn empty_is_identity() {
141 assert_eq!(crc32_naive(&[], 32), 32);
142 }
143
144 #[test]
145 fn words_endianness() {
146 let v = [0, 0, 0, 0, 0, 16, 0, 1];
147 let start = 1534327806;
148
149 let mut h = crc32fast::Hasher::new_with_initial(start);
150 h.update(&v[..]);
151 assert_eq!(crc32_words(&v[..], start), h.finalize());
152 }
153
154 #[test]
155 fn crc32_naive_inner_endianness_and_alignment() {
156 assert_eq!(crc32_naive_inner(&[0, 1], 0), 1996959894);
157
158 let v: Vec<_> = (0..1024).map(|i| i as u8).collect();
159 let start = 0;
160
161 // test alignment
162 for i in 0..8 {
163 let mut h = crc32fast::Hasher::new_with_initial(start);
164 h.update(&v[i..]);
165 assert_eq!(crc32_braid::<5>(start, &v[i..]), h.finalize());
166 }
167 }
168
169 quickcheck::quickcheck! {
170 fn naive_is_crc32fast(v: Vec<u8>, start: u32) -> bool {
171 let mut h = crc32fast::Hasher::new_with_initial(start);
172 h.update(&v[..]);
173 crc32_naive(&v[..], start) == h.finalize()
174 }
175
176 fn words_is_crc32fast(v: Vec<u8>, start: u32) -> bool {
177 let mut h = crc32fast::Hasher::new_with_initial(start);
178 h.update(&v[..]);
179 crc32_words(&v[..], start) == h.finalize()
180 }
181
182 #[cfg_attr(miri, ignore)]
183 fn braid_4_is_crc32fast(v: Vec<u8>, start: u32) -> bool {
184 let mut h = crc32fast::Hasher::new_with_initial(start);
185 h.update(&v[..]);
186 crc32_braid::<4>(start, &v[..]) == h.finalize()
187 }
188
189 #[cfg_attr(miri, ignore)]
190 fn braid_5_is_crc32fast(v: Vec<u8>, start: u32) -> bool {
191 let mut h = crc32fast::Hasher::new_with_initial(start);
192 h.update(&v[..]);
193 crc32_braid::<5>(start, &v[..]) == h.finalize()
194 }
195
196 #[cfg_attr(miri, ignore)]
197 fn braid_6_is_crc32fast(v: Vec<u8>, start: u32) -> bool {
198 let mut h = crc32fast::Hasher::new_with_initial(start);
199 h.update(&v[..]);
200 crc32_braid::<6>(start, &v[..]) == h.finalize()
201 }
202 }
203 }