grippo 0.1.1

Parse, match and scrub data at scale.
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
// Project:   grippo
// File:      src/strmatch/plan.rs
// Purpose:   Plan enum + match-time dispatch for strmatch
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The `Plan` chosen by the classifier and the match dispatch
//! that fires it on a haystack.
//!
//! The variants -- `LiteralOnly` / `Shape` / `Meta` / `Backtrack` -- map to
//! the public [`super::MatcherTier`]. `LineEnd` wraps one of the first three
//! to read `$` as Java's. Match-time dispatch is a single `match` per call.
//! Each arm is one or two instructions for the literal and shape tiers.

use aho_corasick::AhoCorasick;
use regex_automata::util::captures::GroupInfo;
use regex_automata::util::iter::Searcher;
use regex_automata::util::primitives::PatternID;
use regex_automata::{Input, meta};

use super::Match;
use super::dialect::final_terminator;

/// Where in the haystack a match must occur.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Anchor {
    /// `/foo/` -- anywhere in the haystack.
    Anywhere,
    /// `/^foo/` -- match must start at byte 0.
    AtStart,
    /// `/foo$/` -- match must end at `hay.len()`.
    AtEnd,
    /// `/^foo$/` -- match must cover the whole haystack.
    Exact,
}

/// Up-to-3-byte set, used for `[xy]` and `[xyz]` shape patterns. `n` is the
/// live count, and bytes past it are zero.
#[derive(Debug, Clone, Copy)]
pub(super) struct SmallByteSet {
    bytes: [u8; 3],
    n: u8,
}

impl SmallByteSet {
    /// `None` unless `src` holds 1 to 3 bytes.
    pub(super) fn new(src: &[u8]) -> Option<Self> {
        let n = match src.len() {
            1 => 1,
            2 => 2,
            3 => 3,
            _ => return None,
        };
        let mut bytes = [0_u8; 3];
        bytes[..src.len()].copy_from_slice(src);
        Some(Self { bytes, n })
    }

    #[inline]
    pub(super) fn contains_any_in(self, hay: &[u8]) -> Option<usize> {
        match self.n {
            1 => memchr::memchr(self.bytes[0], hay),
            2 => memchr::memchr2(self.bytes[0], self.bytes[1], hay),
            3 => memchr::memchr3(self.bytes[0], self.bytes[1], self.bytes[2], hay),
            _ => None,
        }
    }

    #[inline]
    pub(super) const fn n(self) -> u8 {
        self.n
    }

    #[inline]
    pub(super) const fn byte(self, i: usize) -> u8 {
        self.bytes[i]
    }
}

/// One-of-N byte-level shape that we can dispatch without invoking the
/// regex engine.
///
/// `Contains(Finder)` is boxed because the `memmem::Finder` carries
/// pre-computed search tables that can be hundreds of bytes. The other
/// variants are small. Boxing keeps `ShapeOp` itself one cache line so
/// dispatch doesn't pay for cold variant data.
#[derive(Debug, Clone)]
pub(super) enum ShapeOp {
    /// `/x/` -- single byte, anywhere.
    ContainsByte(u8),
    /// `/[xy]/` or `/[xyz]/`.
    ByteSet(SmallByteSet),
    /// `/foo/` -- multi-byte literal, anywhere. Pre-compiled needle.
    Contains(Box<memchr::memmem::Finder<'static>>),
    /// `/^foo/` -- anchored at start.
    StartsWith(Box<[u8]>),
    /// `/foo$/` -- anchored at end.
    EndsWith(Box<[u8]>),
    /// `/^foo$/` -- must cover the whole haystack.
    ExactMatch(Box<[u8]>),
}

/// The dispatch plan picked by the classifier.
///
/// `AhoCorasick` and `meta::Regex` are large structures (each carries
/// internal heap allocations + several enums in the hundreds of bytes).
/// Boxing them keeps `Plan` itself one cache line -- the Shape variant
/// stays inline because it's used directly on the hottest path.
pub(super) enum Plan {
    /// AC over a finite literal set with optional uniform anchor.
    /// Regex engine never runs at match time.
    ///
    /// `literals` + `case_insensitive` are kept so `StrMatcherSet`
    /// can fold them into a cross-pattern merged AC without
    /// re-parsing.
    LiteralOnly {
        ac: Box<AhoCorasick>,
        anchor: Anchor,
        literals: Box<[Box<[u8]>]>,
        case_insensitive: bool,
    },

