grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/strmatch/ops.rs
// Purpose:   Captures, replace and split on a compiled StrMatcher
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Captures, replace and split. The plan finds each match on its cheapest
//! engine, and a capture engine runs only on a hit, only when a group past
//! group 0 is asked for.

use std::borrow::Cow;
use std::cell::Cell;

use regex_automata::util::captures::{Captures as Slots, GroupInfo};
use regex_automata::util::interpolate;
use regex_automata::util::iter::Searcher;
use regex_automata::util::primitives::{NonMaxUsize, PatternID};
use regex_automata::{Anchored, Input, meta};

use super::dialect::{self, final_terminator};
use super::plan::{JavaEnd, Plan, resume};
use super::{Match, StrMatcher};

/// The groups of one match. Make one with [`StrMatcher::create_captures`] and
/// reuse it, so a search allocates nothing.
#[derive(Debug, Clone)]
pub struct Captures {
    slots: Slots,
    /// Groups the pattern has, counting group 0. `slots` can hold one more,
    /// which the engine that reads `$` as Java's writes and the user never
    /// sees.
    len: usize,
}

impl Captures {
    /// `true` when the last search matched.
    #[must_use]
    pub fn is_match(&self) -> bool {
        self.slots.is_match()
    }

    /// The span of group `index`, 0 being the whole match. `None` for a
    /// group that took no part, or no match.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<Match> {
        if index >= self.len {
            return None;
        }
        self.slots.get_group(index).map(|s| Match {
            start: s.start,
            end: s.end,
        })
    }

    /// The span of the group called `name`.
    #[must_use]
    pub fn name(&self, name: &str) -> Option<Match> {
        self.slots.get_group_by_name(name).map(|s| Match {
            start: s.start,
            end: s.end,
        })
    }

    /// Groups in the pattern, counting group 0.
    #[must_use]
    pub const fn group_len(&self) -> usize {
        self.len
    }

    /// Append `rep` to `dst` with each group it names copied from `hay`, as
    /// `replace` writes a match: `$2-$1` after `(\d+)-(\d+)` matched `10-20`
    /// appends `20-10`. A group that took no part, or that `hay` doesn't
    /// reach, writes nothing. Read `rep` with the matcher these groups came
    /// from, and pass the haystack it searched.
    pub fn expand(&self, hay: &[u8], rep: &Replacement, dst: &mut Vec<u8>) {
        rep.write(hay, |i| self.get(i), self.slots.group_info(), dst);
    }
}

/// How a replacement string reads `$` and `\`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReplaceSyntax {
    /// Written out as given: `$` and `\` are text.
    Literal,
    /// The regex crate's: `$N` and `$name` take the longest run of letters,
    /// digits and `_`, `${N}` and `${name}` are braced, `$$` is a dollar.
    #[default]
    Rust,
    /// Java's `Matcher.replaceAll`: `$N` takes further digits only while the
    /// number still names a group, so `$1_x` is group 1 then `_x`. `${name}`
    /// is a named group, and `\` writes the next character as text.
    Java,
}

/// Why [`StrMatcher::try_replacement`] refused a replacement, where Java's
/// `Matcher.replaceAll` throws. `at` is the byte offset of the `$` or `\`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ReplaceError {
    /// A `$` ends the text.
    #[error("the `$` at byte {at} ends the replacement")]
    MissingGroup {
        /// Where the `$` is.
        at: usize,
    },
    /// A `$` before neither a digit nor `{`.
    #[error("the `$` at byte {at} is followed by neither a digit nor `{{`")]
    IllegalReference {
        /// Where the `$` is.
        at: usize,
    },
    /// `$N` whose first digit is past the last group.
    #[error("`${number}` at byte {at} names no group")]
    NoGroup {
        /// The group number read.
        number: usize,
        /// Where the `$` is.
        at: usize,
    },
    /// `${` not followed by ASCII letters and digits, a letter first, then `}`.
    #[error("the `${{` at byte {at} doesn't hold a group name")]
    BadName {
        /// Where the `$` is.
        at: usize,
    },
    /// `${name}` where no group has that name.
    #[error("`${{{name}}}` at byte {at} names no group")]
    NoGroupNamed {
        /// The name read.
        name: String,
        /// Where the `$` is.
        at: usize,
    },
    /// A `\` ends the text, with nothing to escape.
    #[error("the `\\` at byte {at} ends the replacement")]
    TrailingBackslash {
        /// Where the `\` is.
        at: usize,
    },
}

