1#[cfg(target_arch = "x86")]
22use core::arch::x86 as arch;
23#[cfg(target_arch = "x86_64")]
24use core::arch::x86_64 as arch;
25
26#[derive(Clone, Copy)]
28enum Kind {
29 Sse,
31 #[cfg(stable_vpclmulqdq)]
33 Avx2,
34 #[cfg(stable_vpclmulqdq)]
36 Avx512,
37}
38
39#[cfg(feature = "std")]
40impl Kind {
41 #[inline]
43 fn encode(kind: Option<Kind>) -> u8 {
44 match kind {
45 None => 1,
46 Some(Kind::Sse) => 2,
47 #[cfg(stable_vpclmulqdq)]
48 Some(Kind::Avx2) => 3,
49 #[cfg(stable_vpclmulqdq)]
50 Some(Kind::Avx512) => 4,
51 }
52 }
53
54 #[inline]
56 fn decode(code: u8) -> Option<Kind> {
57 match code {
58 2 => Some(Kind::Sse),
59 #[cfg(stable_vpclmulqdq)]
60 3 => Some(Kind::Avx2),
61 #[cfg(stable_vpclmulqdq)]
62 4 => Some(Kind::Avx512),
63 _ => {
64 debug_assert_eq!(code, 1, "code from `encode` has no `decode` arm");
65 None
66 }
67 }
68 }
69}
70
71#[derive(Clone)]
72pub struct State {
73 kind: Kind,
74}
75
76impl State {
77 #[cfg(not(feature = "std"))]
78 #[inline]
79 fn detect() -> Option<Kind> {
80 if cfg!(target_feature = "pclmulqdq")
81 && cfg!(target_feature = "sse2")
82 && cfg!(target_feature = "sse4.1")
83 && cfg!(target_feature = "ssse3")
84 {
85 #[cfg(stable_vpclmulqdq)]
86 {
87 if cfg!(target_feature = "avx512f") && cfg!(target_feature = "vpclmulqdq") {
88 return Some(Kind::Avx512);
89 }
90 if cfg!(target_feature = "avx2") && cfg!(target_feature = "vpclmulqdq") {
91 return Some(Kind::Avx2);
92 }
93 }
94
95 return Some(Kind::Sse);
96 }
97
98 None
99 }
100
101 #[cfg(feature = "std")]
105 #[inline]
106 fn detect() -> Option<Kind> {
107 use core::sync::atomic::{AtomicU8, Ordering};
108
109 static CACHE: AtomicU8 = AtomicU8::new(0);
112 match CACHE.load(Ordering::Relaxed) {
113 0 => {
114 let kind = Self::detect_uncached();
115 CACHE.store(Kind::encode(kind), Ordering::Relaxed);
116 kind
117 }
118 code => Kind::decode(code),
119 }
120 }
121
122 #[cfg(feature = "std")]
123 #[cold]
124 fn detect_uncached() -> Option<Kind> {
125 if is_x86_feature_detected!("pclmulqdq")
126 && is_x86_feature_detected!("sse2")
127 && is_x86_feature_detected!("sse4.1")
128 && is_x86_feature_detected!("ssse3")
129 {
130 #[cfg(stable_vpclmulqdq)]
131 {
132 if is_x86_feature_detected!("avx512f") && is_x86_feature_detected!("vpclmulqdq") {
133 return Some(Kind::Avx512);
134 }
135 if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("vpclmulqdq") {
136 return Some(Kind::Avx2);
137 }
138 }
139
140 return Some(Kind::Sse);
141 }
142
143 None
144 }
145
146 #[inline]
147 pub fn new() -> Option<Self> {
148 Self::detect().map(|kind| Self { kind })
150 }
151
152 #[inline]
153 pub fn update(&self, state: u32, buf: &[u8]) -> u32 {
154 unsafe {
158 match self.kind {
159 Kind::Sse => calculate(state, buf),
160 #[cfg(stable_vpclmulqdq)]
161 Kind::Avx2 => calculate_avx2(state, buf),
162 #[cfg(stable_vpclmulqdq)]
163 Kind::Avx512 => calculate_avx512(state, buf),
164 }
165 }
166 }
167}
168
169const K1: i64 = 0x154442bd4;
170const K2: i64 = 0x1c6e41596;
171const K3: i64 = 0x1751997d0;
172const K4: i64 = 0x0ccaa009e;
173
174const BARRETT_MU: i64 = 0xb4e5b025f7011641_u64 as i64;
176const BARRETT_G: i64 = 0x1db710641;
177
178const MIN_FOLD_BY_4_BYTES: usize = 128;
181#[cfg(stable_vpclmulqdq)]
182const MIN_AVX512_BYTES: usize = 2 * 1024;
183
184#[cfg(stable_vpclmulqdq)]
188const K_1024_LOW: i64 = 0x1e88ef372;
189#[cfg(stable_vpclmulqdq)]
190const K_1024_HIGH: i64 = 0x14a7fe880;
191#[cfg(stable_vpclmulqdq)]
192const K_2048_LOW: i64 = 0x11542778a;
193#[cfg(stable_vpclmulqdq)]
194const K_2048_HIGH: i64 = 0x1322d1430;
195
196#[target_feature(
197 enable = "pclmulqdq",
198 enable = "sse2",
199 enable = "sse4.1",
200 enable = "ssse3"
201)]
202unsafe fn calculate(crc: u32, mut data: &[u8]) -> u32 {
203 if data.len() < 16 {
205 return crate::baseline::update_short(crc, data);
206 }
207 let input = data;
208
209 if data.len() < MIN_FOLD_BY_4_BYTES {
212 let mut x = get(&mut data);
213 x = arch::_mm_xor_si128(x, arch::_mm_cvtsi32_si128(!crc as i32));
214 return reduce_128_to_crc(x, input, data);
215 }
216
217 let mut x3 = get(&mut data);
219 let mut x2 = get(&mut data);
220 let mut x1 = get(&mut data);
221 let mut x0 = get(&mut data);
222
223 x3 = arch::_mm_xor_si128(x3, arch::_mm_cvtsi32_si128(!crc as i32));
225
226 let k1k2 = arch::_mm_set_epi64x(K2, K1);
227 while data.len() >= 64 {
228 x3 = reduce128(x3, get(&mut data), k1k2);
229 x2 = reduce128(x2, get(&mut data), k1k2);
230 x1 = reduce128(x1, get(&mut data), k1k2);
231 x0 = reduce128(x0, get(&mut data), k1k2);
232 }
233
234 let k3k4 = arch::_mm_set_epi64x(K4, K3);
235 let mut x = reduce128(x3, x2, k3k4);
236 x = reduce128(x, x1, k3k4);
237 x = reduce128(x, x0, k3k4);
238
239 reduce_128_to_crc(x, input, data)
240}
241
242#[cfg(stable_vpclmulqdq)]
245#[allow(clippy::incompatible_msrv)] #[target_feature(
247 enable = "pclmulqdq",
248 enable = "sse2",
249 enable = "sse4.1",
250 enable = "ssse3",
251 enable = "avx",
252 enable = "avx2",
253 enable = "vpclmulqdq"
254)]
255unsafe fn calculate_avx2(crc: u32, mut data: &[u8]) -> u32 {
256 if data.len() < 256 {
258 return calculate(crc, data);
259 }
260 let input = data;
261
262 let mut v0 = get256(&mut data);
264 let mut v1 = get256(&mut data);
265 let mut v2 = get256(&mut data);
266 let mut v3 = get256(&mut data);
267
268 v0 = arch::_mm256_xor_si256(
270 v0,
271 arch::_mm256_castsi128_si256(arch::_mm_cvtsi32_si128(!crc as i32)),
272 );
273
274 let k = arch::_mm256_set_epi64x(K_1024_HIGH, K_1024_LOW, K_1024_HIGH, K_1024_LOW);
275 while data.len() >= 128 {
276 v0 = reduce256(v0, get256(&mut data), k);
277 v1 = reduce256(v1, get256(&mut data), k);
278 v2 = reduce256(v2, get256(&mut data), k);
279 v3 = reduce256(v3, get256(&mut data), k);
280 }
281
282 let k3k4 = arch::_mm_set_epi64x(K4, K3);
284 let mut x = arch::_mm256_castsi256_si128(v0);
285 x = reduce128(x, arch::_mm256_extracti128_si256(v0, 1), k3k4);
286 x = reduce128(x, arch::_mm256_castsi256_si128(v1), k3k4);
287 x = reduce128(x, arch::_mm256_extracti128_si256(v1, 1), k3k4);
288 x = reduce128(x, arch::_mm256_castsi256_si128(v2), k3k4);
289 x = reduce128(x, arch::_mm256_extracti128_si256(v2, 1), k3k4);
290 x = reduce128(x, arch::_mm256_castsi256_si128(v3), k3k4);
291 x = reduce128(x, arch::_mm256_extracti128_si256(v3, 1), k3k4);
292
293 reduce_128_to_crc(x, input, data)
294}
295
296#[cfg(stable_vpclmulqdq)]
299#[allow(clippy::incompatible_msrv)] #[target_feature(
301 enable = "pclmulqdq",
302 enable = "sse2",
303 enable = "sse4.1",
304 enable = "ssse3",
305 enable = "avx",
306 enable = "avx2",
307 enable = "vpclmulqdq",
308 enable = "avx512f"
309)]
310unsafe fn calculate_avx512(crc: u32, mut data: &[u8]) -> u32 {
311 if data.len() < MIN_AVX512_BYTES {
313 return calculate_avx2(crc, data);
314 }
315 let input = data;
316
317 let mut v0 = get512(&mut data);
319 let mut v1 = get512(&mut data);
320 let mut v2 = get512(&mut data);
321 let mut v3 = get512(&mut data);
322
323 v0 = arch::_mm512_xor_si512(
325 v0,
326 arch::_mm512_castsi128_si512(arch::_mm_cvtsi32_si128(!crc as i32)),
327 );
328
329 let k = arch::_mm512_set_epi64(
330 K_2048_HIGH,
331 K_2048_LOW,
332 K_2048_HIGH,
333 K_2048_LOW,
334 K_2048_HIGH,
335 K_2048_LOW,
336 K_2048_HIGH,
337 K_2048_LOW,
338 );
339 while data.len() >= 256 {
340 v0 = reduce512(v0, get512(&mut data), k);
341 v1 = reduce512(v1, get512(&mut data), k);
342 v2 = reduce512(v2, get512(&mut data), k);
343 v3 = reduce512(v3, get512(&mut data), k);
344 }
345
346 let k3k4 = arch::_mm_set_epi64x(K4, K3);
348 let mut x = arch::_mm512_castsi512_si128(v0);
349 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v0, 1), k3k4);
350 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v0, 2), k3k4);
351 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v0, 3), k3k4);
352 x = reduce128(x, arch::_mm512_castsi512_si128(v1), k3k4);
353 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v1, 1), k3k4);
354 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v1, 2), k3k4);
355 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v1, 3), k3k4);
356 x = reduce128(x, arch::_mm512_castsi512_si128(v2), k3k4);
357 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v2, 1), k3k4);
358 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v2, 2), k3k4);
359 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v2, 3), k3k4);
360 x = reduce128(x, arch::_mm512_castsi512_si128(v3), k3k4);
361 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v3, 1), k3k4);
362 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v3, 2), k3k4);
363 x = reduce128(x, arch::_mm512_extracti32x4_epi32(v3, 3), k3k4);
364
365 if data.len() >= MIN_FOLD_BY_4_BYTES {
368 let crc = reduce_128_to_crc(x, input, &[]);
369 return calculate(crc, data);
370 }
371
372 reduce_128_to_crc(x, input, data)
373}
374
375#[target_feature(
380 enable = "pclmulqdq",
381 enable = "sse2",
382 enable = "sse4.1",
383 enable = "ssse3"
384)]
385unsafe fn reduce_128_to_crc(mut x: arch::__m128i, input: &[u8], mut rest: &[u8]) -> u32 {
386 let k3k4 = arch::_mm_set_epi64x(K4, K3);
387
388 while rest.len() >= 16 {
390 x = reduce128(x, get(&mut rest), k3k4);
391 }
392
393 let n = rest.len();
404 if n > 0 {
405 let seq = arch::_mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
406 let shl = arch::_mm_add_epi8(seq, arch::_mm_set1_epi8(n as i8 - 16));
407 let shr = arch::_mm_xor_si128(shl, arch::_mm_set1_epi8(-128));
408
409 let first = arch::_mm_shuffle_epi8(x, shl);
410 let tail =
411 arch::_mm_loadu_si128(input[input.len() - 16..].as_ptr() as *const arch::__m128i);
412 let last = arch::_mm_blendv_epi8(arch::_mm_shuffle_epi8(x, shr), tail, shr);
413 x = reduce128(first, last, k3k4);
414 }
415
416 let x = arch::_mm_xor_si128(
424 arch::_mm_clmulepi64_si128(x, k3k4, 0x10),
425 arch::_mm_srli_si128(x, 8),
426 );
427 let barrett = arch::_mm_set_epi64x(BARRETT_G, BARRETT_MU);
428 let t = arch::_mm_clmulepi64_si128(x, barrett, 0x00);
429 let t = arch::_mm_clmulepi64_si128(t, barrett, 0x10);
430 !(arch::_mm_extract_epi32(arch::_mm_xor_si128(x, t), 2) as u32)
431}
432
433#[inline]
434unsafe fn reduce128(a: arch::__m128i, b: arch::__m128i, keys: arch::__m128i) -> arch::__m128i {
435 let t1 = arch::_mm_clmulepi64_si128(a, keys, 0x00);
436 let t2 = arch::_mm_clmulepi64_si128(a, keys, 0x11);
437 arch::_mm_xor_si128(arch::_mm_xor_si128(b, t1), t2)
438}
439
440#[cfg(stable_vpclmulqdq)]
441#[allow(clippy::incompatible_msrv)] #[target_feature(enable = "avx2", enable = "vpclmulqdq")]
443#[inline]
444unsafe fn reduce256(a: arch::__m256i, b: arch::__m256i, keys: arch::__m256i) -> arch::__m256i {
445 let t1 = arch::_mm256_clmulepi64_epi128(a, keys, 0x00);
446 let t2 = arch::_mm256_clmulepi64_epi128(a, keys, 0x11);
447 arch::_mm256_xor_si256(arch::_mm256_xor_si256(b, t1), t2)
448}
449
450#[cfg(stable_vpclmulqdq)]
451#[allow(clippy::incompatible_msrv)] #[target_feature(enable = "avx512f", enable = "vpclmulqdq")]
453#[inline]
454unsafe fn reduce512(a: arch::__m512i, b: arch::__m512i, keys: arch::__m512i) -> arch::__m512i {
455 let t1 = arch::_mm512_clmulepi64_epi128(a, keys, 0x00);
456 let t2 = arch::_mm512_clmulepi64_epi128(a, keys, 0x11);
457 arch::_mm512_xor_si512(arch::_mm512_xor_si512(b, t1), t2)
458}
459
460#[inline]
466fn get(a: &mut &[u8]) -> arch::__m128i {
467 let r = unsafe { arch::_mm_loadu_si128(a[..16].as_ptr() as *const arch::__m128i) };
470 *a = &a[16..];
471 r
472}
473
474#[cfg(stable_vpclmulqdq)]
475#[target_feature(enable = "avx")]
476#[inline]
477unsafe fn get256(a: &mut &[u8]) -> arch::__m256i {
478 let r = arch::_mm256_loadu_si256(a[..32].as_ptr() as *const arch::__m256i);
479 *a = &a[32..];
480 r
481}
482
483#[cfg(stable_vpclmulqdq)]
484#[allow(clippy::incompatible_msrv)] #[target_feature(enable = "avx512f")]
486#[inline]
487unsafe fn get512(a: &mut &[u8]) -> arch::__m512i {
488 let r = arch::_mm512_loadu_si512(a[..64].as_ptr() as *const _);
489 *a = &a[64..];
490 r
491}
492
493#[cfg(test)]
494mod test {
495 quickcheck::quickcheck! {
496 fn check_against_baseline(init: u32, chunks: Vec<(Vec<u8>, usize)>) -> bool {
497 let mut baseline = init;
498 let mut pclmulqdq = init;
499 let spec = super::State::new().expect("not supported");
500
501 for (chunk, mut offset) in chunks {
502 offset &= 0xF;
504 if chunk.len() <= offset {
505 baseline = crate::baseline::update_fast_16(baseline, &chunk);
506 pclmulqdq = spec.update(pclmulqdq, &chunk);
507 } else {
508 baseline = crate::baseline::update_fast_16(baseline, &chunk[offset..]);
509 pclmulqdq = spec.update(pclmulqdq, &chunk[offset..]);
510 }
511 }
512 pclmulqdq == baseline
513 }
514 }
515
516 #[test]
518 fn check_large_inputs_against_baseline() {
519 let mut data = vec![0u8; 8200];
520 let mut s: u32 = 0x1234_5678;
521 for b in data.iter_mut() {
522 s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
523 *b = (s >> 24) as u8;
524 }
525
526 for &len in &[
527 0usize, 1, 15, 16, 17, 63, 64, 127, 128, 129, 255, 256, 257, 511, 512, 513, 1023, 1024,
528 1025, 2047, 2048, 2049, 2175, 2176, 2303, 2304, 4096, 8192, 8199,
529 ] {
530 for &offset in &[0usize, 1, 3, 7, 8, 15] {
531 if offset + len > data.len() {
532 continue;
533 }
534 let slice = &data[offset..offset + len];
535 let baseline = crate::baseline::update_fast_16(0, slice);
536 let spec = super::State::new().expect("not supported");
537 let specialized = spec.update(0, slice);
538
539 assert_eq!(
540 specialized, baseline,
541 "mismatch for len={len} offset={offset}",
542 );
543 }
544 }
545 }
546}