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
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
#[cfg(target_has_atomic = "ptr")]
use core::sync::atomic::{AtomicPtr, Ordering};

mod iter;

pub use self::iter::{TruffleFinder, TruffleMismatcher};

use super::{arch, TruffleTable};
use crate::SimdBackend;

/// A matcher for a set of bytes.
///
/// # Examples
///
/// ```
/// use bytesetscan::truffle::Truffle;
///
/// let delimiters = Truffle::new(b",;");
/// assert_eq!(delimiters.find(b"one;two,three"), Some(3));
/// assert_eq!(delimiters.rfind(b"one;two,three"), Some(7));
/// ```
#[derive(Debug, Clone)]
pub struct Truffle {
    table: TruffleTable,
}

impl Truffle {
    /// Creates a matcher for the bytes in `needle`.
    ///
    /// An empty needle matches no bytes. Duplicate bytes and their order do not
    /// affect matching.
    ///
    /// # Complexity
    ///
    /// Worst-case O(needle.len()) time.
    pub fn new(needle: &[u8]) -> Self {
        Self {
            table: TruffleTable::new(needle),
        }
    }

    /// Creates a matcher 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`].
    ///
    /// # Complexity
    ///
    /// Worst-case O(needle.len()) time.
    pub fn with_case(ignore_case: bool, needle: &[u8]) -> Self {
        Self {
            table: TruffleTable::with_case(ignore_case, needle),
        }
    }

