frozen-core 0.0.10

Custom implementations and core utilities for frozen codebases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! Implementation of CRC32C (Castagnoli polynomial) to compute a 32-bit cyclic redundancy check (CRC) using
//! Castagnoli polynomial, intended for data integrity verification for torn writes and curruption detection
//!
//! > [!WARNING]
//! > We assume little-endian target architecture, while big-endian architectures are not supported
//!
//! > [!IMPORTANT]
//! > The generated 32-bit CRC is not cryptographically secure, it's intended use only is for data integrity in IO ops
//!
//! ## What is CRC?
//!
//! Cyclic Redundancy Check (CRC) is an err detecting code, e.g. 32 bits, used for data integrity in networking
//! protocols and storage systems, to check whether data has been altered, partially written/send or corrupted
//!
//! For a given buffer of data, e.g. `[u8; 0x100]`, we first compute a 32-bit crc, send/store it w/ the data, and
//! when received/read, again compute crc on the buffer and match it w/ the original, to check for integrity
//!
//! ## CRC32C
//!
//! CRC32C is a specific version of crc algo, which generates 32-bit crc using the Castagnoli polynomial
//!
//! It uses polynomial arithmetic in GF(2), the generator polynomial for CRC32C is `0x1EDC6F41`, and we use the
//! reflected form `0x82F63B78`, which is required by little-endian streaming algorithms
//!
//! ## Example
//!
//! ```
//! let crc = frozen_core::crc32::Crc32C::default();
//!
//! let b0: [u8; 8] = *b"12345678";
//! let b1: [u8; 8] = *b"ABCDEFGH";
//! let b2: [u8; 8] = *b"abcdefgh";
//! let b3: [u8; 8] = *b"zyxwvuts";
//!
//! assert_eq!(crc.crc(&b0), crc.crc(&b0));
//! assert_eq!(crc.crc_2x([&b0, &b1]),crc.crc_2x([&b0, &b1]));
//! assert_eq!(crc.crc_4x([&b0, &b1, &b2, &b3]),crc.crc_4x([&b0, &b1, &b2, &b3]));
//! ```

#[derive(Debug, PartialEq, Clone, Copy)]
enum Backend {
    Hardware,
    Software,
}

type TCrc = u32;
type TBuf = [u8];

/// Implementation of CRC32C (Castagnoli polynomial) to compute a 32-bit cyclic redundancy check (CRC) using
/// Castagnoli polynomial
///
/// ## Example
///
/// ```
/// let crc = frozen_core::crc32::Crc32C::default();
///
/// let b0: [u8; 8] = *b"12345678";
/// let b1: [u8; 8] = *b"ABCDEFGH";
/// let b2: [u8; 8] = *b"abcdefgh";
/// let b3: [u8; 8] = *b"zyxwvuts";
///
/// assert_eq!(crc.crc(&b0), crc.crc(&b0));
/// assert_eq!(crc.crc_2x([&b0, &b1]),crc.crc_2x([&b0, &b1]));
/// assert_eq!(crc.crc_4x([&b0, &b1, &b2, &b3]),crc.crc_4x([&b0, &b1, &b2, &b3]));
/// ```
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Crc32C(Backend);

impl Crc32C {
    /// Create a new instance of [`Crc32C`]
    ///
    /// ## CRC backend (Hardware vs Software)
    ///
    /// When the new instance is created, we select the fastest available backend,
    ///
    /// - On x86_64 we use `sse4.2` SIMD instructions when available
    /// - On aarch64 we use ARMv8 `crc` instructions when available
    /// - Otherwise, fallback to portable software implementation
    ///
    /// Hardware acceleration is significantly faster than the software fallback, while both backend producing
    /// exact same CRC values
    ///
    /// ## Example
    ///
    /// ```
    /// let crc = frozen_core::crc32::Crc32C::default();
    ///
    /// let b0: [u8; 8] = *b"12345678";
    /// let b1: [u8; 8] = *b"ABCDEFGH";
    /// let b2: [u8; 8] = *b"abcdefgh";
    /// let b3: [u8; 8] = *b"zyxwvuts";
    ///
    /// assert_eq!(crc.crc(&b0), crc.crc(&b0));
    /// assert_eq!(crc.crc_2x([&b0, &b1]),crc.crc_2x([&b0, &b1]));
    /// assert_eq!(crc.crc_4x([&b0, &b1, &b2, &b3]),crc.crc_4x([&b0, &b1, &b2, &b3]));
    /// ```
    pub fn new() -> Self {
        #[cfg(target_arch = "x86_64")]
        if std::is_x86_feature_detected!("sse4.2") {
            return Self(Backend::Hardware);
        }

        #[cfg(target_arch = "aarch64")]
        if std::arch::is_aarch64_feature_detected!("crc") {
            return Self(Backend::Hardware);
        }

        Self(Backend::Software)
    }