    /// Shape tier: single-pattern direct byte dispatch.
    Shape(ShapeOp),

    /// Fall-through: the regex-automata meta engine handles
    /// everything we couldn't reduce. Boxed for `Plan` size discipline.
    Meta(Box<meta::Regex>),

    /// A pattern the linear engine refuses, lookaround or a backreference.
    /// A search that passes fancy-regex's backtracking limit is no match.
    #[cfg(feature = "strmatch-backtracking")]
    Backtrack(Box<fancy_regex::Regex>),

    /// A pattern with a `$` read as Java's.
    LineEnd(Box<LineEnd>),
}

/// Java's `$`: the end of the haystack, or just before a line terminator that
/// ends it. A haystack that ends in none runs `inner`, where `$` is the end.
pub(super) struct LineEnd {
    pub(super) inner: Plan,
    pub(super) java: JavaEnd,
}

/// How a haystack that ends in a line terminator is searched.
pub(super) enum JavaEnd {
    /// An end-anchored literal or literal set, tried at both places `$`
    /// holds. `exact` also anchors it at the start.
    Literals {
        literals: Box<[Box<[u8]>]>,
        case_insensitive: bool,
        exact: bool,
    },
    /// The pattern with each `$` rewritten. `find` drops the pattern's groups
    /// and marks the terminator a `$` stepped over in group 1. `groups` keeps
    /// them and marks it in a last group the user never sees, `None` when
    /// `find` has the same layout. `layout` is the room a `Captures` needs.
    Regex {
        find: meta::Regex,
        groups: Option<meta::Regex>,
        layout: GroupInfo,
    },
}

impl Plan {
    /// True if the haystack contains a match per this plan.
    #[inline]
    pub(super) fn is_match(&self, hay: &[u8]) -> bool {
        match self {
            Self::LiteralOnly {
                ac,
                anchor,
                literals,
                case_insensitive,
            } => match_set_is(ac, *anchor, literals, *case_insensitive, hay),
            Self::Shape(op) => match_shape_is(op, hay),
            Self::Meta(r) => r.is_match(hay),
            #[cfg(feature = "strmatch-backtracking")]
            Self::Backtrack(r) => r.is_match(hay).unwrap_or(false),
            Self::LineEnd(le) => le.is_match(hay),
        }
    }

    /// Find the first match per this plan, returning byte offsets.
    #[inline]
    pub(super) fn find(&self, hay: &[u8]) -> Option<Match> {
        match self {
            Self::LiteralOnly {
                ac,
                anchor,
                literals,
                case_insensitive,
            } => match_set_find(ac, *anchor, literals, *case_insensitive, hay),
            Self::Shape(op) => match_shape_find(op, hay),
            Self::Meta(r) => r.find(hay).map(|m| Match {
                start: m.start(),
                end: m.end(),
            }),
            #[cfg(feature = "strmatch-backtracking")]
            Self::Backtrack(r) => r.find(hay).ok().flatten().map(|m| Match {
                start: m.start(),
                end: m.end(),
            }),
            Self::LineEnd(le) => {
                final_terminator(hay).map_or_else(|| le.inner.find(hay), |t| le.find_at(hay, t, 0))
            }
        }
    }