    /// 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.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::truffle::Truffle;
    ///
    /// let whitespace = Truffle::new(b" \t\r\n");
    /// assert_eq!(whitespace.find(b"hello world"), Some(5));
    /// assert_eq!(whitespace.find(b"hello"), None);
    /// ```
    #[inline]
    pub fn find(&self, haystack: &[u8]) -> Option<usize> {
        self.search::<false>(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.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::truffle::Truffle;
    ///
    /// let bases = Truffle::with_case(true, b"ACGTU");
    /// assert_eq!(bases.mismatch(b"acGU?"), Some(4));
    /// assert_eq!(bases.mismatch(b"acGU"), None);
    /// ```
    #[inline]
    pub fn mismatch(&self, haystack: &[u8]) -> Option<usize> {
        self.search::<true>(haystack)
    }

    // Automatic searches cache kernel pointers whenever the target supports
    // pointer-sized atomics, independently of std and the target architecture.
    // SimdBackend handles availability: std builds can use runtime checks, while
    // no_std builds use compilation target features. Both choices can be cached.
    #[inline(always)]
    fn search<const REVERT: bool>(&self, haystack: &[u8]) -> Option<usize> {
        let lower = self.table.lower();
        let upper = self.table.upper();
        #[cfg(target_has_atomic = "ptr")]
        {
            // Generic instantiations share local statics, so find and mismatch
            // still need separate caches. Only function pointers are published;
            // Relaxed ordering suffices because no other mutable state is shared.
            static FIND: AtomicPtr<()> = AtomicPtr::new(detect::<false> as *mut ());
            static MISMATCH: AtomicPtr<()> = AtomicPtr::new(detect::<true> as *mut ());

            #[cold]
            fn detect<const REVERT: bool>(
                lower: &[u8; 16],
                upper: &[u8; 16],
                haystack: &[u8],
            ) -> Option<usize> {
                let search = arch::search_fn::<REVERT>(SimdBackend::new());
                let caching = if REVERT { &MISMATCH } else { &FIND };
                caching.store(search as *mut (), Ordering::Relaxed);
                // SAFETY: SimdBackend::new selected a supported backend.
                // Each entry point handles all slice lengths.
                unsafe { search(lower, upper, haystack) }
            }

            let cached = if REVERT { &MISMATCH } else { &FIND };
            // SAFETY: each cached pointer has the SearchFn signature and is
            // either the initializer or a kernel selected for a supported backend.
            // Every entry point handles its own short-input path.
            unsafe {
                let search: arch::SearchFn = core::mem::transmute(cached.load(Ordering::Relaxed));
                search(lower, upper, haystack)
            }
        }
        #[cfg(not(target_has_atomic = "ptr"))]
        {
            // AtomicPtr is unavailable on this target. Select a supported kernel
            // for this call without publishing a shared function pointer.
            let search = arch::search_fn::<REVERT>(SimdBackend::new());
            // SAFETY: SimdBackend::new selected a supported backend; its entry
            // point handles all slice lengths, including empty slices.
            unsafe { search(lower, upper, 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.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::truffle::Truffle;
    ///
    /// let whitespace = Truffle::new(b" \t");
    /// assert_eq!(whitespace.rfind(b"one two\tthree"), Some(7));
    /// assert_eq!(whitespace.rfind(b"word"), None);
    /// ```
    #[inline]
    pub fn rfind(&self, haystack: &[u8]) -> Option<usize> {
        self.rsearch::<false>(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.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::truffle::Truffle;
    ///
    /// let whitespace = Truffle::new(b" \t");
    /// assert_eq!(whitespace.rmismatch(b"one two \t"), Some(6));
    /// assert_eq!(whitespace.rmismatch(b" \t"), None);
    /// ```
    #[inline]
    pub fn rmismatch(&self, haystack: &[u8]) -> Option<usize> {
        self.rsearch::<true>(haystack)
    }

    #[inline(always)]
    fn rsearch<const REVERT: bool>(&self, haystack: &[u8]) -> Option<usize> {
        let lower = self.table.lower();
        let upper = self.table.upper();
        #[cfg(target_has_atomic = "ptr")]
        {
            // Keep the two operations separate even inside this generic function.
            // Concurrent initializations publish the same supported kernel, and
            // SimdBackend::new supplies the choice. Only the pointer needs publishing.
            static RFIND: AtomicPtr<()> = AtomicPtr::new(detect::<false> as *mut ());
            static RMISMATCH: AtomicPtr<()> = AtomicPtr::new(detect::<true> as *mut ());

            #[cold]
            fn detect<const REVERT: bool>(
                lower: &[u8; 16],
                upper: &[u8; 16],
                haystack: &[u8],
            ) -> Option<usize> {
                let search = arch::rsearch_fn::<REVERT>(SimdBackend::new());
                let caching = if REVERT { &RMISMATCH } else { &RFIND };
                caching.store(search as *mut (), Ordering::Relaxed);
                // SAFETY: SimdBackend::new selected a supported backend.
                // Each entry point handles all slice lengths.
                unsafe { search(lower, upper, haystack) }
            }

            let cached = if REVERT { &RMISMATCH } else { &RFIND };
            // SAFETY: each cached pointer has the SearchFn signature and is
            // either the initializer or a kernel selected for a supported backend.
            // Every entry point handles its own short-input path.
            unsafe {
                let search: arch::SearchFn = core::mem::transmute(cached.load(Ordering::Relaxed));
                search(lower, upper, haystack)
            }
        }
        #[cfg(not(target_has_atomic = "ptr"))]
        {
            // Use the same selection on targets without pointer-sized atomics,
            // but keep the function pointer local instead of caching it.
            let search = arch::rsearch_fn::<REVERT>(SimdBackend::new());
            // SAFETY: SimdBackend::new selected a supported backend; its entry
            // point handles all slice lengths, including empty slices.
            unsafe { search(lower, upper, 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::truffle::Truffle;
    ///
    /// let letters = Truffle::new(b"a");
    /// let mut matches = letters.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]) -> TruffleFinder<'a, 'h> {
        TruffleFinder::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::truffle::Truffle;
    ///
    /// let bases = Truffle::new(b"ACGT");
    /// assert!(bases.mismatcher(b"AC?GT!").eq([2, 5]));
    /// assert!(bases.mismatcher(b"AC?GT!").rev().eq([5, 2]));
    /// ```
    #[inline]
    pub fn mismatcher<'a, 'h>(&'a self, haystack: &'h [u8]) -> TruffleMismatcher<'a, 'h> {
        TruffleMismatcher::new(self, haystack)
    }

    /// Returns an iterator over the needle in ascending byte order.
    ///
    /// This is the matching byte set, not the original constructor input.
    /// Each byte is yielded once. With ASCII case-insensitive matching, both
    /// cases of each letter are included.
    ///
    /// # Complexity
    ///
    /// Creating the iterator takes O(1) time. Full iteration checks
    /// the 256 possible byte values, so its time is O(1), independent of the
    /// original needle length.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytesetscan::truffle::Truffle;
    ///
    /// let letters = Truffle::with_case(true, b"aAa");
    /// assert!(letters.needle().eq(b"Aa".iter().copied()));
    /// ```
    pub fn needle(&self) -> impl Iterator<Item = u8> + '_ {
        self.table.needle()
    }
}

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

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

    use super::Truffle;
    use crate::tests::hyperscan_needle_and_haystack;

    #[test]
    fn find_returns_the_first_member() {
        let matcher = Truffle::new(b"Ab");
        // 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() {
        let haystack: [u8; 256] = core::array::from_fn(|index| index as u8);
        for member in 0..=255u8 {
            let matcher = Truffle::new(&[member]);
            // 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_distinguishes_members_of_a_sparse_set() {
        // h << 4 fills the high nibble; adding h fills the low nibble.
        // These isolated members span the whole byte range.
        let needle: Vec<u8> = (0..16).map(|h| (h << 4) + h).collect();
        let matcher = Truffle::new(&needle);
        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_distinguishes_nonmembers_of_a_dense_set() {
        // Exclude bytes whose high and low nibbles are equal.
        let needle: Vec<u8> = (0..=255u8)
            .filter(|byte| byte >> 4 != byte & 0b00001111)
            .collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::with_case(true, b"A");
        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 needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
            let matcher = Truffle::new(needle);
            assert_eq!(matcher.find(b""), None, "needle={needle:?}");
        }
    }

    #[test]
    fn find_returns_none_for_an_empty_needle() {
        let matcher = Truffle::new(b"");
        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() {
        let needle: Vec<u8> = (0..=255).collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::new(&[0]);
        // 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);
        let matcher = Truffle::new(&[0]);
        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 (needle, haystack) in hyperscan_needle_and_haystack() {
            let matcher = Truffle::new(&needle);
            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,
                    "needle={needle:?}, haystack={haystack:?}, offset={offset}"
                );
            }
        }
    }

    #[test]
    fn mismatch_returns_the_first_nonmember() {
        let matcher = Truffle::new(b"Ab");
        // 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 member in 0..=255u8 {
            let matcher = Truffle::new(&[member]);
            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_distinguishes_members_of_a_sparse_set() {
        // h << 4 fills the high nibble; adding h fills the low nibble.
        // These isolated members span the whole byte range.
        let needle: Vec<u8> = (0..16).map(|h| (h << 4) + h).collect();
        let matcher = Truffle::new(&needle);
        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_distinguishes_nonmembers_of_a_dense_set() {
        // Exclude bytes whose high and low nibbles are equal.
        let needle: Vec<u8> = (0..=255u8)
            .filter(|byte| byte >> 4 != byte & 0b00001111)
            .collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::with_case(true, b"A");
        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 needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
            let matcher = Truffle::new(needle);
            assert_eq!(matcher.mismatch(b""), None, "needle={needle:?}");
        }
    }

    #[test]
    fn mismatch_returns_first_position_for_an_empty_needle() {
        let matcher = Truffle::new(b"");
        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() {
        let needle: Vec<u8> = (0..=255).collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::new(&[1]);
        // 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);
        let matcher = Truffle::new(&[1]);
        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 (needle, haystack) in hyperscan_needle_and_haystack() {
            let matcher = Truffle::new(&needle);
            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,
                    "needle={needle:?}, haystack={haystack:?}, offset={offset}"
                );
            }
        }
    }

    #[test]
    fn rfind_returns_the_last_member() {
        let matcher = Truffle::new(b"Ab");
        // 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() {
        let haystack: [u8; 256] = core::array::from_fn(|index| index as u8);
        for member in 0..=255u8 {
            let matcher = Truffle::new(&[member]);
            // 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_distinguishes_members_of_a_sparse_set() {
        // h << 4 fills the high nibble; adding h fills the low nibble.
        // These isolated members span the whole byte range.
        let needle: Vec<u8> = (0..16).map(|h| (h << 4) + h).collect();
        let matcher = Truffle::new(&needle);
        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_distinguishes_nonmembers_of_a_dense_set() {
        // Exclude bytes whose high and low nibbles are equal.
        let needle: Vec<u8> = (0..=255u8)
            .filter(|byte| byte >> 4 != byte & 0b00001111)
            .collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::with_case(true, b"A");
        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 needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
            let matcher = Truffle::new(needle);
            assert_eq!(matcher.rfind(b""), None, "needle={needle:?}");
        }
    }

    #[test]
    fn rfind_returns_none_for_an_empty_needle() {
        let matcher = Truffle::new(b"");
        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() {
        let needle: Vec<u8> = (0..=255).collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::new(&[0]);
        // 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);
        let matcher = Truffle::new(&[0]);
        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 (needle, haystack) in hyperscan_needle_and_haystack() {
            let matcher = Truffle::new(&needle);
            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,
                    "needle={needle:?}, haystack={haystack:?}, offset={offset}"
                );
            }
        }
    }

    #[test]
    fn rmismatch_returns_the_last_nonmember() {
        let matcher = Truffle::new(b"Ab");
        // 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 member in 0..=255u8 {
            let matcher = Truffle::new(&[member]);
            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_distinguishes_members_of_a_sparse_set() {
        // h << 4 fills the high nibble; adding h fills the low nibble.
        // These isolated members span the whole byte range.
        let needle: Vec<u8> = (0..16).map(|h| (h << 4) + h).collect();
        let matcher = Truffle::new(&needle);
        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_distinguishes_nonmembers_of_a_dense_set() {
        // Exclude bytes whose high and low nibbles are equal.
        let needle: Vec<u8> = (0..=255u8)
            .filter(|byte| byte >> 4 != byte & 0b00001111)
            .collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::with_case(true, b"A");
        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 needle in [b"".as_slice(), b"a", all_bytes.as_slice()] {
            let matcher = Truffle::new(needle);
            assert_eq!(matcher.rmismatch(b""), None, "needle={needle:?}");
        }
    }

    #[test]
    fn rmismatch_returns_last_position_for_an_empty_needle() {
        let matcher = Truffle::new(b"");
        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() {
        let needle: Vec<u8> = (0..=255).collect();
        let matcher = Truffle::new(&needle);
        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() {
        let matcher = Truffle::new(&[1]);
        // 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);
        let matcher = Truffle::new(&[1]);
        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 (needle, haystack) in hyperscan_needle_and_haystack() {
            let matcher = Truffle::new(&needle);
            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,
                    "needle={needle:?}, haystack={haystack:?}, offset={offset}"
                );
            }
        }
    }

    #[test]
    fn finder_uses_the_matchers_needle() {
        let matcher = Truffle::new(b"Ab");
        assert!(matcher.finder(b"!A?b!").eq([1, 3]));
    }

    #[test]
    fn mismatcher_uses_the_matchers_needle() {
        let matcher = Truffle::new(b"Ab");
        assert!(matcher.mismatcher(b"!A?b!").eq([0, 2, 4]));
    }
}