bytesetscan 0.0.1

SIMD-accelerated byte-set matching with Shufti and Truffle
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
mod iter;
mod vtable;

pub use self::iter::{ShuftiEngineFinder, ShuftiEngineMismatcher};

use self::vtable::VTable;
use super::ShuftiTable;
use crate::SimdBackend;

/// A Shufti search engine with a custom backend.
///
/// # Examples
///
/// ```
/// use bytesetscan::{shufti::ShuftiEngine, SimdBackend};
///
/// let engine = ShuftiEngine::new(SimdBackend::Fallback, b"a").unwrap();
/// assert_eq!(engine.find(b"a!a"), Some(0));
/// assert_eq!(engine.mismatch(b"a!a"), Some(1));
/// assert_eq!(engine.rfind(b"a!a"), Some(2));
/// assert_eq!(engine.rmismatch(b"a!a"), Some(1));
/// ```
#[derive(Debug, Clone)]
pub struct ShuftiEngine {
    table: ShuftiTable,
    vtable: VTable,
}

impl ShuftiEngine {
    /// Creates an engine for `needle` using `backend`.
    ///
    /// Returns `None` if the backend is unavailable or the needle cannot be
    /// represented; see [`super::Shufti::new`] for the accepted byte sets.
    ///
    /// # Complexity
    ///
    /// Worst-case O(needle.len()) time.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::{shufti::ShuftiEngine, SimdBackend};
    ///
    /// let engine = ShuftiEngine::new(SimdBackend::Fallback, b" \t").unwrap();
    /// assert_eq!(engine.find(b"hello world"), Some(5));
    /// ```
    pub fn new(backend: SimdBackend, needle: &[u8]) -> Option<Self> {
        Self::with_table(ShuftiTable::new(needle)?, backend)
    }

    /// Creates an engine that can ignore ASCII letter case.
    ///
    /// When `ignore_case` is `true`, ASCII letters match either case; other
    /// bytes match exactly. When it is `false`, this behaves like [`Self::new`].
    ///
    /// Returns `None` if the backend is unavailable or the resulting byte set
    /// cannot be represented.
    ///
    /// # Complexity
    ///
    /// Worst-case O(needle.len()) time.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::{shufti::ShuftiEngine, SimdBackend};
    ///
    /// let letters = ShuftiEngine::with_case(true, SimdBackend::Fallback, b"a").unwrap();
    /// assert_eq!(letters.find(b"!A!"), Some(1));
    /// ```
    pub fn with_case(ignore_case: bool, backend: SimdBackend, needle: &[u8]) -> Option<Self> {
        Self::with_table(ShuftiTable::with_case(ignore_case, needle)?, backend)
    }

    // Move the prepared masks into the engine without rebuilding them. VTable
    // validates the backend before any callable engine can be returned.
    fn with_table(table: ShuftiTable, backend: SimdBackend) -> Option<Self> {
        Some(Self {
            table,
            vtable: VTable::new(backend)?,
        })
    }

    /// Returns the index of the first byte in `haystack` that belongs to the needle.
    ///
    /// Returns `None` if no match is found.
    ///
    /// # Complexity
    ///
    /// Worst-case O(haystack.len()) time.
    #[inline]
    pub fn find(&self, haystack: &[u8]) -> Option<usize> {
        self.vtable.search::<false>(&self.table, haystack)
    }

    /// Returns the index of the first byte in `haystack` that is not in the needle.
    ///
    /// Returns `None` if all bytes belong to the needle.
    ///
    /// # Complexity
    ///
    /// Worst-case O(haystack.len()) time.
    #[inline]
    pub fn mismatch(&self, haystack: &[u8]) -> Option<usize> {
        self.vtable.search::<true>(&self.table, haystack)
    }

    /// Returns the index of the last byte in `haystack` that belongs to the needle.
    ///
    /// Searches from the end of the slice. Returns `None` if no match is found.
    ///
    /// # Complexity
    ///
    /// Worst-case O(haystack.len()) time.
    #[inline]
    pub fn rfind(&self, haystack: &[u8]) -> Option<usize> {
        self.vtable.rsearch::<false>(&self.table, haystack)
    }