    /// The leftmost match that starts at `from` or later. The haystack before
    /// `from` is still read by `^`, `\b` and lookbehind.
    pub(super) fn find_from(&self, hay: &[u8], from: usize) -> Result<Option<Match>, Limit> {
        if from > hay.len() {
            return Ok(None);
        }
        let found = match self {
            Self::LiteralOnly {
                ac,
                anchor,
                literals,
                case_insensitive,
            } => match anchor {
                Anchor::Anywhere => ac
                    .find(aho_corasick::Input::new(hay).span(from..hay.len()))
                    .map(|m| Match {
                        start: m.start(),
                        end: m.end(),
                    }),
                Anchor::AtStart => (from == 0)
                    .then(|| match_set_find(ac, *anchor, literals, *case_insensitive, hay))
                    .flatten(),
                Anchor::AtEnd | Anchor::Exact => {
                    match_set_end(literals, *case_insensitive, *anchor, hay, from)
                }
            },
            Self::Shape(op) => match op {
                ShapeOp::StartsWith(_) | ShapeOp::ExactMatch(_) if from > 0 => None,
                ShapeOp::StartsWith(_) | ShapeOp::ExactMatch(_) | ShapeOp::EndsWith(_) => {
                    match_shape_find(op, hay).filter(|m| m.start >= from)
                }
                ShapeOp::ContainsByte(_) | ShapeOp::ByteSet(_) | ShapeOp::Contains(_) => {
                    match_shape_find(op, &hay[from..]).map(|m| Match {
                        start: m.start + from,
                        end: m.end + from,
                    })
                }
            },
            Self::Meta(r) => r
                .search(&Input::new(hay).span(from..hay.len()))
                .map(|m| Match {
                    start: m.start(),
                    end: m.end(),
                }),
            #[cfg(feature = "strmatch-backtracking")]
            Self::Backtrack(r) => r
                .find_from_pos(hay, from)
                .map_err(|_| Limit)?
                .map(|m| Match {
                    start: m.start(),
                    end: m.end(),
                }),
            Self::LineEnd(le) => match final_terminator(hay) {
                None => le.inner.find_from(hay, from)?,
                Some(t) => le.find_at(hay, t, from),
            },
        };
        Ok(found)
    }

    /// As [`Self::for_each_match`], with Java's `Matcher.find` rule for empty
    /// matches: one may start where the last match ended, and the search after
    /// one resumes a character on.
    pub(super) fn for_each_match_java(&self, hay: &[u8], mut f: impl FnMut(Match) -> bool) -> bool {
        let mut at = 0;
        while at <= hay.len() {
            let Ok(found) = self.find_from(hay, at) else {
                return false;
            };
            let Some(m) = found else { break };
            if !f(m) {
                break;
            }
            at = resume(hay, m);
        }
        true
    }

    /// Call `f` on every non-overlapping match in order until it returns
    /// `false`. Returns `false` when the engine gave up part way, which only
    /// the backtracking tier does.
    pub(super) fn for_each_match(&self, hay: &[u8], mut f: impl FnMut(Match) -> bool) -> bool {
        match self {
            Self::LiteralOnly {
                ac,
                anchor,
                literals,
                case_insensitive,
            } => {
                if *anchor == Anchor::Anywhere {
                    each_set(ac, hay, &mut f);
                } else if let Some(m) =
                    match_set_find(ac, *anchor, literals, *case_insensitive, hay)
                {
                    f(m);
                }
            }
            Self::Shape(op) => each_shape(op, hay, &mut f),
            Self::Meta(r) => {
                for m in r.find_iter(hay) {
                    if !f(Match {
                        start: m.start(),
                        end: m.end(),
                    }) {
                        break;
                    }
                }
            }
            #[cfg(feature = "strmatch-backtracking")]
            Self::Backtrack(r) => {
                for m in r.find_iter(hay) {
                    let Ok(m) = m else { return false };
                    if !f(Match {
                        start: m.start(),
                        end: m.end(),
                    }) {
                        break;
                    }
                }
            }
            Self::LineEnd(le) => match final_terminator(hay) {
                None => return le.inner.for_each_match(hay, f),
                Some(t) => le.each_at(hay, t, &mut f),
            },
        }
        true
    }