    /// Checks whether hardware acceleration is available at runtime
    /// ```
    /// let crc = frozen_core::crc32::Crc32C::default();
    ///
    /// #[cfg(target_arch = "x86_64")]
    /// let expected = std::is_x86_feature_detected!("sse4.2");
    ///
    /// #[cfg(target_arch = "aarch64")]
    /// let expected = std::arch::is_aarch64_feature_detected!("crc");
    ///
    /// assert_eq!(crc.is_hardware_acceleration_available(), expected);    
    /// ```
    pub fn is_hardware_acceleration_available(&self) -> bool {
        self.0 == Backend::Hardware
    }

    /// Compute CRC32C for given `buf` to generate 32-bit crc
    ///
    /// **NOTE:** Length of `buf` must be a multiple of 8
    ///
    /// At runtime we choose the fastest available backend,
    ///
    /// - x86_64: `sse4.2` when available
    /// - aarch64: ArmV8 `crc` instruction when available
    /// - fallback: software castagnoli impl
    ///
    /// All backends produce identical CRC32C values
    ///
    /// ## Example
    ///
    /// ```
    /// let crc = frozen_core::crc32::Crc32C::default();
    ///
    /// let b0: [u8; 8] = *b"12345678";
    /// assert_eq!(crc.crc(&b0), crc.crc(&b0));
    /// ```
    pub fn crc(&self, buf: &TBuf) -> TCrc {
        match self.0 {
            Backend::Software => crc32c_slice8(buf),
            Backend::Hardware => unsafe { crc32c_hardware(buf) },
        }
    }

    /// Compute CRC32C for two bufs in parallel using `Instruction Level Parallelism` to generate 32-bit crc
    /// for each buf (mapped one-to-one)
    ///
    /// **NOTE:** Length of each `buf` must be equal and a multiple of 8
    ///
    /// At runtime we choose the fastest available backend,
    ///
    /// - x86_64: `sse4.2` when available
    /// - aarch64: ArmV8 `crc` instruction when available
    /// - fallback: software castagnoli impl
    ///
    /// All backends produce identical CRC32C values
    ///
    /// ## Example
    ///
    /// ```
    /// let crc = frozen_core::crc32::Crc32C::default();
    ///
    /// let b0: [u8; 8] = *b"12345678";
    /// let b1: [u8; 8] = *b"ABCDEFGH";
    ///
    /// assert_eq!(crc.crc_2x([&b0, &b1]),crc.crc_2x([&b0, &b1]));
    /// ```
    pub fn crc_2x(&self, buffers: [&TBuf; 2]) -> [TCrc; 2] {
        match self.0 {
            Backend::Software => crc32c_slice8_2x(buffers),
            Backend::Hardware => unsafe { crc32c_hardware_2x(buffers) },
        }
    }

    /// Compute CRC32C for four bufs in parallel using `Instruction Level Parallelism` to generate 32-bit crc
    /// for each buf (mapped one-to-one)
    ///
    /// **NOTE:** Length of each `buf` must be equal and a multiple of 8
    ///
    /// At runtime we choose the fastest available backend,
    ///
    /// - x86_64: `sse4.2` when available
    /// - aarch64: ArmV8 `crc` instruction when available
    /// - fallback: software castagnoli impl
    ///
    /// All backends produce identical CRC32C values
    /// ## Example
    ///
    /// ```
    /// let crc = frozen_core::crc32::Crc32C::default();
    ///
    /// let b0: [u8; 8] = *b"12345678";
    /// let b1: [u8; 8] = *b"ABCDEFGH";
    /// let b2: [u8; 8] = *b"abcdefgh";
    /// let b3: [u8; 8] = *b"zyxwvuts";
    ///
    /// assert_eq!(crc.crc_4x([&b0, &b1, &b2, &b3]),crc.crc_4x([&b0, &b1, &b2, &b3]));
    /// ```
    pub fn crc_4x(&self, buffers: [&TBuf; 4]) -> [TCrc; 4] {
        match self.0 {
            Backend::Software => crc32c_slice8_4x(buffers),
            Backend::Hardware => unsafe { crc32c_hardware_4x(buffers) },
        }
    }
}