    /// Returns the index of the last byte in `haystack` that is not in the needle.
    ///
    /// Searches from the end of the slice. Returns `None` if all bytes belong
    /// to the needle.
    ///
    /// # Complexity
    ///
    /// Worst-case O(haystack.len()) time.
    #[inline]
    pub fn rmismatch(&self, haystack: &[u8]) -> Option<usize> {
        self.vtable.rsearch::<true>(&self.table, haystack)
    }

    /// Returns an iterator over the indices of bytes belonging to the needle.
    ///
    /// Indices are yielded in ascending order. Use [`.rev()`](Iterator::rev)
    /// to iterate in reverse.
    ///
    /// # Complexity
    ///
    /// Creating the iterator takes O(1) time. Fully consuming it
    /// takes O(haystack.len()) time. A single `next()` or `next_back()` call
    /// may scan all remaining input.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::{shufti::ShuftiEngine, SimdBackend};
    ///
    /// let engine = ShuftiEngine::new(SimdBackend::Fallback, b"a").unwrap();
    /// let mut matches = engine.finder(b"banana");
    /// assert_eq!(matches.next(), Some(1));
    /// assert_eq!(matches.next_back(), Some(5));
    /// assert!(matches.eq([3]));
    /// ```
    #[inline]
    pub fn finder<'a, 'h>(&'a self, haystack: &'h [u8]) -> ShuftiEngineFinder<'a, 'h> {
        ShuftiEngineFinder::new(self, haystack)
    }

    /// Returns an iterator over the indices of bytes not belonging to the needle.
    ///
    /// Indices are yielded in ascending order. Use [`.rev()`](Iterator::rev)
    /// to iterate in reverse.
    ///
    /// # Complexity
    ///
    /// Creating the iterator takes O(1) time. Fully consuming it
    /// takes O(haystack.len()) time. A single `next()` or `next_back()` call
    /// may scan all remaining input.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::{shufti::ShuftiEngine, SimdBackend};
    ///
    /// let engine = ShuftiEngine::with_case(true, SimdBackend::Fallback, b"ACGT").unwrap();
    /// assert!(engine.mismatcher(b"ac?GT!").eq([2, 5]));
    /// assert!(engine.mismatcher(b"ac?GT!").rev().eq([5, 2]));
    /// ```
    #[inline]
    pub fn mismatcher<'a, 'h>(&'a self, haystack: &'h [u8]) -> ShuftiEngineMismatcher<'a, 'h> {
        ShuftiEngineMismatcher::new(self, haystack)
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use std::{vec, vec::Vec};

    use super::ShuftiEngine;
    use crate::tests::hyperscan_needle_and_haystack;
    use crate::SimdBackend;

    #[test]
    fn find_returns_the_first_member() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"Ab").unwrap();
            // Both positions qualify; the earlier one must win.
            let mut haystack = [b'!'; 128];
            haystack[17] = b'A';
            haystack[96] = b'b';