    /// Literals + case flag for [`super::StrMatcherSet`] AC-merge.
    /// `None` for anchored, regex, or any other position-sensitive
    /// shape.
    pub(super) fn merge_literals(&self) -> Option<(Vec<Vec<u8>>, bool)> {
        match self {
            Self::LiteralOnly {
                anchor: Anchor::Anywhere,
                literals,
                case_insensitive,
                ..
            } => Some((
                literals.iter().map(|l| l.to_vec()).collect(),
                *case_insensitive,
            )),
            Self::Shape(ShapeOp::ContainsByte(b)) => Some((vec![vec![*b]], false)),
            Self::Shape(ShapeOp::ByteSet(s)) => {
                let n = s.n() as usize;
                Some(((0..n).map(|i| vec![s.byte(i)]).collect(), false))
            }
            Self::Shape(ShapeOp::Contains(f)) => Some((vec![f.needle().to_vec()], false)),
            Self::LiteralOnly { .. } | Self::Shape(_) | Self::Meta(_) | Self::LineEnd(_) => None,
            #[cfg(feature = "strmatch-backtracking")]
            Self::Backtrack(_) => None,
        }
    }

    /// The literals of a plan anchored at the end, with its case flag and
    /// whether it's anchored at the start too. `None` for any other plan.
    pub(super) fn end_literals(&self) -> Option<(Box<[Box<[u8]>]>, bool, bool)> {
        match self {
            Self::Shape(ShapeOp::EndsWith(lit)) => Some((Box::new([lit.clone()]), false, false)),
            Self::Shape(ShapeOp::ExactMatch(lit)) => Some((Box::new([lit.clone()]), false, true)),
            Self::LiteralOnly {
                anchor: anchor @ (Anchor::AtEnd | Anchor::Exact),
                literals,
                case_insensitive,
                ..
            } => Some((
                literals.clone(),
                *case_insensitive,
                *anchor == Anchor::Exact,
            )),
            _ => None,
        }
    }

    /// The room a [`super::Captures`] for this plan needs, when it isn't the
    /// pattern's own group table.
    pub(super) fn layout(&self) -> Option<&GroupInfo> {
        match self {
            Self::LineEnd(le) => match &le.java {
                JavaEnd::Regex { layout, .. } => Some(layout),
                JavaEnd::Literals { .. } => None,
            },
            _ => None,
        }
    }
}

impl LineEnd {
    fn is_match(&self, hay: &[u8]) -> bool {
        match (final_terminator(hay), &self.java) {
            (None, _) => self.inner.is_match(hay),
            (Some(_), JavaEnd::Regex { find, .. }) => find.is_match(hay),
            (Some(t), JavaEnd::Literals { .. }) => self.find_at(hay, t, 0).is_some(),
        }
    }

    /// The first match starting at `from` or later in `hay`, whose final line
    /// terminator starts at `t`.
    pub(super) fn find_at(&self, hay: &[u8], t: usize, from: usize) -> Option<Match> {
        match &self.java {
            JavaEnd::Literals {
                literals,
                case_insensitive,
                exact,
            } => end_literal(literals, *case_insensitive, *exact, hay, t, from),
            JavaEnd::Regex { find, .. } => {
                let mut slots = [None; 4];
                find.search_slots(&Input::new(hay).span(from..hay.len()), &mut slots)?;
                let [Some(start), Some(end), marker, _] = slots else {
                    return None;
                };
                Some(Match {
                    start: start.get(),
                    end: marker.unwrap_or(end).get(),
                })
            }
        }
    }

