grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
// 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;
use super::plan::{JavaEnd, Plan, resume};
use super::replace::{self, Part};
use super::{Match, StrMatcher, on_boundaries};

/// 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,
    /// JavaScript's `String.prototype.replace`: `$1` to `$99` take two digits
    /// when they name a group and one when they don't, `$<name>` is a named
    /// group where the pattern has any, `$&` is the match, `` $` `` and `$'`
    /// the haystack before and after it, `$$` a dollar, and every other
    /// `$` is text. It never fails.
    JavaScript,
    /// Python's `re.sub`: `\1` to `\99` and `\g<1>`, `\g<name>` and `\g<0>`
    /// are groups, `\a \b \f \n \r \t \v \\` and `\0` with up to two octal
    /// digits and `\ddd` are characters, and `$` is text.
    Python,
    /// GNU sed's `s` with `-E`: `&` and `\0` are the match, `\1` to `\9`
    /// groups, `\&` an ampersand, `\n \t \a \f \v \r` and `\cX`, `\dNNN`,
    /// `\oNNN` and `\xHH` characters, and `\` before any other character
    /// writes that character. The case conversions `\L \U \l \u \E` aren't
    /// read.
    Sed,
}

/// Why [`StrMatcher::try_replacement`] refused a replacement, where its
/// syntax's engine 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 reference, in a Python or sed replacement, to a group number the
    /// pattern doesn't have.
    #[error("the reference to group {number} at byte {at} names no group")]
    GroupRef {
        /// The group number read.
        number: usize,
        /// Where the `\` is.
        at: usize,
    },
    /// A reference, in a Python replacement, to a group name the pattern
    /// doesn't have.
    #[error("the reference to group `{name}` at byte {at} names no group")]
    UnknownName {
        /// The name read.
        name: String,
        /// Where the `\` is.
        at: usize,
    },
    /// A Python `\g<...>` that isn't well formed.
    #[error("the `\\g` at byte {at} doesn't hold a group number or name in `<>`")]
    BadReference {
        /// Where the `\` is.
        at: usize,
    },
    /// An escape the syntax rejects, or sed's case conversion, which isn't
    /// read.
    #[error("the escape at byte {at} isn't one this syntax reads")]
    BadEscape {
        /// 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,
    /// The pieces of a replacement the regex crate's syntax can't hold, which
    /// replace `text` when they are set.
    parts: Option<Box<[Part]>>,
}

/// 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,
                parts: 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,
            parts: None,
        }
    }

    /// A replacement written from `parts`. Text alone is a plain replacement.
    fn from_parts(parts: Vec<Part>) -> Self {
        let (mut whole, mut groups) = (false, false);
        for part in &parts {
            match part {
                Part::Group(0) | Part::Before | Part::After => whole = true,
                Part::Group(_) => groups = true,
                Part::Text(_) => {}
            }
        }
        if !whole && !groups {
            let text = parts.into_iter().flat_map(|p| match p {
                Part::Text(bytes) => bytes,
                _ => Vec::new(),
            });
            return Self {
                text: Text::new(text.collect()),
                expand: Expand::None,
                parts: None,
            };
        }
        Self {
            text: Text::new(Vec::new()),
            expand: if groups {
                Expand::Groups
            } else {
                Expand::WholeMatch
            },
            parts: Some(parts.into_boxed_slice()),
        }
    }

    /// Write the parts of a replacement for the match `group(0)` gives.
    fn write_parts(
        parts: &[Part],
        hay: &[u8],
        group: impl Fn(usize) -> Option<Match>,
        dst: &mut Vec<u8>,
    ) {
        let whole = group(0);
        for part in parts {
            match part {
                Part::Text(bytes) => dst.extend_from_slice(bytes),
                Part::Group(i) => {
                    if let Some(text) = group(*i).and_then(|m| hay.get(m.start..m.end)) {
                        dst.extend_from_slice(text);
                    }
                }
                Part::Before => {
                    if let Some(m) = whole {
                        dst.extend_from_slice(&hay[..m.start]);
                    }
                }
                Part::After => {
                    if let Some(m) = whole {
                        dst.extend_from_slice(&hay[m.end..]);
                    }
                }
            }
        }
    }

    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;
        }
        if let Some(parts) = &self.parts {
            Self::write_parts(parts, hay, group, dst);
            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 {
        if let Some(parts) = &self.parts {
            let mut bytes = Vec::new();
            Self::write_parts(parts, hay.as_bytes(), group, &mut bytes);
            return String::from_utf8(bytes).is_ok_and(|text| {
                dst.push_str(&text);
                true
            });
        }
        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
    }
}