            assert_eq!(matcher.find(&haystack), Some(17));
        }
    }

    #[test]
    fn find_recognizes_every_byte_value() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let haystack: [u8; 256] = core::array::from_fn(|index| index as u8);
            for member in 0..=255u8 {
                let matcher = ShuftiEngine::new(backend, &[member]).unwrap();
                // Each byte occurs once, at the index equal to its value.
                assert_eq!(
                    matcher.find(&haystack),
                    Some(usize::from(member)),
                    "member={member}"
                );
            }
        }
    }

    #[test]
    fn find_recognizes_members_after_group_reuse() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            // Each row h allows low nibble h, using all eight group flags.
            let mut needle: Vec<u8> = (0..8).map(|h| (h << 4) + h).collect();
            // Row 8 reuses row 0's group because both allow low nibble 0.
            needle.push(0b1000_0000);
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            for byte in 0..=255 {
                let expected = (needle.contains(&byte)).then_some(0);
                // A uniform input either qualifies everywhere or nowhere.
                assert_eq!(matcher.find(&[byte; 128]), expected, "byte={byte}");
            }
        }
    }

    #[test]
    fn find_uses_ascii_case_expansion() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::with_case(true, backend, b"A").unwrap();
            assert_eq!(matcher.find(b"!a!A!"), Some(1));
        }
    }

    #[test]
    fn find_returns_none_for_an_empty_haystack() {
        let all_bytes: Vec<u8> = (0..=255).collect();
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
                let matcher = ShuftiEngine::new(backend, needle).unwrap();
                assert_eq!(matcher.find(b""), None, "needle={needle:?}");
            }
        }
    }

    #[test]
    fn find_returns_none_for_an_empty_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"").unwrap();
            assert_eq!(matcher.find(b"abc"), None);
            // Also search all byte values, spanning multiple SIMD blocks.
            let all_bytes: Vec<u8> = (0..=255).collect();
            assert_eq!(matcher.find(&all_bytes), None);
        }
    }

    #[test]
    fn find_returns_first_position_for_a_full_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let needle: Vec<u8> = (0..=255).collect();
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            assert_eq!(matcher.find(b"abc"), Some(0));
            // Also search all byte values, spanning multiple SIMD blocks.
            assert_eq!(matcher.find(&needle), Some(0));
        }
    }

    #[test]
    fn find_ignores_matches_outside_the_slice() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[0]).unwrap();
            // Cover short inputs, vector tails, and every 64-byte alignment.
            for len in 0..=257 {
                for offset in 0..64 {
                    // Only the surrounding zeros match the needle.
                    let mut storage = vec![0; offset + len + 64];
                    let haystack = &mut storage[offset..offset + len];
                    haystack.fill(1);
                    assert_eq!(matcher.find(haystack), None, "len={len}, offset={offset}");
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn find_stays_inside_guarded_slices() {
        use crate::tests::GuardedPage;

        let mut guarded = GuardedPage::new();
        let page = guarded.as_mut_slice();
        // No members: the search must read through the whole slice.
        page.fill(1);
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[0]).unwrap();
            for len in 0..=257 {
                // Start immediately after the leading guard page.
                assert_eq!(matcher.find(&page[..len]), None, "start, len={len}");
                // End immediately before the trailing guard page.
                assert_eq!(
                    matcher.find(&page[page.len() - len..]),
                    None,
                    "end, len={len}"
                );
            }
        }
    }

    #[test]
    fn find_returns_expected_positions() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for (needle, haystack) in hyperscan_needle_and_haystack() {
                let matcher = ShuftiEngine::new(backend, &needle).unwrap();
                let expected = haystack.iter().position(|byte| needle.contains(byte));
                // Exercise every start alignment of the widest (64-byte) vector.
                let mut storage = vec![0; haystack.len() + 63];
                for offset in 0..64 {
                    let input = &mut storage[offset..offset + haystack.len()];
                    input.copy_from_slice(&haystack);
                    assert_eq!(
                        matcher.find(input),
                        expected,
                        "backend={backend:?}, needle={needle:?}, haystack={haystack:?}, offset={offset}"
                    );
                }
            }
        }
    }

    #[test]
    fn mismatch_returns_the_first_nonmember() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"Ab").unwrap();
            // Both positions qualify; the earlier one must win.
            let mut haystack = [b'A'; 128];
            haystack[17] = b'!';
            haystack[96] = b'?';

            assert_eq!(matcher.mismatch(&haystack), Some(17));
        }
    }

    #[test]
    fn mismatch_recognizes_every_byte_value() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for member in 0..=255u8 {
                let matcher = ShuftiEngine::new(backend, &[member]).unwrap();
                let mut haystack = [member; 129];
                // The only nonmember lies just beyond a 64-byte block.
                haystack[65] = member.wrapping_add(1);
                assert_eq!(matcher.mismatch(&haystack), Some(65), "member={member}");
            }
        }
    }

    #[test]
    fn mismatch_recognizes_members_after_group_reuse() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            // Each row h allows low nibble h, using all eight group flags.
            let mut needle: Vec<u8> = (0..8).map(|h| (h << 4) + h).collect();
            // Row 8 reuses row 0's group because both allow low nibble 0.
            needle.push(0b1000_0000);
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            for byte in 0..=255 {
                let expected = (!needle.contains(&byte)).then_some(0);
                // A uniform input either qualifies everywhere or nowhere.
                assert_eq!(matcher.mismatch(&[byte; 128]), expected, "byte={byte}");
            }
        }
    }

    #[test]
    fn mismatch_uses_ascii_case_expansion() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::with_case(true, backend, b"A").unwrap();
            assert_eq!(matcher.mismatch(b"aA!aA?"), Some(2));
        }
    }

    #[test]
    fn mismatch_returns_none_for_an_empty_haystack() {
        let all_bytes: Vec<u8> = (0..=255).collect();
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
                let matcher = ShuftiEngine::new(backend, needle).unwrap();
                assert_eq!(matcher.mismatch(b""), None, "needle={needle:?}");
            }
        }
    }

    #[test]
    fn mismatch_returns_first_position_for_an_empty_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"").unwrap();
            assert_eq!(matcher.mismatch(b"abc"), Some(0));
            // Also search all byte values, spanning multiple SIMD blocks.
            let all_bytes: Vec<u8> = (0..=255).collect();
            assert_eq!(matcher.mismatch(&all_bytes), Some(0));
        }
    }

    #[test]
    fn mismatch_returns_none_for_a_full_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let needle: Vec<u8> = (0..=255).collect();
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            assert_eq!(matcher.mismatch(b"abc"), None);
            // Also search all byte values, spanning multiple SIMD blocks.
            assert_eq!(matcher.mismatch(&needle), None);
        }
    }

    #[test]
    fn mismatch_ignores_nonmembers_outside_the_slice() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[1]).unwrap();
            // Cover short inputs, vector tails, and every 64-byte alignment.
            for len in 0..=257 {
                for offset in 0..64 {
                    // Only the surrounding zeros are nonmembers.
                    let mut storage = vec![0; offset + len + 64];
                    let haystack = &mut storage[offset..offset + len];
                    haystack.fill(1);
                    assert_eq!(
                        matcher.mismatch(haystack),
                        None,
                        "len={len}, offset={offset}"
                    );
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn mismatch_stays_inside_guarded_slices() {
        use crate::tests::GuardedPage;

        let mut guarded = GuardedPage::new();
        let page = guarded.as_mut_slice();
        // No nonmembers: the search must read through the whole slice.
        page.fill(1);
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[1]).unwrap();
            for len in 0..=257 {
                // Start immediately after the leading guard page.
                assert_eq!(matcher.mismatch(&page[..len]), None, "start, len={len}");
                // End immediately before the trailing guard page.
                assert_eq!(
                    matcher.mismatch(&page[page.len() - len..]),
                    None,
                    "end, len={len}"
                );
            }
        }
    }

    #[test]
    fn mismatch_returns_expected_positions() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for (needle, haystack) in hyperscan_needle_and_haystack() {
                let matcher = ShuftiEngine::new(backend, &needle).unwrap();
                let expected = haystack.iter().position(|byte| !needle.contains(byte));
                // Exercise every start alignment of the widest (64-byte) vector.
                let mut storage = vec![0; haystack.len() + 63];
                for offset in 0..64 {
                    let input = &mut storage[offset..offset + haystack.len()];
                    input.copy_from_slice(&haystack);
                    assert_eq!(
                        matcher.mismatch(input),
                        expected,
                        "backend={backend:?}, needle={needle:?}, haystack={haystack:?}, offset={offset}"
                    );
                }
            }
        }
    }

    #[test]
    fn rfind_returns_the_last_member() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"Ab").unwrap();
            // Both positions qualify; the later one must win.
            let mut haystack = [b'!'; 128];
            haystack[17] = b'A';
            haystack[96] = b'b';

            assert_eq!(matcher.rfind(&haystack), Some(96));
        }
    }

    #[test]
    fn rfind_recognizes_every_byte_value() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let haystack: [u8; 256] = core::array::from_fn(|index| index as u8);
            for member in 0..=255u8 {
                let matcher = ShuftiEngine::new(backend, &[member]).unwrap();
                // Each byte occurs once, at the index equal to its value.
                assert_eq!(
                    matcher.rfind(&haystack),
                    Some(usize::from(member)),
                    "member={member}"
                );
            }
        }
    }

    #[test]
    fn rfind_recognizes_members_after_group_reuse() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            // Each row h allows low nibble h, using all eight group flags.
            let mut needle: Vec<u8> = (0..8).map(|h| (h << 4) + h).collect();
            // Row 8 reuses row 0's group because both allow low nibble 0.
            needle.push(0b1000_0000);
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            for byte in 0..=255 {
                let expected = (needle.contains(&byte)).then_some(127);
                // A uniform input either qualifies everywhere or nowhere.
                assert_eq!(matcher.rfind(&[byte; 128]), expected, "byte={byte}");
            }
        }
    }

    #[test]
    fn rfind_uses_ascii_case_expansion() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::with_case(true, backend, b"A").unwrap();
            assert_eq!(matcher.rfind(b"!A!a!"), Some(3));
        }
    }

    #[test]
    fn rfind_returns_none_for_an_empty_haystack() {
        let all_bytes: Vec<u8> = (0..=255).collect();
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
                let matcher = ShuftiEngine::new(backend, needle).unwrap();
                assert_eq!(matcher.rfind(b""), None, "needle={needle:?}");
            }
        }
    }

    #[test]
    fn rfind_returns_none_for_an_empty_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"").unwrap();
            assert_eq!(matcher.rfind(b"abc"), None);
            // Also search all byte values, spanning multiple SIMD blocks.
            let all_bytes: Vec<u8> = (0..=255).collect();
            assert_eq!(matcher.rfind(&all_bytes), None);
        }
    }

    #[test]
    fn rfind_returns_last_position_for_a_full_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let needle: Vec<u8> = (0..=255).collect();
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            assert_eq!(matcher.rfind(b"abc"), Some(2));
            // Also search all byte values, spanning multiple SIMD blocks.
            assert_eq!(matcher.rfind(&needle), Some(255));
        }
    }

    #[test]
    fn rfind_ignores_matches_outside_the_slice() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[0]).unwrap();
            // Cover short inputs, vector tails, and every 64-byte alignment.
            for len in 0..=257 {
                for offset in 0..64 {
                    // Only the surrounding zeros match the needle.
                    let mut storage = vec![0; offset + len + 64];
                    let haystack = &mut storage[offset..offset + len];
                    haystack.fill(1);
                    assert_eq!(matcher.rfind(haystack), None, "len={len}, offset={offset}");
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn rfind_stays_inside_guarded_slices() {
        use crate::tests::GuardedPage;

        let mut guarded = GuardedPage::new();
        let page = guarded.as_mut_slice();
        // No members: the search must read through the whole slice.
        page.fill(1);
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[0]).unwrap();
            for len in 0..=257 {
                // Start immediately after the leading guard page.
                assert_eq!(matcher.rfind(&page[..len]), None, "start, len={len}");
                // End immediately before the trailing guard page.
                assert_eq!(
                    matcher.rfind(&page[page.len() - len..]),
                    None,
                    "end, len={len}"
                );
            }
        }
    }

    #[test]
    fn rfind_returns_expected_positions() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for (needle, haystack) in hyperscan_needle_and_haystack() {
                let matcher = ShuftiEngine::new(backend, &needle).unwrap();
                let expected = haystack.iter().rposition(|byte| needle.contains(byte));
                // Exercise every start alignment of the widest (64-byte) vector.
                let mut storage = vec![0; haystack.len() + 63];
                for offset in 0..64 {
                    let input = &mut storage[offset..offset + haystack.len()];
                    input.copy_from_slice(&haystack);
                    assert_eq!(
                        matcher.rfind(input),
                        expected,
                        "backend={backend:?}, needle={needle:?}, haystack={haystack:?}, offset={offset}"
                    );
                }
            }
        }
    }

    #[test]
    fn rmismatch_returns_the_last_nonmember() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"Ab").unwrap();
            // Both positions qualify; the later one must win.
            let mut haystack = [b'A'; 128];
            haystack[17] = b'!';
            haystack[96] = b'?';

            assert_eq!(matcher.rmismatch(&haystack), Some(96));
        }
    }

    #[test]
    fn rmismatch_recognizes_every_byte_value() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for member in 0..=255u8 {
                let matcher = ShuftiEngine::new(backend, &[member]).unwrap();
                let mut haystack = [member; 129];
                // The only nonmember lies just beyond a 64-byte block.
                haystack[65] = member.wrapping_add(1);
                assert_eq!(matcher.rmismatch(&haystack), Some(65), "member={member}");
            }
        }
    }

    #[test]
    fn rmismatch_recognizes_members_after_group_reuse() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            // Each row h allows low nibble h, using all eight group flags.
            let mut needle: Vec<u8> = (0..8).map(|h| (h << 4) + h).collect();
            // Row 8 reuses row 0's group because both allow low nibble 0.
            needle.push(0b1000_0000);
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            for byte in 0..=255 {
                let expected = (!needle.contains(&byte)).then_some(127);
                // A uniform input either qualifies everywhere or nowhere.
                assert_eq!(matcher.rmismatch(&[byte; 128]), expected, "byte={byte}");
            }
        }
    }

    #[test]
    fn rmismatch_uses_ascii_case_expansion() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::with_case(true, backend, b"A").unwrap();
            assert_eq!(matcher.rmismatch(b"?Aa!Aa"), Some(3));
        }
    }

    #[test]
    fn rmismatch_returns_none_for_an_empty_haystack() {
        let all_bytes: Vec<u8> = (0..=255).collect();
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
                let matcher = ShuftiEngine::new(backend, needle).unwrap();
                assert_eq!(matcher.rmismatch(b""), None, "needle={needle:?}");
            }
        }
    }

    #[test]
    fn rmismatch_returns_last_position_for_an_empty_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"").unwrap();
            assert_eq!(matcher.rmismatch(b"abc"), Some(2));
            // Also search all byte values, spanning multiple SIMD blocks.
            let all_bytes: Vec<u8> = (0..=255).collect();
            assert_eq!(matcher.rmismatch(&all_bytes), Some(255));
        }
    }

    #[test]
    fn rmismatch_returns_none_for_a_full_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let needle: Vec<u8> = (0..=255).collect();
            let matcher = ShuftiEngine::new(backend, &needle).unwrap();
            assert_eq!(matcher.rmismatch(b"abc"), None);
            // Also search all byte values, spanning multiple SIMD blocks.
            assert_eq!(matcher.rmismatch(&needle), None);
        }
    }

    #[test]
    fn rmismatch_ignores_nonmembers_outside_the_slice() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[1]).unwrap();
            // Cover short inputs, vector tails, and every 64-byte alignment.
            for len in 0..=257 {
                for offset in 0..64 {
                    // Only the surrounding zeros are nonmembers.
                    let mut storage = vec![0; offset + len + 64];
                    let haystack = &mut storage[offset..offset + len];
                    haystack.fill(1);
                    assert_eq!(
                        matcher.rmismatch(haystack),
                        None,
                        "len={len}, offset={offset}"
                    );
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn rmismatch_stays_inside_guarded_slices() {
        use crate::tests::GuardedPage;

        let mut guarded = GuardedPage::new();
        let page = guarded.as_mut_slice();
        // No nonmembers: the search must read through the whole slice.
        page.fill(1);
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, &[1]).unwrap();
            for len in 0..=257 {
                // Start immediately after the leading guard page.
                assert_eq!(matcher.rmismatch(&page[..len]), None, "start, len={len}");
                // End immediately before the trailing guard page.
                assert_eq!(
                    matcher.rmismatch(&page[page.len() - len..]),
                    None,
                    "end, len={len}"
                );
            }
        }
    }

    #[test]
    fn rmismatch_returns_expected_positions() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            for (needle, haystack) in hyperscan_needle_and_haystack() {
                let matcher = ShuftiEngine::new(backend, &needle).unwrap();
                let expected = haystack.iter().rposition(|byte| !needle.contains(byte));
                // Exercise every start alignment of the widest (64-byte) vector.
                let mut storage = vec![0; haystack.len() + 63];
                for offset in 0..64 {
                    let input = &mut storage[offset..offset + haystack.len()];
                    input.copy_from_slice(&haystack);
                    assert_eq!(
                        matcher.rmismatch(input),
                        expected,
                        "backend={backend:?}, needle={needle:?}, haystack={haystack:?}, offset={offset}"
                    );
                }
            }
        }
    }

    #[test]
    fn finder_uses_the_engines_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"Ab").unwrap();
            assert!(matcher.finder(b"!A?b!").eq([1, 3]));
        }
    }

    #[test]
    fn mismatcher_uses_the_engines_needle() {
        for backend in SimdBackend::backends().filter(SimdBackend::is_available) {
            let matcher = ShuftiEngine::new(backend, b"Ab").unwrap();
            assert!(matcher.mismatcher(b"!A?b!").eq([0, 2, 4]));
        }
    }
}