/// A replacement read once against one matcher's groups.
#[derive(Debug, Clone)]
pub struct Replacement {
    /// In the regex crate's syntax, or the text to write for `Expand::None`.
    text: Text,
    expand: Expand,
}

/// A replacement's text, held as a `str` when it is UTF-8 so a replace over
/// a `str` writes it unchecked.
#[derive(Debug, Clone)]
enum Text {
    Str(Box<str>),
    Bytes(Box<[u8]>),
}

impl Text {
    fn new(text: Vec<u8>) -> Self {
        match String::from_utf8(text) {
            Ok(text) => Self::Str(text.into_boxed_str()),
            Err(error) => Self::Bytes(error.into_bytes().into_boxed_slice()),
        }
    }

    fn bytes(&self) -> &[u8] {
        match self {
            Self::Str(text) => text.as_bytes(),
            Self::Bytes(text) => text,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Expand {
    None,
    WholeMatch,
    Groups,
}

impl Replacement {
    fn bind(text: Vec<u8>) -> Self {
        if memchr::memchr(b'$', &text).is_none() {
            return Self {
                text: Text::new(text),
                expand: Expand::None,
            };
        }
        let (whole, groups) = (Cell::new(false), Cell::new(false));
        let mut plain: Vec<u8> = Vec::with_capacity(text.len());
        interpolate::bytes(
            &text,
            |index, _| {
                if index == 0 {
                    whole.set(true);
                } else {
                    groups.set(true);
                }
            },
            |_| {
                groups.set(true);
                None
            },
            &mut plain,
        );
        let (text, expand) = match (whole.get(), groups.get()) {
            (_, true) => (text, Expand::Groups),
            (true, false) => (text, Expand::WholeMatch),
            (false, false) => (plain, Expand::None),
        };
        Self {
            text: Text::new(text),
            expand,
        }
    }

    fn write(
        &self,
        hay: &[u8],
        group: impl Fn(usize) -> Option<Match>,
        info: &GroupInfo,
        dst: &mut Vec<u8>,
    ) {
        if self.expand == Expand::None {
            dst.extend_from_slice(self.text.bytes());
            return;
        }
        interpolate::bytes(
            self.text.bytes(),
            |index, dst| {
                if let Some(text) = group(index).and_then(|m| hay.get(m.start..m.end)) {
                    dst.extend_from_slice(text);
                }
            },
            |name| info.to_index(PatternID::ZERO, name),
            dst,
        );
    }
}

impl Replacement {
    /// [`Self::write`] into a `String`. `false` when the text isn't UTF-8 or a
    /// group's span splits a character of `hay`.
    fn write_str(
        &self,
        hay: &str,
        group: impl Fn(usize) -> Option<Match>,
        info: &GroupInfo,
        dst: &mut String,
    ) -> bool {
        let Text::Str(text) = &self.text else {
            return false;
        };
        if self.expand == Expand::None {
            dst.push_str(text);
            return true;
        }
        let mut whole = true;
        interpolate::string(
            text,
            |index, dst| {
                if let Some(m) = group(index) {
                    match hay.get(m.start..m.end) {
                        Some(piece) => dst.push_str(piece),
                        None => whole = false,
                    }
                }
            },
            |name| info.to_index(PatternID::ZERO, name),
            dst,
        );
        whole
    }
}

impl StrMatcher {
    /// Capture groups in the pattern, counting group 0.
    #[must_use]
    pub fn group_len(&self) -> usize {
        self.groups.info.group_len(PatternID::ZERO)
    }

    /// Each group's name in group order, `None` for an unnamed group.
    pub fn group_names(&self) -> impl Iterator<Item = Option<&str>> + '_ {
        self.groups.info.pattern_names(PatternID::ZERO)
    }

    /// The index of the group called `name`.
    #[must_use]
    pub fn group_index(&self, name: &str) -> Option<usize> {
        self.groups.info.to_index(PatternID::ZERO, name)
    }

    /// Room for this matcher's groups, to pass to [`Self::captures_into`].
    #[must_use]
    pub fn create_captures(&self) -> Captures {
        let layout = self.plan.layout().unwrap_or(&self.groups.info);
        Captures {
            slots: Slots::all(layout.clone()),
            len: self.group_len(),
        }
    }

    /// The groups of the first match, allocating their room.
    #[must_use]
    pub fn captures(&self, hay: &[u8]) -> Option<Captures> {
        let mut caps = self.create_captures();
        self.captures_into(hay, &mut caps).then_some(caps)
    }

    /// Write the groups of the first match into `caps` and say whether there
    /// was one. `caps` from another matcher with a different group count is
    /// replaced.
    pub fn captures_into(&self, hay: &[u8], caps: &mut Captures) -> bool {
        self.fit(caps);
        if !self.captures_from(&self.plan, hay, 0, caps) {
            caps.slots.set_pattern(None);
        }
        caps.slots.is_match()
    }

    /// Write the groups of the leftmost match starting at `from` or later
    /// into `caps`. Returns `false` when the backtracking tier passed its
    /// limit.
    fn captures_from(&self, plan: &Plan, hay: &[u8], from: usize, caps: &mut Captures) -> bool {
        let input = Input::new(hay).span(from.min(hay.len())..hay.len());
        match plan {
            Plan::Meta(r) => r.search_captures(&input, &mut caps.slots),
            #[cfg(feature = "strmatch-backtracking")]
            Plan::Backtrack(r) => match r.on(hay).captures_from_pos(hay, from) {
                Ok(Some(found)) => fill_backtrack(&found, &self.groups.info, caps),
                Ok(None) => caps.slots.set_pattern(None),
                Err(_) => return false,
            },
            Plan::LineEnd(le) => match (final_terminator(hay), &le.java) {
                (None, _) => return self.captures_from(&le.inner, hay, from, caps),
                (Some(_), JavaEnd::Regex { find, groups, .. }) => {
                    java_captures(groups.as_ref().unwrap_or(find), &input, caps);
                }
                (Some(t), JavaEnd::Literals { .. }) => match le.find_at(hay, t, from) {
                    Some(m) => self.read_groups(&hay[..m.end], m, caps),
                    None => caps.slots.set_pattern(None),
                },
            },
            plan => match plan.find_from(hay, from) {
                Ok(Some(m)) => self.read_groups(hay, m, caps),
                Ok(None) => caps.slots.set_pattern(None),
                Err(_) => return false,
            },
        }
        true
    }

    /// The groups of every non-overlapping match, in order.
    #[must_use]
    pub fn captures_iter(&self, hay: &[u8]) -> std::vec::IntoIter<Captures> {
        let mut out: Vec<Captures> = Vec::new();
        let mut caps = self.create_captures();
        if !self.each_captures(hay, 0, &mut caps, |c| {
            out.push(c.clone());
            true
        }) {
            out.clear();
        }
        out.into_iter()
    }

    /// Read `text` as a replacement for this matcher's groups.
    #[must_use]
    pub fn replacement(&self, text: impl AsRef<[u8]>, syntax: ReplaceSyntax) -> Replacement {
        let text = text.as_ref();
        match syntax {
            ReplaceSyntax::Literal => Replacement {
                text: Text::new(text.to_vec()),
                expand: Expand::None,
            },
            ReplaceSyntax::Rust => Replacement::bind(text.to_vec()),
            ReplaceSyntax::Java => {
                Replacement::bind(dialect::java_replacement(text, self.group_len()))
            }
        }
    }

    /// [`Self::replacement`], failing where Java's `Matcher.replaceAll` throws
    /// for [`ReplaceSyntax::Java`]: a `$` at the end or before neither a digit
    /// nor `{`, `$N` past the last group, `${1}`, `${name}` with no such group,
    /// and a `\` at the end. The other syntaxes never fail.
    ///
    /// # Errors
    ///
    /// The [`ReplaceError`] for the first place Java throws.
    pub fn try_replacement(
        &self,
        text: impl AsRef<[u8]>,
        syntax: ReplaceSyntax,
    ) -> Result<Replacement, ReplaceError> {
        let text = text.as_ref();
        if syntax == ReplaceSyntax::Java {
            dialect::java_replacement_check(text, self.group_len(), |name| {
                self.group_index(name).is_some()
            })?;
        }
        Ok(self.replacement(text, syntax))
    }

    /// Replace the first match. Borrows `hay` when nothing matches.
    #[must_use]
    #[inline]
    pub fn replace<'h>(&self, hay: &'h [u8], rep: &Replacement) -> Cow<'h, [u8]> {
        self.replacen(hay, 1, rep)
    }