impl Default for Crc32C {
    fn default() -> Self {
        Self::new()
    }
}

/// Polynomial in refelected form (little endian) over `0x1EDC6F41`, used by CRC32C algorithm as init value
const CASTAGNOLI_POLYNOMIAL: TCrc = 0x82F63B78;

/// Precomputed table of CRC32C values, for runtime perf by reducing computations at runtime,
///
/// ## Memory Footprint
///
/// Memory used is `0x100 * 4 * 8` i.e. `8 KiB`, which is stored in `.rodata` section
const CRC_TABLE: [[TCrc; 0x100]; 8] = {
    let mut table = [[0; 0x100]; 8];

    // table[0]
    let mut i = 0;
    while i < 0x100 {
        let mut crc = i as TCrc;
        let mut j = 0;

        while j < 8 {
            if (crc & 1) != 0 {
                crc = (crc >> 1) ^ CASTAGNOLI_POLYNOMIAL;
            } else {
                crc >>= 1;
            }

            j += 1;
        }

        table[0][i] = crc;
        i += 1;
    }

    // derive table[1..7] from table[0]
    let mut t = 1;
    while t < 8 {
        let mut n = 0;
        while n < 0x100 {
            let crc = table[t - 1][n];
            table[t][n] = (crc >> 8) ^ table[0][(crc & 0xFF) as usize];
            n += 1;
        }

        t += 1;
    }

    table
};

/// Compute CRC32C for `buf` w/ Software Castagnoli impl, to generate 32-bit crc
///
/// **NOTE:** Length of buffer must be a multiple of 8
#[inline(always)]
fn crc32c_slice8(buf: &TBuf) -> TCrc {
    // sanity check
    debug_assert!(buf.len() & 7 == 0);

    let table = &CRC_TABLE[..];

    let mut crc: TCrc = !0;
    let mut len = buf.len();
    let mut ptr = buf.as_ptr();

    while len > 0 {
        let word: u64 = unsafe { core::ptr::read_unaligned(ptr as *const u64) };
        let hi = (word >> 0x20) as TCrc;
        let w = word as TCrc;
        let x = crc ^ w;

        crc = table[7][(x & 0xFF) as usize]
            ^ table[6][((x >> 8) & 0xFF) as usize]
            ^ table[5][((x >> 0x10) & 0xFF) as usize]
            ^ table[4][((x >> 0x18) & 0xFF) as usize]
            ^ table[3][(hi & 0xFF) as usize]
            ^ table[2][((hi >> 8) & 0xFF) as usize]
            ^ table[1][((hi >> 0x10) & 0xFF) as usize]
            ^ table[0][((hi >> 0x18) & 0xFF) as usize];

        ptr = unsafe { ptr.add(8) };
        len -= 8;
    }

    !crc
}