    /// Every non-overlapping match in `hay`, whose final line terminator
    /// starts at `t`, with the regex crate's rule for empty matches.
    pub(super) fn each_at(&self, hay: &[u8], t: usize, f: &mut impl FnMut(Match) -> bool) {
        let mut it = Searcher::new(Input::new(hay));
        while let Some(m) = it.advance(|input| {
            Ok(self
                .find_at(hay, t, input.start())
                .map(|m| regex_automata::Match::new(PatternID::ZERO, m.start..m.end)))
        }) {
            if !f(Match {
                start: m.start(),
                end: m.end(),
            }) {
                break;
            }
        }
    }
}

/// The backtracking tier passed its limit.
pub(super) struct Limit;

/// Where Java's next search starts after `m`: its end, or one character past
/// an empty match. A UTF-8 lead byte takes the continuation bytes after it, up
/// to its width, and any other byte is a character.
pub(super) fn resume(hay: &[u8], m: Match) -> usize {
    if m.start < m.end {
        return m.end;
    }
    let tail = match hay.get(m.end) {
        Some(0xC2..=0xDF) => 1,
        Some(0xE0..=0xEF) => 2,
        Some(0xF0..=0xF4) => 3,
        _ => 0,
    };
    let rest = hay.get(m.end + 1..).unwrap_or_default();
    let tail = rest
        .iter()
        .take(tail)
        .take_while(|b| (0x80..=0xBF).contains(*b))
        .count();
    m.end + 1 + tail
}

/// The leftmost of `literals` that ends where `$` holds, at `t` or at the end
/// of `hay`, and starts at `from` or later. On a tie the earlier literal wins,
/// as a leftmost-first search tries them. `exact` needs a start of 0.
fn end_literal(
    literals: &[Box<[u8]>],
    case_insensitive: bool,
    exact: bool,
    hay: &[u8],
    t: usize,
    from: usize,
) -> Option<Match> {
    literals
        .iter()
        .enumerate()
        .flat_map(|(i, lit)| [t, hay.len()].map(|end| (i, lit, end)))
        .filter_map(|(i, lit, end)| {
            let start = end.checked_sub(lit.len())?;
            let tail = &hay[start..end];
            let hit = if case_insensitive {
                tail.eq_ignore_ascii_case(lit)
            } else {
                tail == lit.as_ref()
            };
            (hit && start >= from && (!exact || start == 0)).then_some((start, i, end))
        })
        .min()
        .map(|(start, _, end)| Match { start, end })
}

// ---------------------------------------------------------------------------
// LiteralOnly dispatch -- one AC scan, then optional position check
// ---------------------------------------------------------------------------

#[inline]
fn match_set_is(
    ac: &AhoCorasick,
    anchor: Anchor,
    literals: &[Box<[u8]>],
    case_insensitive: bool,
    hay: &[u8],
) -> bool {
    match anchor {
        Anchor::Anywhere => ac.find(hay).is_some(),
        // `ac.find` returns the LEFTMOST match. The smallest possible start
        // position is 0, so if any match is at position 0, the leftmost is
        // at position 0. Checking the leftmost is sufficient for `AtStart`.
        Anchor::AtStart => ac.find(hay).is_some_and(|m| m.start() == 0),
        Anchor::AtEnd | Anchor::Exact => {
            match_set_end(literals, case_insensitive, anchor, hay, 0).is_some()
        }
    }
}

#[inline]
fn match_set_find(
    ac: &AhoCorasick,
    anchor: Anchor,
    literals: &[Box<[u8]>],
    case_insensitive: bool,
    hay: &[u8],
) -> Option<Match> {
    match anchor {
        Anchor::Anywhere => ac.find(hay).map(|m| Match {
            start: m.start(),
            end: m.end(),
        }),
        Anchor::AtStart => ac.find(hay).filter(|m| m.start() == 0).map(|m| Match {
            start: m.start(),
            end: m.end(),
        }),
        Anchor::AtEnd | Anchor::Exact => match_set_end(literals, case_insensitive, anchor, hay, 0),
    }
}

/// A set anchored at the end matches the longest literal `hay` ends with that
/// starts at `from` or later, as leftmost-first search does. A scan of
/// non-overlapping hits steps over it when one literal is a prefix of another,
/// `(?:a|ab)$` on `ab`.
fn match_set_end(
    literals: &[Box<[u8]>],
    case_insensitive: bool,
    anchor: Anchor,
    hay: &[u8],
    from: usize,
) -> Option<Match> {
    let room = hay.len().checked_sub(from)?;
    let longest = literals
        .iter()
        .filter(|l| {
            if anchor == Anchor::Exact {
                l.len() == hay.len() && from == 0
            } else {
                l.len() <= room
            }
        })
        .filter(|l| {
            let tail = &hay[hay.len() - l.len()..];
            if case_insensitive {
                tail.eq_ignore_ascii_case(l)
            } else {
                tail == l.as_ref()
            }
        })
        .map(|l| l.len())
        .max()?;
    Some(Match {
        start: hay.len() - longest,
        end: hay.len(),
    })
}

// ---------------------------------------------------------------------------
// Shape dispatch -- single match arm per shape, 1-3 instructions per
// ---------------------------------------------------------------------------

#[inline]
fn match_shape_is(op: &ShapeOp, hay: &[u8]) -> bool {
    match op {
        ShapeOp::ContainsByte(b) => memchr::memchr(*b, hay).is_some(),
        ShapeOp::ByteSet(s) => s.contains_any_in(hay).is_some(),
        ShapeOp::Contains(f) => f.find(hay).is_some(),
        ShapeOp::StartsWith(lit) => hay.starts_with(lit),
        ShapeOp::EndsWith(lit) => hay.ends_with(lit),
        ShapeOp::ExactMatch(lit) => hay == lit.as_ref(),
    }
}

#[inline]
fn match_shape_find(op: &ShapeOp, hay: &[u8]) -> Option<Match> {
    match op {
        ShapeOp::ContainsByte(b) => memchr::memchr(*b, hay).map(|i| Match {
            start: i,
            end: i + 1,
        }),
        ShapeOp::ByteSet(s) => s.contains_any_in(hay).map(|i| Match {
            start: i,
            end: i + 1,
        }),
        ShapeOp::Contains(f) => f.find(hay).map(|i| Match {
            start: i,
            end: i + f.needle().len(),
        }),
        ShapeOp::StartsWith(lit) => hay.starts_with(lit).then_some(Match {
            start: 0,
            end: lit.len(),
        }),
        // `then_some` eagerly evaluates the Match struct, so the subtraction
        // `hay.len() - lit.len()` underflows (panics in debug, wraps in release)
        // when the haystack is shorter than the literal -- even though
        // `ends_with` returns false. `then(closure)` defers evaluation.
        ShapeOp::EndsWith(lit) => hay.ends_with(lit).then(|| Match {
            start: hay.len() - lit.len(),
            end: hay.len(),
        }),
        ShapeOp::ExactMatch(lit) => (hay == lit.as_ref()).then_some(Match {
            start: 0,
            end: hay.len(),
        }),
    }
}

// ---------------------------------------------------------------------------
// Iteration dispatch -- non-overlapping matches handed to a callback
// ---------------------------------------------------------------------------

/// Every non-overlapping leftmost-first hit of an unanchored set.
fn each_set(ac: &AhoCorasick, hay: &[u8], f: &mut impl FnMut(Match) -> bool) {
    for m in ac.find_iter(hay) {
        if !f(Match {
            start: m.start(),
            end: m.end(),
        }) {
            break;
        }
    }
}

fn each_byte(hits: impl Iterator<Item = usize>, f: &mut impl FnMut(Match) -> bool) {
    for i in hits {
        if !f(Match {
            start: i,
            end: i + 1,
        }) {
            break;
        }
    }
}

fn each_shape(op: &ShapeOp, hay: &[u8], f: &mut impl FnMut(Match) -> bool) {
    match op {
        ShapeOp::ContainsByte(b) => each_byte(memchr::memchr_iter(*b, hay), f),
        ShapeOp::ByteSet(s) => match s.n() {
            1 => each_byte(memchr::memchr_iter(s.byte(0), hay), f),
            2 => each_byte(memchr::memchr2_iter(s.byte(0), s.byte(1), hay), f),
            3 => each_byte(
                memchr::memchr3_iter(s.byte(0), s.byte(1), s.byte(2), hay),
                f,
            ),
            _ => {}
        },
        ShapeOp::Contains(finder) => {
            for i in finder.find_iter(hay) {
                if !f(Match {
                    start: i,
                    end: i + finder.needle().len(),
                }) {
                    break;
                }
            }
        }
        // Anchored shapes have at most one match. Reuse the single-find logic.
        ShapeOp::StartsWith(_) | ShapeOp::EndsWith(_) | ShapeOp::ExactMatch(_) => {
            if let Some(m) = match_shape_find(op, hay) {
                f(m);
            }
        }
    }
}