/// The result of a `str` replace under way: `hay` cut at each match, with
/// what replaces it written in between.
struct Pieces<'h> {
    hay: &'h str,
    out: Option<String>,
    /// Where the piece of `hay` after the last match starts.
    last: usize,
    done: usize,
    limit: usize,
    /// `false` once a piece or group split a character.
    whole: bool,
}

impl<'h> Pieces<'h> {
    const fn new(hay: &'h str, limit: usize) -> Self {
        Self {
            hay,
            out: None,
            last: 0,
            done: 0,
            limit,
            whole: true,
        }
    }

    /// Write the text before `m`, then what `write` appends for it. `false`
    /// when the search should stop: the limit is reached, or a piece or
    /// group split a character.
    #[inline]
    fn put(&mut self, m: Match, write: impl FnOnce(&mut String) -> bool) -> bool {
        if m.start == m.end && !self.hay.is_char_boundary(m.start) {
            return true;
        }
        let hay = self.hay;
        let dst = self
            .out
            .get_or_insert_with(|| String::with_capacity(hay.len()));
        let Some(piece) = hay.get(self.last..m.start) else {
            self.whole = false;
            return false;
        };
        dst.push_str(piece);
        if !write(dst) {
            self.whole = false;
            return false;
        }
        self.last = m.end;
        if self.limit == 0 {
            return true;
        }
        self.done += 1;
        self.done < self.limit
    }
}

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

    /// 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_count,
        }
    }

    /// 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.first_captures(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);
        self.first_captures(hay, caps)
    }

    /// [`Self::captures_into`] for `caps` that fit this matcher.
    fn first_captures(&self, hay: &[u8], caps: &mut Captures) -> bool {
        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 (le.terminators.final_in(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()
    }

    /// [`Self::captures`] over UTF-8 text, for the first match
    /// [`Self::find_str`] keeps.
    #[must_use]
    pub fn captures_str(&self, hay: &str) -> Option<Captures> {
        let mut caps = self.create_captures();
        self.first_captures_str(hay, &mut caps).then_some(caps)
    }

    /// [`Self::captures_into`] over UTF-8 text, for the first match
    /// [`Self::find_str`] keeps.
    pub fn captures_into_str(&self, hay: &str, caps: &mut Captures) -> bool {
        self.fit(caps);
        self.first_captures_str(hay, caps)
    }

    /// [`Self::captures_iter`] over UTF-8 text, for the matches
    /// [`Self::find_str`] keeps. A group's span can split a character only in
    /// a pattern read as bytes.
    #[must_use]
    pub fn captures_iter_str(&self, hay: &str) -> std::vec::IntoIter<Captures> {
        let mut out: Vec<Captures> = Vec::new();
        let mut caps = self.create_captures();
        if !self.each_captures_str(hay, &mut caps, |c| {
            out.push(c.clone());
            true
        }) {
            out.clear();
        }
        out.into_iter()
    }

    /// [`Self::first_captures`] for a `str`, which only looks further than the
    /// first match when that one splits a character.
    fn first_captures_str(&self, hay: &str, caps: &mut Captures) -> bool {
        if !self.first_captures(hay.as_bytes(), caps) {
            return false;
        }
        if caps.get(0).is_some_and(|m| on_boundaries(hay, m)) {
            return true;
        }
        let mut found = false;
        if !self.each_captures_str(hay, caps, |_| {
            found = true;
            false
        }) || !found
        {
            caps.slots.set_pattern(None);
        }
        found
    }

    /// [`Self::each_captures`] from the start of `hay`, passing on only the
    /// matches that start and end on a character boundary.
    fn each_captures_str(
        &self,
        hay: &str,
        caps: &mut Captures,
        mut f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        self.each_captures(hay.as_bytes(), 0, caps, |c| {
            c.get(0).is_none_or(|m| !on_boundaries(hay, m)) || f(c)
        })
    }

    /// 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,
                parts: None,
            },
            ReplaceSyntax::Rust => Replacement::bind(text.to_vec()),
            ReplaceSyntax::Java => {
                Replacement::bind(dialect::java_replacement(text, self.group_len()))
            }
            ReplaceSyntax::JavaScript => self
                .with_groups(|groups| Replacement::from_parts(replace::javascript(text, groups))),
            ReplaceSyntax::Python | ReplaceSyntax::Sed => self
                .try_replacement(text, syntax)
                .unwrap_or_else(|_| self.replacement(text, ReplaceSyntax::Literal)),
        }
    }

    /// Run `read` with what a template may refer to in this matcher.
    fn with_groups<T>(&self, read: impl FnOnce(&replace::Groups<'_>) -> T) -> T {
        let index_of = |name: &str| self.group_index(name);
        read(&replace::Groups {
            len: self.group_len(),
            index_of: &index_of,
            named: self.group_names().any(|n| n.is_some()),
        })
    }

    /// [`Self::replacement`], failing where the syntax's own engine does.
    /// [`ReplaceSyntax::Java`] fails where `Matcher.replaceAll` throws: 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.
    /// [`ReplaceSyntax::Python`] fails where `re.sub` raises: a group number
    /// or name the pattern lacks, a malformed `\g<...>`, a bad escape and a
    /// trailing `\`. [`ReplaceSyntax::Sed`] fails on a group past the last, a
    /// trailing `\`, and the case conversions `\L \U \l \u \E`, which aren't
    /// read. 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();
        match syntax {
            ReplaceSyntax::Java => {
                dialect::java_replacement_check(text, self.group_len(), |name| {
                    self.group_index(name).is_some()
                })?;
            }
            ReplaceSyntax::Python => {
                let parts = self.with_groups(|groups| replace::python(text, groups))?;
                return Ok(Replacement::from_parts(parts));
            }
            ReplaceSyntax::Sed => {
                let parts = self.with_groups(|groups| replace::sed(text, groups))?;
                return Ok(Replacement::from_parts(parts));
            }
            _ => {}
        }
        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>> {
        let Text::Str(text) = &rep.text else {
            return None;
        };
        let bytes = hay.as_bytes();
        let mut pieces = Pieces::new(hay, limit);
        let info = &self.groups.info;
        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 };
                pieces.put(m, |dst| rep.write_str(hay, |i| c.get(i), info, dst))
            })
        } else if rep.expand == Expand::None {
            self.each_match(bytes, |m| {
                pieces.put(m, |dst| {
                    dst.push_str(text);
                    true
                })
            })
        } else {
            self.each_match(bytes, |m| {
                pieces.put(m, |dst| {
                    rep.write_str(hay, |i| (i == 0).then_some(m), info, dst)
                })
            })
        };
        if !pieces.whole {
            return None;
        }
        match pieces.out {
            Some(mut dst) if complete => {
                dst.push_str(hay.get(pieces.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()
    }

    /// [`Self::split`] over UTF-8 text, at the matches [`Self::find_str`]
    /// keeps, giving `&str` pieces.
    #[must_use]
    pub fn split_str<'h>(&self, hay: &'h str) -> std::vec::IntoIter<&'h str> {
        self.splitn_str(hay, usize::MAX)
    }

    /// [`Self::splitn`] over UTF-8 text, at the matches [`Self::find_str`]
    /// keeps, giving `&str` pieces.
    #[must_use]
    pub fn splitn_str<'h>(&self, hay: &'h str, limit: usize) -> std::vec::IntoIter<&'h str> {
        let mut out: Vec<&'h str> = Vec::new();
        if limit == 0 {
            return out.into_iter();
        }
        let mut last = 0;
        let complete = self.each_match_str(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) {
        if caps.slots.slots().len() != self.slot_count || caps.len != self.group_count {
            *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. Stops after a match that
    /// ends `hay` when no match is empty, as the search that follows can't
    /// find one.
    fn each_captures(
        &self,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        mut f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        self.fit(caps);
        let (end, non_empty) = (hay.len(), self.non_empty);
        let f = move |c: &Captures| {
            let last = non_empty && c.get(0).is_some_and(|m| m.end == end);
            f(c) && !last
        };
        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 (le.terminators.final_in(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());
        }
    }
}