/// Compute CRC32C for two bufs in parallel using `Instruction Level Parallelism` w/ Software Castagnoli impl,
/// to generate 32-bit crc for each buf (mapped one-to-one)
///
/// **NOTE:** Length of each buf must be equal and a multiple of 8
#[inline(always)]
fn crc32c_slice8_2x(buffers: [&TBuf; 2]) -> [TCrc; 2] {
    let mut len = buffers[0].len();

    // sanity checks
    debug_assert!(len & 7 == 0, "bytes_buf must be 8 bytes aligned");
    debug_assert!(
        buffers.iter().all(|b| b.len() == len),
        "each buf in bytes_bufs must be of same length"
    );

    let table = &CRC_TABLE[..];

    let mut crc0: TCrc = !0;
    let mut crc1: TCrc = !0;

    let mut p0 = buffers[0].as_ptr();
    let mut p1 = buffers[1].as_ptr();

    while len > 0 {
        unsafe {
            let w0: u64 = core::ptr::read_unaligned(p0 as *const u64);
            let w1: u64 = core::ptr::read_unaligned(p1 as *const u64);

            let lo0 = w0 as TCrc;
            let lo1 = w1 as TCrc;

            let hi0 = (w0 >> 0x20) as TCrc;
            let hi1 = (w1 >> 0x20) as TCrc;

            let x0 = crc0 ^ lo0;
            let x1 = crc1 ^ lo1;

            crc0 = table[7][(x0 & 0xFF) as usize]
                ^ table[6][((x0 >> 8) & 0xFF) as usize]
                ^ table[5][((x0 >> 0x10) & 0xFF) as usize]
                ^ table[4][((x0 >> 0x18) & 0xFF) as usize]
                ^ table[3][(hi0 & 0xFF) as usize]
                ^ table[2][((hi0 >> 8) & 0xFF) as usize]
                ^ table[1][((hi0 >> 0x10) & 0xFF) as usize]
                ^ table[0][((hi0 >> 0x18) & 0xFF) as usize];

            crc1 = table[7][(x1 & 0xFF) as usize]
                ^ table[6][((x1 >> 8) & 0xFF) as usize]
                ^ table[5][((x1 >> 0x10) & 0xFF) as usize]
                ^ table[4][((x1 >> 0x18) & 0xFF) as usize]
                ^ table[3][(hi1 & 0xFF) as usize]
                ^ table[2][((hi1 >> 8) & 0xFF) as usize]
                ^ table[1][((hi1 >> 0x10) & 0xFF) as usize]
                ^ table[0][((hi1 >> 0x18) & 0xFF) as usize];

            p0 = p0.add(8);
            p1 = p1.add(8);
        }

        len -= 8;
    }

    [!crc0, !crc1]
}