    /// Replace every non-overlapping match. Borrows `hay` when nothing
    /// matches.
    #[must_use]
    #[inline]
    pub fn replace_all<'h>(&self, hay: &'h [u8], rep: &Replacement) -> Cow<'h, [u8]> {
        self.replacen(hay, 0, rep)
    }

    /// [`Self::replace`] over UTF-8 text, as [`Self::replacen_str`] writes it.
    #[inline]
    #[must_use]
    pub fn replace_str<'h>(&self, hay: &'h str, rep: &Replacement) -> Cow<'h, str> {
        self.replacen_str(hay, 1, rep)
    }

    /// [`Self::replace_all`] over UTF-8 text, as [`Self::replacen_str`]
    /// writes it.
    #[inline]
    #[must_use]
    pub fn replace_all_str<'h>(&self, hay: &'h str, rep: &Replacement) -> Cow<'h, str> {
        self.replacen_str(hay, 0, rep)
    }

    /// [`Self::replacen`] over UTF-8 text, giving UTF-8 back with no pass over
    /// the result: each piece is cut from `hay` at a character boundary, and
    /// the replacement's text was checked when it was read.
    ///
    /// An empty match inside a character is skipped, as the regex crate's
    /// `str` replace skips it. A longer match or group that splits a
    /// character, which a pattern read as bytes can give, or a replacement
    /// that isn't UTF-8, is replaced as bytes instead, and a broken character
    /// in the result is written as U+FFFD.
    #[must_use]
    pub fn replacen_str<'h>(&self, hay: &'h str, limit: usize, rep: &Replacement) -> Cow<'h, str> {
        self.replacen_text(hay, limit, rep).unwrap_or_else(|| {
            match self.replacen(hay.as_bytes(), limit, rep) {
                Cow::Borrowed(_) => Cow::Borrowed(hay),
                Cow::Owned(bytes) => Cow::Owned(
                    String::from_utf8(bytes)
                        .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()),
                ),
            }
        })
    }

    /// [`Self::replacen_str`] while every piece falls on a character boundary,
    /// `None` once one doesn't.
    fn replacen_text<'h>(
        &self,
        hay: &'h str,
        limit: usize,
        rep: &Replacement,
    ) -> Option<Cow<'h, str>> {
        if matches!(rep.text, Text::Bytes(_)) {
            return None;
        }
        let bytes = hay.as_bytes();
        let mut out: Option<String> = None;
        let (mut last, mut done, mut whole) = (0, 0, true);
        let info = &self.groups.info;
        let mut put = |m: Match, write: &dyn Fn(&mut String) -> bool| {
            if m.start == m.end && !hay.is_char_boundary(m.start) {
                return true;
            }
            let dst = out.get_or_insert_with(|| String::with_capacity(hay.len()));
            let Some(piece) = hay.get(last..m.start) else {
                whole = false;
                return false;
            };
            dst.push_str(piece);
            if !write(dst) {
                whole = false;
                return false;
            }
            last = m.end;
            done += 1;
            limit == 0 || done < limit
        };
        let complete = if rep.expand == Expand::Groups {
            let Some(first) = self.plan.find(bytes) else {
                return Some(Cow::Borrowed(hay));
            };
            let mut caps = self.create_captures();
            self.each_captures(bytes, first.start, &mut caps, |c| {
                let Some(m) = c.get(0) else { return true };
                put(m, &|dst| rep.write_str(hay, |i| c.get(i), info, dst))
            })
        } else {
            self.each_match(bytes, |m| {
                put(m, &|dst| {
                    rep.write_str(hay, |i| (i == 0).then_some(m), info, dst)
                })
            })
        };
        if !whole {
            return None;
        }
        match out {
            Some(mut dst) if complete => {
                dst.push_str(hay.get(last..)?);
                Some(Cow::Owned(dst))
            }
            _ => Some(Cow::Borrowed(hay)),
        }
    }

    /// Replace the first `limit` matches, every one when `limit` is 0.
    /// Borrows `hay` when nothing matches, or when the backtracking tier
    /// passes its limit.
    #[must_use]
    pub fn replacen<'h>(&self, hay: &'h [u8], limit: usize, rep: &Replacement) -> Cow<'h, [u8]> {
        let mut out: Option<Vec<u8>> = None;
        let mut last = 0;
        let mut done = 0;
        let info = &self.groups.info;
        let mut put = |m: Match, write: &dyn Fn(&mut Vec<u8>)| {
            let dst = out.get_or_insert_with(|| Vec::with_capacity(hay.len()));
            dst.extend_from_slice(&hay[last..m.start]);
            write(dst);
            last = m.end;
            done += 1;
            limit == 0 || done < limit
        };
        let complete = if rep.expand == Expand::Groups {
            let Some(first) = self.plan.find(hay) else {
                return Cow::Borrowed(hay);
            };
            let mut caps = self.create_captures();
            self.each_captures(hay, first.start, &mut caps, |c| {
                let Some(m) = c.get(0) else { return true };
                put(m, &|dst| rep.write(hay, |i| c.get(i), info, dst))
            })
        } else {
            self.each_match(hay, |m| {
                put(m, &|dst| {
                    rep.write(hay, |i| (i == 0).then_some(m), info, dst);
                })
            })
        };
        match out {
            Some(mut dst) if complete => {
                dst.extend_from_slice(&hay[last..]);
                Cow::Owned(dst)
            }
            _ => Cow::Borrowed(hay),
        }
    }

    /// The pieces between every match.
    #[must_use]
    pub fn split<'h>(&self, hay: &'h [u8]) -> std::vec::IntoIter<&'h [u8]> {
        self.splitn(hay, usize::MAX)
    }

    /// At most `limit` pieces: the last one holds the rest of `hay` unsplit,
    /// and a `limit` of 0 gives none. When the backtracking tier passes its
    /// limit, `hay` is the one piece.
    #[must_use]
    pub fn splitn<'h>(&self, hay: &'h [u8], limit: usize) -> std::vec::IntoIter<&'h [u8]> {
        let mut out: Vec<&'h [u8]> = Vec::new();
        if limit == 0 {
            return out.into_iter();
        }
        let mut last = 0;
        let complete = self.each_match(hay, |m| {
            if out.len() + 1 >= limit {
                return false;
            }
            out.push(&hay[last..m.start]);
            last = m.end;
            true
        });
        if !complete {
            return vec![hay].into_iter();
        }
        out.push(&hay[last..]);
        out.into_iter()
    }

    fn fit(&self, caps: &mut Captures) {
        let layout = self.plan.layout().unwrap_or(&self.groups.info);
        if caps.slots.group_info().slot_len() != layout.slot_len() || caps.len != self.group_len() {
            *caps = self.create_captures();
        }
    }

    /// The groups of a hit a literal plan found at `m`. For a hit that ends
    /// before a final line terminator, pass `hay` cut there, so its `$` holds.
    fn read_groups(&self, hay: &[u8], m: Match, caps: &mut Captures) {
        if let Some(r) = &self.groups.anchored {
            let input = Input::new(hay).span(m.start..m.end).anchored(Anchored::Yes);
            r.search_captures(&input, &mut caps.slots);
            if caps.slots.is_match() {
                return;
            }
        }
        set_whole(m, &self.groups.info, caps);
    }

    /// Call `f` on the groups of each match from `from` on, until it returns
    /// `false`. `from` must be at or before the first match. Returns `false`
    /// when the backtracking tier passed its limit.
    fn each_captures(
        &self,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        self.fit(caps);
        if self.java_empty {
            self.each_captures_java(hay, from, caps, f)
        } else {
            self.each_captures_on(&self.plan, hay, from, caps, f)
        }
    }

    /// As [`Self::each_captures`], with Java's rule for empty matches.
    fn each_captures_java(
        &self,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        mut f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        let mut at = from;
        while at <= hay.len() {
            if !self.captures_from(&self.plan, hay, at, caps) {
                return false;
            }
            let Some(m) = caps.get(0) else { break };
            if !f(caps) {
                break;
            }
            at = resume(hay, m);
        }
        true
    }

    fn each_captures_on(
        &self,
        plan: &Plan,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        mut f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        match plan {
            Plan::Meta(r) => {
                each_search(
                    hay,
                    from,
                    caps,
                    |input, caps| {
                        r.search_captures(input, &mut caps.slots);
                    },
                    f,
                );
                true
            }
            #[cfg(feature = "strmatch-backtracking")]
            Plan::Backtrack(r) => {
                for found in r.on(hay).captures_iter(hay) {
                    let Ok(found) = found else { return false };
                    fill_backtrack(&found, &self.groups.info, caps);
                    if !f(caps) {
                        break;
                    }
                }
                true
            }
            Plan::LineEnd(le) => match (final_terminator(hay), &le.java) {
                (None, _) => self.each_captures_on(&le.inner, hay, from, caps, f),
                (Some(_), JavaEnd::Regex { find, groups, .. }) => {
                    let re = groups.as_ref().unwrap_or(find);
                    each_search(
                        hay,
                        from,
                        caps,
                        |input, caps| java_captures(re, input, caps),
                        f,
                    );
                    true
                }
                (Some(t), JavaEnd::Literals { .. }) => {
                    le.each_at(hay, t, &mut |m| {
                        self.read_groups(&hay[..m.end], m, caps);
                        f(caps)
                    });
                    true
                }
            },
            plan => plan.for_each_match(hay, |m| {
                self.read_groups(hay, m, caps);
                f(caps)
            }),
        }
    }
}