/// Compute CRC32C for four bufs in parallel using `Instruction Level Parallelism` w/ Software Castagnoli impl,
/// to generate 32-bit crc for each buf (mapped one-to-one)
///
/// **NOTE:** Length of each buf must be equal and a multiple of 8
#[inline(always)]
fn crc32c_slice8_4x(buffers: [&TBuf; 4]) -> [TCrc; 4] {
    let mut len = buffers[0].len();

    // sanity checks
    debug_assert!(len & 7 == 0, "bytes_buf must be 8 bytes aligned");
    debug_assert!(
        buffers.iter().all(|b| b.len() == len),
        "each buf in bytes_bufs must be of same length"
    );

    let table = &CRC_TABLE[..];

    let mut crc0: TCrc = !0;
    let mut crc1: TCrc = !0;
    let mut crc2: TCrc = !0;
    let mut crc3: TCrc = !0;

    let mut p0 = buffers[0].as_ptr();
    let mut p1 = buffers[1].as_ptr();
    let mut p2 = buffers[2].as_ptr();
    let mut p3 = buffers[3].as_ptr();

    while len > 0 {
        unsafe {
            let w0: u64 = core::ptr::read_unaligned(p0 as *const u64);
            let w1: u64 = core::ptr::read_unaligned(p1 as *const u64);
            let w2: u64 = core::ptr::read_unaligned(p2 as *const u64);
            let w3: u64 = core::ptr::read_unaligned(p3 as *const u64);

            let lo0 = w0 as TCrc;
            let lo1 = w1 as TCrc;
            let lo2 = w2 as TCrc;
            let lo3 = w3 as TCrc;

            let hi0 = (w0 >> 0x20) as TCrc;
            let hi1 = (w1 >> 0x20) as TCrc;
            let hi2 = (w2 >> 0x20) as TCrc;
            let hi3 = (w3 >> 0x20) as TCrc;

            let x0 = crc0 ^ lo0;
            let x1 = crc1 ^ lo1;
            let x2 = crc2 ^ lo2;
            let x3 = crc3 ^ lo3;

            crc0 = table[7][(x0 & 0xFF) as usize]
                ^ table[6][((x0 >> 8) & 0xFF) as usize]
                ^ table[5][((x0 >> 0x10) & 0xFF) as usize]
                ^ table[4][((x0 >> 0x18) & 0xFF) as usize]
                ^ table[3][(hi0 & 0xFF) as usize]
                ^ table[2][((hi0 >> 8) & 0xFF) as usize]
                ^ table[1][((hi0 >> 0x10) & 0xFF) as usize]
                ^ table[0][((hi0 >> 0x18) & 0xFF) as usize];

            crc1 = table[7][(x1 & 0xFF) as usize]
                ^ table[6][((x1 >> 8) & 0xFF) as usize]
                ^ table[5][((x1 >> 0x10) & 0xFF) as usize]
                ^ table[4][((x1 >> 0x18) & 0xFF) as usize]
                ^ table[3][(hi1 & 0xFF) as usize]
                ^ table[2][((hi1 >> 8) & 0xFF) as usize]
                ^ table[1][((hi1 >> 0x10) & 0xFF) as usize]
                ^ table[0][((hi1 >> 0x18) & 0xFF) as usize];

            crc2 = table[7][(x2 & 0xFF) as usize]
                ^ table[6][((x2 >> 8) & 0xFF) as usize]
                ^ table[5][((x2 >> 0x10) & 0xFF) as usize]
                ^ table[4][((x2 >> 0x18) & 0xFF) as usize]
                ^ table[3][(hi2 & 0xFF) as usize]
                ^ table[2][((hi2 >> 8) & 0xFF) as usize]
                ^ table[1][((hi2 >> 0x10) & 0xFF) as usize]
                ^ table[0][((hi2 >> 0x18) & 0xFF) as usize];

            crc3 = table[7][(x3 & 0xFF) as usize]
                ^ table[6][((x3 >> 8) & 0xFF) as usize]
                ^ table[5][((x3 >> 0x10) & 0xFF) as usize]
                ^ table[4][((x3 >> 0x18) & 0xFF) as usize]
                ^ table[3][(hi3 & 0xFF) as usize]
                ^ table[2][((hi3 >> 8) & 0xFF) as usize]
                ^ table[1][((hi3 >> 0x10) & 0xFF) as usize]
                ^ table[0][((hi3 >> 0x18) & 0xFF) as usize];

            p0 = p0.add(8);
            p1 = p1.add(8);
            p2 = p2.add(8);
            p3 = p3.add(8);
        }

        len -= 8;
    }

    [!crc0, !crc1, !crc2, !crc3]
}

/// Compute CRC32C w/ `sse4.2` SIMD ISA, to generate 32-bit crc
///
/// **NOTE:** Length of `buf` must be a multiple of 8
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse4.2")]
unsafe fn crc32c_hardware(buf: &TBuf) -> TCrc {
    // sanity check
    debug_assert!(buf.len() & 7 == 0, "bytes_buf must be 8 bytes aligned");

    let mut crc: u64 = (!0u32) as u64;
    let mut len = buf.len();
    let mut ptr = buf.as_ptr();

    while len > 0 {
        let word = core::ptr::read_unaligned(ptr as *const u64);
        crc = core::arch::x86_64::_mm_crc32_u64(crc, word);
        ptr = ptr.add(8);

        len -= 8;
    }

    (!crc) as TCrc
}

/// Compute CRC32C for two bufs in parallel using `Instruction Level Parallelism` w/ `sse4.2` SIMD ISA,
/// to generate 32-bit crc for each buf (mapped one-to-one)
///
/// **NOTE:** Length of each buf must be equal and a multiple of 8
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse4.2")]
unsafe fn crc32c_hardware_2x(buffers: [&TBuf; 2]) -> [TCrc; 2] {
    let mut len = buffers[0].len();

    // sanity checks
    debug_assert!(len & 7 == 0, "bytes_buf must be 8 bytes aligned");
    debug_assert!(
        buffers.iter().all(|b| b.len() == len),
        "each buf in bytes_bufs must be of same length"
    );

    let mut c0: u64 = (!0u32) as u64;
    let mut c1: u64 = (!0u32) as u64;

    let mut p0 = buffers[0].as_ptr();
    let mut p1 = buffers[1].as_ptr();

    while len > 0 {
        let w0 = core::ptr::read_unaligned(p0 as *const u64);
        let w1 = core::ptr::read_unaligned(p1 as *const u64);

        c0 = core::arch::x86_64::_mm_crc32_u64(c0, w0);
        c1 = core::arch::x86_64::_mm_crc32_u64(c1, w1);

        p0 = p0.add(8);
        p1 = p1.add(8);
        len -= 8;
    }

    [!(c0 as TCrc), !(c1 as TCrc)]
}