/// Call `f` on the groups of each match `search` writes into `caps`, from
/// `from` on, until it returns `false`, with the regex crate's rule for empty
/// matches.
fn each_search(
    hay: &[u8],
    from: usize,
    caps: &mut Captures,
    search: impl Fn(&Input<'_>, &mut Captures),
    mut f: impl FnMut(&Captures) -> bool,
) {
    let mut it = Searcher::new(Input::new(hay).span(from..hay.len()));
    loop {
        let found = it.advance(|input| {
            search(input, caps);
            Ok(caps.slots.get_match())
        });
        if found.is_none() || !f(caps) {
            return;
        }
    }
}

/// A search on a regex [`JavaEnd::Regex`] built, which marks in its hidden
/// last group a terminator a `$` stepped over. The match and each group bound
/// at the end move back to where that terminator starts, where Java's `$`
/// stood.
fn java_captures(re: &meta::Regex, input: &Input<'_>, caps: &mut Captures) {
    // The marker must read as unset unless this search set it.
    if let [.., start, end] = caps.slots.slots_mut() {
        (*start, *end) = (None, None);
    }
    re.search_captures(input, &mut caps.slots);
    if !caps.slots.is_match() {
        return;
    }
    let end = input.haystack().len();
    let [groups @ .., start, marker_end] = caps.slots.slots_mut() else {
        return;
    };
    let Some(at) = start.take() else { return };
    *marker_end = None;
    for slot in groups
        .iter_mut()
        .filter(|s| s.is_some_and(|s| s.get() == end))
    {
        *slot = Some(at);
    }
}

/// Group 0 at `m` and every other group unset.
fn set_whole(m: Match, info: &GroupInfo, caps: &mut Captures) {
    caps.slots.set_pattern(Some(PatternID::ZERO));
    let slots = caps.slots.slots_mut();
    slots.fill(None);
    if let Some((start, end)) = info.slots(PatternID::ZERO, 0) {
        slots[start] = NonMaxUsize::new(m.start);
        slots[end] = NonMaxUsize::new(m.end);
    }
}

#[cfg(feature = "strmatch-backtracking")]
fn fill_backtrack(found: &fancy_regex::Captures<'_, [u8]>, info: &GroupInfo, caps: &mut Captures) {
    caps.slots.set_pattern(Some(PatternID::ZERO));
    let slots = caps.slots.slots_mut();
    slots.fill(None);
    for index in 0..info.group_len(PatternID::ZERO) {
        if let (Some((start, end)), Some(m)) =
            (info.slots(PatternID::ZERO, index), found.get(index))
        {
            slots[start] = NonMaxUsize::new(m.start());
            slots[end] = NonMaxUsize::new(m.end());
        }
    }
}