/// Compute CRC32C for four bufs in parallel using `Instruction Level Parallelism` w/ `sse4.2` SIMD ISA,
/// to generate 32-bit crc for each buf (mapped one-to-one)
///
/// **NOTE:** Length of each buffer must be equal and a multiple of 8
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse4.2")]
unsafe fn crc32c_hardware_4x(buffers: [&TBuf; 4]) -> [TCrc; 4] {
    let mut len = buffers[0].len();

    // sanity checks
    debug_assert!(len & 7 == 0, "bytes_buf must be 8 bytes aligned");
    debug_assert!(
        buffers.iter().all(|b| b.len() == len),
        "each buf in bytes_bufs must be of same length"
    );

    let mut c0: u64 = (!0u32) as u64;
    let mut c1: u64 = (!0u32) as u64;
    let mut c2: u64 = (!0u32) as u64;
    let mut c3: u64 = (!0u32) as u64;

    let mut p0 = buffers[0].as_ptr();
    let mut p1 = buffers[1].as_ptr();
    let mut p2 = buffers[2].as_ptr();
    let mut p3 = buffers[3].as_ptr();

    while len > 0 {
        let w0 = core::ptr::read_unaligned(p0 as *const u64);
        let w1 = core::ptr::read_unaligned(p1 as *const u64);
        let w2 = core::ptr::read_unaligned(p2 as *const u64);
        let w3 = core::ptr::read_unaligned(p3 as *const u64);

        c0 = core::arch::x86_64::_mm_crc32_u64(c0, w0);
        c1 = core::arch::x86_64::_mm_crc32_u64(c1, w1);
        c2 = core::arch::x86_64::_mm_crc32_u64(c2, w2);
        c3 = core::arch::x86_64::_mm_crc32_u64(c3, w3);

        p0 = p0.add(8);
        p1 = p1.add(8);
        p2 = p2.add(8);
        p3 = p3.add(8);

        len -= 8;
    }

    [!(c0 as TCrc), !(c1 as TCrc), !(c2 as TCrc), !(c3 as TCrc)]
}

/// Compute CRC32C w/ ArmV8 `crc` SIMD instruction, to generate 32-bit crc
///
/// **NOTE:** Length of `buf` must be a multiple of 8
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "crc")]
unsafe fn crc32c_hardware(buf: &TBuf) -> TCrc {
    // sanity check
    debug_assert!(buf.len() & 7 == 0, "bytes_buf must be 8 bytes aligned");

    let mut crc: TCrc = !0;
    let mut len = buf.len();
    let mut ptr = buf.as_ptr();

    while len > 0 {
        let word: u64 = core::ptr::read_unaligned(ptr as *const u64);
        crc = core::arch::aarch64::__crc32cd(crc, word);
        ptr = ptr.add(8);

        len -= 8;
    }

    !crc
}

/// Compute CRC32C for two bufs in parallel using `Instruction Level Parallelism` w/ ArmV8 `crc` SIMD instruction,
/// to generate 32-bit crc for each buf (mapped one-to-one)
///
/// **NOTE:** Length of each buf must be equal and a multiple of 8
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "crc")]
unsafe fn crc32c_hardware_2x(buffers: [&TBuf; 2]) -> [TCrc; 2] {
    let mut len = buffers[0].len();

    // sanity checks
    debug_assert!(len & 7 == 0, "bytes_buf must be 8 bytes aligned");
    debug_assert!(
        buffers.iter().all(|b| b.len() == len),
        "each buf in bytes_bufs must be of same length"
    );

    let mut c0: TCrc = !0;
    let mut c1: TCrc = !0;

    let mut p0 = buffers[0].as_ptr();
    let mut p1 = buffers[1].as_ptr();

    while len > 0 {
        let w0: u64 = core::ptr::read_unaligned(p0 as *const u64);
        let w1: u64 = core::ptr::read_unaligned(p1 as *const u64);

        c0 = core::arch::aarch64::__crc32cd(c0, w0);
        c1 = core::arch::aarch64::__crc32cd(c1, w1);

        p0 = p0.add(8);
        p1 = p1.add(8);

        len -= 8;
    }

    [!c0, !c1]
}

/// Compute CRC32C for four bufs in parallel using `Instruction Level Parallelism` w/ ArmV8 `crc` SIMD instruction,
/// to generate 32-bit crc for each buf (mapped one-to-one)
///
/// **NOTE:** Length of each buf must be equal and a multiple of 8
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "crc")]
unsafe fn crc32c_hardware_4x(buffers: [&TBuf; 4]) -> [TCrc; 4] {
    let mut len = buffers[0].len();

    // sanity checks
    debug_assert!(len & 7 == 0, "bytes_buf must be 8 bytes aligned");
    debug_assert!(
        buffers.iter().all(|b| b.len() == len),
        "each buf in bytes_bufs must be of same length"
    );

    let mut c0: TCrc = !0;
    let mut c1: TCrc = !0;
    let mut c2: TCrc = !0;
    let mut c3: TCrc = !0;

    let mut p0 = buffers[0].as_ptr();
    let mut p1 = buffers[1].as_ptr();
    let mut p2 = buffers[2].as_ptr();
    let mut p3 = buffers[3].as_ptr();

    while len > 0 {
        let w0: u64 = core::ptr::read_unaligned(p0 as *const u64);
        let w1: u64 = core::ptr::read_unaligned(p1 as *const u64);
        let w2: u64 = core::ptr::read_unaligned(p2 as *const u64);
        let w3: u64 = core::ptr::read_unaligned(p3 as *const u64);

        c0 = core::arch::aarch64::__crc32cd(c0, w0);
        c1 = core::arch::aarch64::__crc32cd(c1, w1);
        c2 = core::arch::aarch64::__crc32cd(c2, w2);
        c3 = core::arch::aarch64::__crc32cd(c3, w3);

        p0 = p0.add(8);
        p1 = p1.add(8);
        p2 = p2.add(8);
        p3 = p3.add(8);

        len -= 8;
    }

    [!c0, !c1, !c2, !c3]
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_buf(len: usize, seed: u8) -> Vec<u8> {
        (0..len).map(|i| seed.wrapping_add(i as u8)).collect()
    }

    #[inline]
    fn is_simd_available() -> bool {
        #[cfg(target_arch = "x86_64")]
        return std::is_x86_feature_detected!("sse4.2");

        #[cfg(target_arch = "aarch64")]
        return std::arch::is_aarch64_feature_detected!("crc");
    }

    mod public_api {
        use super::*;

        #[test]
        fn ok_known_crc_vectors() {
            let crc = Crc32C::default();
            assert_eq!(crc.crc(b"12345678"), 0x6087809A);
        }

        #[test]
        fn ok_crc_is_deterministic() {
            let crc = Crc32C::default();

            let buf = make_buf(0x1000, 0x77);

            let a = crc.crc(&buf);
            let b = crc.crc(&buf);
            let c = crc.crc(&buf);

            assert_eq!(a, b);
            assert_eq!(b, c);
        }

        #[test]
        fn ok_different_buffers_have_different_crc() {
            let crc = Crc32C::default();

            let a = make_buf(0x1000, 0x10);
            let b = make_buf(0x1000, 0x11);

            assert_ne!(crc.crc(&a), crc.crc(&b));
        }

        #[test]
        fn ok_parallel_crc_matches_single() {
            let crc = Crc32C::default();

            let b0 = make_buf(0x1000, 1);
            let b1 = make_buf(0x1000, 2);
            let b2 = make_buf(0x1000, 3);
            let b3 = make_buf(0x1000, 4);

            let s0 = crc.crc(&b0);
            let s1 = crc.crc(&b1);
            let s2 = crc.crc(&b2);
            let s3 = crc.crc(&b3);

            let p2 = crc.crc_2x([&b0, &b1]);
            let p4 = crc.crc_4x([&b0, &b1, &b2, &b3]);

            assert_eq!([s0, s1], p2);
            assert_eq!([s0, s1, s2, s3], p4);
        }

        #[test]
        fn ok_zero_buffer_crc() {
            let crc = Crc32C::default();

            let buf = vec![0u8; 0x1000];
            let a = crc.crc(&buf);
            let b = crc.crc(&buf);

            assert_eq!(a, b);
        }
    }

    mod hw_sw_consistency {
        use super::*;

        #[test]
        fn ok_crc_single_buf() {
            if !is_simd_available() {
                return;
            }

            let buf = make_buf(0x1000, 0x0A);

            let sw = crc32c_slice8(&buf);
            let hw = unsafe { crc32c_hardware(&buf) };
            assert_eq!(sw, hw);
        }

        #[test]
        fn ok_crc_random_bufs() {
            for seed in 0..0x20u8 {
                let buf = make_buf(0x2000, seed);

                let sw = crc32c_slice8(&buf);
                let hw = unsafe { crc32c_hardware(&buf) };
                assert_eq!(sw, hw);
            }
        }

        #[test]
        fn ok_crc_buf_2x() {
            if !is_simd_available() {
                return;
            }

            let b0 = make_buf(0x1000, 0x0A);
            let b1 = make_buf(0x1000, 0x0B);

            let sw = crc32c_slice8_2x([&b0, &b1]);
            let hw = unsafe { crc32c_hardware_2x([&b0, &b1]) };
            assert_eq!(sw, hw);
        }

        #[test]
        fn ok_crc_buf_4x() {
            if !is_simd_available() {
                return;
            }

            let b0 = make_buf(0x1000, 0x0A);
            let b1 = make_buf(0x1000, 0x0B);
            let b2 = make_buf(0x1000, 0x0C);
            let b3 = make_buf(0x1000, 0x0D);

            let sw = crc32c_slice8_4x([&b0, &b1, &b2, &b3]);
            let hw = unsafe { crc32c_hardware_4x([&b0, &b1, &b2, &b3]) };
            assert_eq!(sw, hw);
        }
    }

    mod corruption_detection {
        use super::*;

        #[test]
        fn ok_single_bit_flip_changes_crc() {
            let crc = Crc32C::default();

            let mut buf = make_buf(0x1000, 0xAA);
            let original = crc.crc(&buf);
            buf[0x1A] ^= 1; // manually corrupt a single bit

            let corrupted = crc.crc(&buf);
            assert_ne!(original, corrupted);
        }

        #[test]
        fn ok_multiple_bit_flips_change_crc() {
            let crc = Crc32C::default();

            let mut buf = make_buf(0x2000, 0x11);
            let original = crc.crc(&buf);

            buf[0] ^= 0b0000_0001;
            buf[0x12A] ^= 0b1000_0000;
            buf[0x23B] ^= 0b0001_0000;
            buf[0x100B] ^= 0b0100_0000;

            let corrupted = crc.crc(&buf);
            assert_ne!(original, corrupted);
        }

        #[test]
        fn ok_detects_torn_write_simulation() {
            let crc = Crc32C::default();

            let mut buf = make_buf(0x1000, 0x55);
            let original = crc.crc(&buf);

            // simulating partial overwrites
            for b in &mut buf[0x80..0x100] {
                *b = 0;
            }

            let corrupted = crc.crc(&buf);
            assert_ne!(original, corrupted);
        }

        #[test]
        fn ok_detects_random_corruption() {
            let crc = Crc32C::default();

            let mut buf = make_buf(0x1000, 0x42);
            let original = crc.crc(&buf);

            for i in (0..buf.len()).step_by(0x5F) {
                buf[i] ^= 0xFF;
            }

            let corrupted = crc.crc(&buf);
            assert_ne!(original, corrupted);
        }

        #[test]
        fn ok_every_bit_flip_changes_crc() {
            let crc = Crc32C::default();

            let mut buf = make_buf(0x40, 0xAB);
            let base = crc.crc(&buf);

            for i in 0..buf.len() {
                for bit in 0..8 {
                    buf[i] ^= 1 << bit;
                    assert_ne!(base, crc.crc(&buf));
                    buf[i] ^= 1 << bit;
                }
            }
        }
    }
}