grippo 0.3.1

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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
// Project:   grippo
// File:      src/scrub/mod.rs
// Purpose:   Find and redact secrets with gitleaks rules and answers
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Secret detection and redaction with gitleaks' rules and gitleaks' answers.
//!
//! Each rule's keywords go into one overlapping signature set over the
//! lower-cased text, so text that names no keyword runs no regex. A table of
//! the keywords' first three bytes rules most clean text out before the set
//! runs. A rule's
//! regex runs ASCII-only, as RE2 does. Its secret is the configured capture
//! group, else the first non-empty one, else the whole match. A secret at or
//! under the rule's entropy is dropped, and so is one an allowlist matches.

mod classes;
#[cfg(feature = "record")]
mod closed;
pub mod config;
pub mod field;
#[cfg(feature = "scrub-json")]
mod json;
mod pii;
mod policy;
mod prefix;
#[cfg(feature = "record")]
mod record;
mod redact;
mod report;
mod rule;
mod rules;
mod target;
#[cfg(any(feature = "scrub-json", feature = "record"))]
mod walk;

use std::borrow::Cow;
use std::ops::Range;

use regex_automata::util::captures::Captures;
use thiserror::Error;

pub use config::{AllowlistConfig, GITLEAKS, RuleConfig, RuleSpec};
pub use policy::{PolicyBuilder, ScrubberBuilder};
#[cfg(feature = "record")]
pub use record::JsonBytes;
#[cfg(all(feature = "record", feature = "parse"))]
pub use record::LayeredBytes;
#[cfg(all(feature = "record", feature = "xml"))]
pub use record::XmlBytes;
pub use redact::{HASH_ALGORITHM, HashKey, Redaction};
pub use report::{Entry, Kind, Layer, Report, RuleId};
pub use rules::{ScrubRules, ScrubRulesBuilder};
pub use target::{Scrub, TextBytes};

use crate::path::keys;
use crate::strmatch::{SignatureError, SignatureScratch};
use field::CredentialMatcher;
use prefix::Fold;
use redact::Redactor;
use report::RuleMeta;
use rule::{Allow, Allows, Outcome};
use rules::Compiled;

/// Why a scrubber didn't build.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ScrubError {
    /// The rule config isn't valid TOML for a gitleaks config.
    #[error("scrub: the rule config doesn't parse: {0}")]
    Config(#[from] toml::de::Error),
    /// The config's global allowlist, or one the caller gave, doesn't
    /// compile.
    #[error("scrub: an allowlist doesn't build: {reason}")]
    GlobalAllowlist {
        /// What failed.
        reason: String,
    },
    /// [`Strictness::Strict`] and a rule or field path would be skipped.
    #[error("scrub: {target} can't run: {reason}")]
    Skipped {
        /// What would be left out.
        target: SkipTarget,
        /// Why.
        reason: SkipReason,
    },
    /// A rule id in a builder list that no rule has.
    #[error("scrub: unknown rule ids: {}", unknown_names(.unknown))]
    UnknownRules {
        /// Each id and the list it was in, in the order the lists are read.
        unknown: Vec<UnknownRule>,
    },
    /// A credential term with no letter or digit, which no name could spell.
    #[error("scrub: the credential term {term:?} has no letter or digit to match")]
    CredentialTerm {
        /// The term as given.
        term: String,
    },
    /// `allow_rules` names the credential-field rule, which takes no
    /// allowlist.
    #[error("scrub: allow_rules names \"credential-field\", which takes no allowlist")]
    FieldRuleAllowlist,
    /// A policy asks for a layer its [`ScrubRules`] didn't compile.
    #[error("scrub: the policy runs layers the rules weren't compiled with")]
    LayersNotCompiled {
        /// The layers the policy asked for.
        asked: Layers,
        /// The layers the rules hold.
        compiled: Layers,
    },
    /// A built-in PII pattern didn't compile.
    #[error("scrub: a built-in PII pattern doesn't compile: {source}")]
    Builtin {
        /// The engine's error.
        #[source]
        source: Box<regex_automata::meta::BuildError>,
    },
    /// The keyword set didn't build.
    #[error(transparent)]
    Keywords(#[from] SignatureError),
}

/// Why a rule was left out of a build.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum SkipReason {
    /// It matches on a file path, which text has none of.
    #[error("it matches on a file path")]
    PathGated,
    /// It has no regex.
    #[error("it has no regex")]
    NoRegex,
    /// Its regex or one of its allowlist regexes doesn't compile.
    #[error("a regex doesn't compile: {0}")]
    BadRegex(String),
    /// A field exception path is empty, has an empty segment, or has a `*`
    /// other than a whole last segment.
    #[error("the field path is malformed")]
    BadFieldPath,
}

/// What a build left out: a config rule or a field path.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkipTarget {
    /// A config rule, by id.
    Rule(String),
    /// A path given to [`ScrubberBuilder::except_fields`] or
    /// [`ScrubberBuilder::only_fields`].
    FieldPath(String),
}

impl SkipTarget {
    /// The rule id or the field path.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Rule(id) | Self::FieldPath(id) => id,
        }
    }

    /// `rule` or `field_path`.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Rule(_) => "rule",
            Self::FieldPath(_) => "field_path",
        }
    }
}

impl std::fmt::Display for SkipTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Rule(id) => write!(f, "rule {id:?}"),
            Self::FieldPath(path) => write!(f, "field path {path:?}"),
        }
    }
}

/// A rule or field path left out of a build, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skipped {
    /// What was left out.
    pub target: SkipTarget,
    /// Why.
    pub reason: SkipReason,
}

/// The builder list a rule id came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RuleList {
    /// [`ScrubberBuilder::only_rules`].
    Only,
    /// [`ScrubberBuilder::without_rules`].
    Without,
    /// [`ScrubberBuilder::allow_rules`].
    Allow,
    /// [`ScrubberBuilder::observe_rules`].
    Observe,
}

impl RuleList {
    /// The builder method's name: `only_rules`, `without_rules`,
    /// `allow_rules` or `observe_rules`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Only => "only_rules",
            Self::Without => "without_rules",
            Self::Allow => "allow_rules",
            Self::Observe => "observe_rules",
        }
    }
}

/// A rule id that no rule has, and the list it was in.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnknownRule {
    /// The list.
    pub list: RuleList,
    /// The id as given.
    pub id: String,
}

fn unknown_names(unknown: &[UnknownRule]) -> String {
    let named: Vec<String> = unknown
        .iter()
        .map(|u| format!("{} names {:?}", u.list.as_str(), u.id))
        .collect();
    named.join(", ")
}

/// What a `gitleaks:allow` on a line does.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AllowMarker {
    /// Nothing: in log text, whoever writes part of a line controls it.
    #[default]
    Ignore,
    /// The secret layer skips the line, as gitleaks does for source code.
    Honour,
}

/// What a build does with a rule it can't run.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Strictness {
    /// Leave it out and list it in [`Scrubber::skipped`].
    #[default]
    Lenient,
    /// Fail the build with [`ScrubError::Skipped`].
    Strict,
}

/// One secret found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding<'s> {
    /// The rule's id.
    pub rule: &'s str,
    /// The whole regex match.
    pub matched: Range<usize>,
    /// The secret within the text.
    pub secret: Range<usize>,
}

/// The report row and token stem of a value redacted for its field name.
pub const FIELD_RULE: &str = "credential-field";

/// The stem of the token a redaction by rule `id` writes: `credit-card`
/// gives `CREDIT_CARD`, written as `[CREDIT_CARD_REDACTED]` or, hashed, as
/// `[CREDIT_CARD_<32 hex>]`.
#[must_use]
pub fn rule_token(id: &str) -> String {
    RuleMeta::new(id, Layer::Secret).token.into()
}

/// The id of every PII check this build runs, in the order they run. `phone`
/// is there only with `scrub-phone`.
pub const PII_RULES: &[&str] = &[
    "credit-card",
    "iban",
    "email",
    #[cfg(feature = "scrub-phone")]
    "phone",
    "au-abn",
    "au-acn",
    "au-medicare",
    "au-tfn",
];

/// Every rule id a build from `config` accepts, with its layer.
///
/// The config's rules come first, then [`PII_RULES`], then [`FIELD_RULE`]
/// under the field and text layers. It reads no regex, so a caller checks its
/// ids against it without a build.
pub fn known_rules(config: &RuleConfig) -> impl Iterator<Item = RuleId<'_>> {
    let secret = config.rules.iter().map(|r| RuleId {
        id: &r.id,
        layer: Layer::Secret,
    });
    let pii = PII_RULES.iter().map(|&id| RuleId {
        id,
        layer: Layer::Pii,
    });
    let field = [Layer::Field, Layer::Text].into_iter().map(|layer| RuleId {
        id: FIELD_RULE,
        layer,
    });
    secret.chain(pii).chain(field)
}

/// The layers a scrubber runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Layers(u8);

impl Layers {
    /// gitleaks' rules over the value.
    pub const SECRET: Self = Self(1);
    /// A credential field name redacts its whole value.
    pub const FIELD: Self = Self(2);
    /// Card numbers, IBANs, emails and national ids, each
    /// confirmed by its own check.
    pub const PII: Self = Self(4);
    /// Credential pairs in free text: the value after `password=`,
    /// `Authorization:` and the like, URL passwords, bearer tokens, signed
    /// URL parameters and a header value an error quotes as refused. Counted
    /// as [`FIELD_RULE`] on its own row.
    pub const TEXT: Self = Self(8);
    /// Every layer.
    pub const ALL: Self = Self(15);

    /// Both sets of layers.
    #[must_use]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// These layers less `other`'s.
    #[must_use]
    pub const fn without(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }

    /// `true` when every layer here is also in `other`.
    #[must_use]
    pub const fn within(self, other: Self) -> bool {
        self.0 & !other.0 == 0
    }

    /// `true` when `layer` runs.
    #[must_use]
    pub const fn runs(self, layer: Layer) -> bool {
        let bit = match layer {
            Layer::Secret => Self::SECRET.0,
            Layer::Field => Self::FIELD.0,
            Layer::Pii => Self::PII.0,
            Layer::Text => Self::TEXT.0,
        };
        self.0 & bit != 0
    }
}

/// A field path a scrub leaves alone: its keys as [`crate::path`] writes a
/// name, exact, or ending `.*` for every field below.
#[derive(Debug, Clone)]
struct FieldException {
    segments: Vec<String>,
    /// Each segment as a credential name is compared, for a scope.
    compared: Vec<String>,
    below: bool,
}

impl FieldException {
    /// `None` for an empty path, an empty segment, a bare `*`, or a `*`
    /// anywhere but a whole last segment.
    fn new(path: &str) -> Option<Self> {
        let (path, below) = path.strip_suffix(".*").map_or((path, false), |p| (p, true));
        let segments: Vec<String> = keys(path).map(Cow::into_owned).collect();
        let bad = segments.iter().any(|s| s.is_empty() || s.contains('*'));
        let compared = segments
            .iter()
            .map(|s| field::key_skeleton(s).into_owned())
            .collect();
        (!bad).then_some(Self {
            segments,
            compared,
            below,
        })
    }

    fn covers(&self, path: &[&str]) -> bool {
        let n = self.segments.len();
        let len_fits = if self.below {
            path.len() > n
        } else {
            path.len() == n
        };
        len_fits && self.segments.iter().zip(path).all(|(a, b)| a == b)
    }

    /// Where `path` sits against this path taken as a scope. `a.*` holds the
    /// fields below `a`, not `a` itself, as it does for an exception. Where
    /// either is past ASCII, a key matches a segment whose skeleton it shares,
    /// so a scope reaches a key in any Unicode normal form.
    fn scope(&self, path: &[&str]) -> Scope {
        let shared = self
            .segments
            .iter()
            .zip(&self.compared)
            .zip(path)
            .all(|((a, skeleton), b)| a == b || same_skeleton(a, skeleton, b));
        let n = self.segments.len();
        match path.len().cmp(&n) {
            _ if !shared => Scope::Out,
            std::cmp::Ordering::Less => Scope::Above,
            std::cmp::Ordering::Equal if self.below => Scope::Above,
            std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => Scope::In,
        }
    }
}

/// Whether `key` matches the scope segment `segment`, whose skeleton is
/// `skeleton`, by skeleton: only where either is past ASCII.
#[inline(never)]
fn same_skeleton(segment: &str, skeleton: &str, key: &str) -> bool {
    !(segment.is_ascii() && key.is_ascii()) && skeleton == field::key_skeleton(key)
}

/// Where a value's path sits against a scrubber's scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// At or below a scoped path: scrubbed.
    In,
    /// Above a scoped path: left alone, its members walked.
    Above,
    /// Neither: left alone with all its members.
    Out,
}

/// A policy over [`ScrubRules`]: what a scrub does with a find, and where it
/// looks.
///
/// It holds the layers it runs, the credential terms, the exceptions and
/// scope, the redaction, the caller's allowlists and the observe list. The
/// compiled rules sit behind [`ScrubRules`], so a scrubber is cheap to build
/// and to drop, and every policy over the same rules shares one
/// [`ScrubScratch`] and [`Report`]. Build it with [`ScrubRules::policy`], or
/// with [`Scrubber::builder`] for rules and one policy in a step.
#[derive(Debug)]
pub struct Scrubber {
    rules: ScrubRules,
    layers: Layers,
    redactor: Redactor,
    credentials: CredentialMatcher,
    exceptions: Vec<FieldException>,
    /// The paths scrubbed, with everything below them: every path when empty.
    scope: Vec<FieldException>,
    /// The caller's global allowlists, beside the config's.
    global: Vec<Allow>,
    /// Per compiled rule, the caller's allowlists for it.
    rule_allow: Vec<Vec<Allow>>,
    /// Per PII check, the caller's allowlists for it.
    pii_allow: Vec<Vec<Allow>>,
    /// Per report row, `true` when its finds are counted and left alone.
    observe: Box<[bool]>,
    allow_marker: AllowMarker,
    /// What the text layer writes in place of a value.
    pair_token: String,
    /// Every token a scrub writes is plain ASCII, so text that is plain stays so.
    tokens_plain: bool,
    /// The rules' skips, then the field paths this policy couldn't read.
    skipped: Vec<Skipped>,
}

/// A secret found during a scrub: rule index and where.
#[derive(Debug, Clone)]
struct Hit {
    rule: usize,
    secret: Range<usize>,
}

/// Per-thread buffers, reused across calls.
///
/// A scratch belongs to the [`ScrubRules`] that made it, so it serves every
/// [`Scrubber`] over them. One from other rules is replaced on first use.
pub struct ScrubScratch {
    owner: u64,
    lower: Vec<u8>,
    /// The text the rules read, its white space past ASCII written as ASCII spaces.
    spaced: Vec<u8>,
    hits: SignatureScratch,
    /// The rules a scan runs, in rule order.
    run: Vec<usize>,
    caps: Vec<Captures>,
    found: Vec<Hit>,
    #[cfg_attr(not(any(feature = "scrub-json", feature = "record")), allow(dead_code))]
    number: String,
    spellings: field::Spellings,
    pii_seen: regex_automata::PatternSet,
    /// A record walk's index stack.
    #[cfg(any(feature = "scrub-json", feature = "record"))]
    stack: Vec<usize>,
    /// A record walk's key path, empty between calls.
    #[cfg(any(feature = "scrub-json", feature = "record"))]
    path: Vec<&'static str>,
    /// A raw JSON record's values, empty between calls.
    #[cfg(feature = "record")]
    events: Vec<walk::Event<'static, &'static str>>,
    #[cfg(feature = "record")]
    json: crate::record::WalkBufs,
    /// A record rewritten in place is spliced here, then copied back.
    #[cfg(feature = "record")]
    spliced: Vec<u8>,
    /// The counts for the record being scrubbed, added to the caller's report
    /// only when it scrubs.
    pending: Option<Report>,
}

impl std::fmt::Debug for ScrubScratch {
    /// Buffer sizes only: the buffers hold the last record's text.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScrubScratch")
            .field("lower_capacity", &self.lower.capacity())
            .field("rules", &self.caps.len())
            .finish_non_exhaustive()
    }
}

impl ScrubScratch {
    fn new(c: &Compiled) -> Self {
        Self {
            owner: c.id,
            lower: Vec::new(),
            spaced: Vec::new(),
            hits: c.keywords.scratch(),
            run: Vec::with_capacity(c.rules.len()),
            caps: c.rules.iter().map(|r| r.regex.create_captures()).collect(),
            found: Vec::new(),
            number: String::new(),
            spellings: field::Spellings::default(),
            pii_seen: c.pii_gate.scratch(),
            #[cfg(any(feature = "scrub-json", feature = "record"))]
            stack: Vec::new(),
            #[cfg(any(feature = "scrub-json", feature = "record"))]
            path: Vec::new(),
            #[cfg(feature = "record")]
            events: Vec::new(),
            #[cfg(feature = "record")]
            json: crate::record::WalkBufs::default(),
            #[cfg(feature = "record")]
            spliced: Vec::new(),
            pending: None,
        }
    }
}

/// What the FIELD layer did with one value.
enum FieldLayer {
    /// The name isn't a credential, so the other layers run.
    NotCredential,
    /// A credential left as it is: excepted, or observed only.
    Kept,
    /// A credential and the token written in its place.
    Replaced(Vec<u8>),
}

impl Scrubber {
    /// The compiled rules this policy runs over.
    fn compiled(&self) -> &Compiled {
        &self.rules.0
    }

    /// `report`, replaced with a fresh one when other rules made it.
    fn own(&self, report: &mut Report) {
        if report.owner() != self.compiled().id {
            *report = self.report();
        }
    }

    /// Where `path` sits against the scope: [`Scope::In`] when there's none.
    fn scope_of(&self, path: &[&str]) -> Scope {
        if self.scope.is_empty() {
            return Scope::In;
        }
        self.scoped(path)
    }

    /// As [`Scrubber::scope_of`], for a scrubber with a scope.
    #[inline(never)]
    fn scoped(&self, path: &[&str]) -> Scope {
        let mut at = Scope::Out;
        for s in &self.scope {
            match s.scope(path) {
                Scope::In => return Scope::In,
                Scope::Above => at = Scope::Above,
                Scope::Out => {}
            }
        }
        at
    }

    /// A builder for the rules and one policy over them: mask redaction,
    /// lenient, every rule and layer, the default credential terms, no
    /// exceptions, no scope. For several policies over one rule set, build
    /// [`ScrubRules`] and a [`ScrubRules::policy`] for each.
    pub fn builder() -> ScrubberBuilder {
        ScrubberBuilder::new()
    }

    /// The FIELD layer for one value.
    fn field_layer(
        &self,
        path: &[&str],
        value: &[u8],
        excepted: bool,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> FieldLayer {
        let name = path.last().copied().unwrap_or_default();
        let parent = path.len().checked_sub(2).map_or("", |i| path[i]);
        if !self.layers.runs(Layer::Field)
            || value.is_empty()
            || name.is_empty()
            || !self
                .credentials
                .matches_value(name, parent, value, &mut scratch.spellings)
        {
            return FieldLayer::NotCredential;
        }
        let field = self.compiled().rules.len();
        if excepted {
            report.add(field, Kind::ExceptedField);
            return FieldLayer::Kept;
        }
        if self.observes(field) {
            report.add(field, Kind::Observed);
            return FieldLayer::Kept;
        }
        let mut out = Vec::with_capacity(FIELD_RULE.len() + 20);
        self.redactor
            .write(&mut out, &self.compiled().meta[field].token, value);
        // A value that is already the token was redacted by an earlier scrub.
        if out == value {
            return FieldLayer::Kept;
        }
        report.add(field, Kind::Redacted);
        report.set_changed();
        FieldLayer::Replaced(out)
    }

    /// As [`Scrubber::scrub_field`] for a number or bool: only a credential
    /// field name redacts it, so a timestamp or an id keeps its type.
    #[cfg(any(feature = "scrub-json", feature = "record"))]
    fn scrub_number(
        &self,
        path: &[&str],
        value: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        self.own(report);
        let excepted = self.exceptions.iter().any(|e| e.covers(path));
        match self.field_layer(path, value, excepted, scratch, report) {
            FieldLayer::Replaced(out) => Some(out),
            FieldLayer::NotCredential | FieldLayer::Kept => None,
        }
    }

    /// Scrub one field's value, `path` naming it from the record's root.
    ///
    /// A path outside [`ScrubberBuilder::only_fields`] is left alone and not
    /// counted. An excepted path is left alone, its findings counted as
    /// [`Kind::ExceptedField`]. A credential field name redacts the whole
    /// value as [`FIELD_RULE`]. Anything else goes to [`Scrubber::scrub_text`].
    pub fn scrub_field(
        &self,
        path: &[&str],
        value: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        self.own(report);
        if self.scope_of(path) != Scope::In {
            return None;
        }
        let excepted = self.exceptions.iter().any(|e| e.covers(path));
        match self.field_layer(path, value, excepted, scratch, report) {
            FieldLayer::NotCredential => {}
            FieldLayer::Kept => return None,
            FieldLayer::Replaced(out) => return Some(out),
        }
        if excepted {
            self.scan(value, scratch, |rule, outcome| {
                if let Outcome::Found { .. } = outcome {
                    report.add(rule, Kind::ExceptedField);
                }
            });
            for chunk in value.utf8_chunks() {
                if self.layers.runs(Layer::Text) {
                    self.scrub_pairs_str(
                        chunk.valid(),
                        &mut scratch.spellings,
                        Kind::ExceptedField,
                        report,
                    );
                }
                let c = self.compiled();
                if !self.layers.runs(Layer::Pii) {
                    continue;
                }
                let candidates = c.pii_gate.candidates(chunk.valid(), &mut scratch.pii_seen);
                for (k, validator) in c.pii.iter().enumerate() {
                    if candidates & (1 << k) == 0 {
                        continue;
                    }
                    let rule = self.pii_base() + k;
                    validator.confirmed(chunk.valid(), |_| report.add(rule, Kind::ExceptedField));
                }
            }
            return None;
        }
        self.scrub_text(value, scratch, report)
    }

    /// Build from a rule config with the builder's defaults.
    ///
    /// # Errors
    ///
    /// As [`ScrubberBuilder::build`].
    pub fn new(config: &RuleConfig) -> Result<Self, ScrubError> {
        Self::builder().build(config)
    }

    /// The gitleaks v8.30.1 default rules with the builder's defaults.
    ///
    /// # Errors
    ///
    /// As [`ScrubberBuilder::build`].
    pub fn gitleaks() -> Result<Self, ScrubError> {
        Self::new(&RuleConfig::from_toml(GITLEAKS)?)
    }

    /// The compiled rules behind this policy, to build a sibling policy over
    /// with [`ScrubRules::policy`].
    #[must_use]
    pub const fn scrub_rules(&self) -> &ScrubRules {
        &self.rules
    }

    /// The layers this policy runs.
    #[must_use]
    pub const fn layers(&self) -> Layers {
        self.layers
    }

    /// Number of rules built.
    #[must_use]
    pub fn len(&self) -> usize {
        self.compiled().rules.len()
    }

    /// `true` when no rule was built.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.compiled().rules.is_empty()
    }

    /// Rules and field paths left out of the build, rules first in config
    /// order.
    #[must_use]
    pub fn skipped(&self) -> &[Skipped] {
        &self.skipped
    }

    /// The rules this scrubber runs, by id and layer: each config rule built,
    /// each PII check, and [`FIELD_RULE`] under the field and text layers. A
    /// rule left out by id, by a skip or by the layers isn't listed.
    pub fn rules(&self) -> impl Iterator<Item = RuleId<'_>> {
        self.compiled()
            .meta
            .iter()
            .filter(|m| self.layers.runs(m.layer))
            .map(|m| RuleId {
                id: &m.id,
                layer: m.layer,
            })
    }

    /// Heap bytes held by the compiled regexes and this policy's allowlists.
    /// The regexes are shared with every policy over the same rules. Lazy DFA
    /// caches live in the regexes' own pools and grow per thread as text
    /// arrives.
    #[must_use]
    pub fn memory_usage(&self) -> usize {
        let own = |lists: &[Vec<Allow>]| -> usize {
            lists.iter().flatten().map(Allow::memory_usage).sum()
        };
        self.rules.memory_usage()
            + self.global.iter().map(Allow::memory_usage).sum::<usize>()
            + own(&self.rule_allow)
            + own(&self.pii_allow)
    }

    /// Buffers for one thread, good for every scrubber over the same
    /// [`ScrubRules`].
    #[must_use]
    pub fn scratch(&self) -> ScrubScratch {
        self.rules.scratch()
    }

    /// A report sized for these rules, to reuse across records and across
    /// every scrubber over them.
    #[must_use]
    pub fn report(&self) -> Report {
        self.rules.report()
    }

    /// Every secret in `text`, rule by rule. Counts nothing and changes
    /// nothing.
    pub fn find(&self, text: &[u8], scratch: &mut ScrubScratch) -> Vec<Finding<'_>> {
        let mut found = Vec::new();
        self.scan(text, scratch, |i, outcome| {
            if let Outcome::Found { matched, secret } = outcome {
                found.push(Finding {
                    rule: &self.compiled().meta[i].id,
                    matched,
                    secret,
                });
            }
        });
        found
    }

    /// Scrub `text`, counting into `report`: the secret layer, then credential
    /// pairs in the text, then each PII validator, each over what the last
    /// wrote. `None` when the bytes stay as they are: nothing found, or
    /// [`Redaction::Observe`].
    ///
    /// The credential pair layer reads each invalid UTF-8 sequence as one
    /// character, so a value runs on through it. Bytes outside the replaced
    /// values come out as they went in, invalid ones included.
    pub fn scrub_text(
        &self,
        text: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        self.own(report);
        // A record walk says its texts are plain. Any other text is read once
        // here, and what the passes write into it keeps it so while every token is.
        let walked = scratch.spellings.plain();
        scratch
            .spellings
            .set_plain(walked || (self.tokens_plain && field::is_plain(text)));
        let out = self.scrub_text_read(text, scratch, report);
        scratch.spellings.set_plain(walked);
        out
    }

    /// [`Scrubber::scrub_text`] once `scratch` says whether `text` is plain.
    fn scrub_text_read(
        &self,
        text: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        let secret = self.scrub_secrets(text, scratch, report);
        let current = secret.as_deref().unwrap_or(text);
        let pairs = if self.layers.runs(Layer::Text)
            && field::may_mask(current, scratch.spellings.plain())
        {
            let kind = self.found_kind(self.compiled().rules.len() + 1);
            let spellings = &mut scratch.spellings;
            match std::str::from_utf8(current) {
                Ok(valid) => self
                    .scrub_pairs_str(valid, spellings, kind, report)
                    .map(String::into_bytes),
                Err(_) => match tag_invalid(current) {
                    Some((read, invalid)) => self
                        .scrub_pairs_str(&read, spellings, kind, report)
                        .map(|masked| untag(&masked, &invalid)),
                    None => self
                        .scrub_pairs_str(&String::from_utf8_lossy(current), spellings, kind, report)
                        .map(String::into_bytes),
                },
            }
        } else {
            None
        };
        let pairs = pairs.or(secret);
        let current = pairs.as_deref().unwrap_or(text);
        let pii = if !self.layers.runs(Layer::Pii)
            || self.compiled().pii.is_empty()
            || !self.compiled().pii_gate.may_find(current)
        {
            None
        } else {
            let seen = &mut scratch.pii_seen;
            per_chunk(current, |s| self.scrub_pii_str(s, seen, report))
        };
        let out = pii.or(pairs);
        if out.is_some() {
            report.set_changed();
        }
        out
    }

    /// The text layer: values after credential keys, URL passwords, bearer
    /// tokens, signed URL parameters and refused header values, each counted
    /// on the text row.
    fn scrub_pairs_str(
        &self,
        text: &str,
        spellings: &mut field::Spellings,
        kind: Kind,
        report: &mut Report,
    ) -> Option<String> {
        let token = self.pair_token.as_str();
        let (masked, _) = field::mask_text_in(text, &self.credentials, token, spellings);
        let Cow::Owned(masked) = masked else {
            return None;
        };
        // Tokens a later pass wrote over an earlier one count once. A change
        // that left the count level, such as two tokens merged, still counts.
        let found = masked
            .matches(token)
            .count()
            .saturating_sub(text.matches(token).count())
            .max(1);
        report.add_n(self.compiled().rules.len() + 1, kind, found);
        (kind == Kind::Redacted).then_some(masked)
    }

    /// `true` when report row `row` counts its finds and leaves the bytes.
    fn observes(&self, row: usize) -> bool {
        self.redactor.observes() || self.observe[row]
    }

    /// What a find on report row `row` counts as.
    fn found_kind(&self, row: usize) -> Kind {
        if self.observes(row) {
            Kind::Observed
        } else {
            Kind::Redacted
        }
    }

    fn scrub_pii_str(
        &self,
        text: &str,
        seen: &mut regex_automata::PatternSet,
        report: &mut Report,
    ) -> Option<String> {
        let c = self.compiled();
        let mut current: Cow<'_, str> = Cow::Borrowed(text);
        let mut candidates = c.pii_gate.candidates(text, seen);
        for k in 0..c.pii.len() {
            if candidates & (1 << k) == 0 {
                continue;
            }
            let rule = self.pii_base() + k;
            let mut out: Option<String> = None;
            let mut copied = 0;
            for m in self.pii_spans(k, &current, report) {
                report.add(rule, Kind::Redacted);
                let o = out.get_or_insert_with(|| String::with_capacity(current.len() + 32));
                o.push_str(&current[copied..m.start]);
                self.redactor
                    .write_str(o, &c.meta[rule].token, current[m.clone()].as_bytes());
                copied = m.end;
            }
            if let Some(mut o) = out {
                o.push_str(&current[copied..]);
                current = Cow::Owned(o);
                // A token just written can hold what a later pattern matches.
                candidates = c.pii_gate.candidates(&current, seen);
            }
        }
        match current {
            Cow::Owned(s) => Some(s),
            Cow::Borrowed(_) => None,
        }
    }

    /// The spans of `text` that PII check `k` masks, counting the rest.
    ///
    /// Each candidate is judged on its own: one an allowlist exempts is counted
    /// and left, and the ones kept merge into the spans written, so an exemption
    /// for one card never reaches another that overlaps it.
    fn pii_spans(&self, k: usize, text: &str, report: &mut Report) -> Vec<Range<usize>> {
        let c = self.compiled();
        let rule = self.pii_base() + k;
        let bytes = text.as_bytes();
        let found = c.pii[k].confirmed_each(text);
        if found.is_empty() {
            return found;
        }
        // Candidates come in order, so the line of one usually holds the next, and
        // what each allowlist's line regexes said of it still stands.
        let lists = [&c.global[..], &self.global[..], &self.pii_allow[k][..]];
        let mut line = 0..0;
        let mut line_hits: Vec<Option<bool>> = vec![None; lists.iter().map(|l| l.len()).sum()];
        let (exempt, kept): (Vec<_>, Vec<_>) = found.into_iter().partition(|m| {
            if !(line.start <= m.start && m.end <= line.end) {
                line = rule::line_bounds(bytes, m);
                line_hits.fill(None);
            }
            let mut from = 0;
            lists.iter().any(|allows| {
                let hits = &mut line_hits[from..from + allows.len()];
                from += allows.len();
                rule::allowlisted_in(allows, bytes, m.clone(), line.clone(), hits)
            })
        });
        let spans = pii::merge_spans(kept);
        let observe = self.observes(rule);
        // Exempt cards come in order of start, so one sweep of the spans serves them all.
        let mut first = 0;
        for m in &exempt {
            // An exempt card inside a span that is masked anyway is no exemption.
            while spans.get(first).is_some_and(|s| s.end <= m.start) {
                first += 1;
            }
            let masked = spans
                .get(first)
                .is_some_and(|s| s.start <= m.start && m.end <= s.end);
            if observe || !masked {
                report.add(rule, Kind::AllowlistedValue);
            }
        }
        if observe {
            for _ in &spans {
                report.add(rule, Kind::Observed);
            }
            return Vec::new();
        }
        spans
    }

    /// Where the PII validators' report rows start: after the rules, the
    /// field row and the text row.
    fn pii_base(&self) -> usize {
        self.compiled().rules.len() + 2
    }

    /// The secret layer alone.
    fn scrub_secrets(
        &self,
        text: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        let mut found = std::mem::take(&mut scratch.found);
        found.clear();
        self.scan(text, scratch, |rule, outcome| match outcome {
            Outcome::Found { secret, .. } => {
                let observe = self.observes(rule);
                report.add(
                    rule,
                    if observe {
                        Kind::Observed
                    } else {
                        Kind::Redacted
                    },
                );
                if !observe && !secret.is_empty() {
                    found.push(Hit {
                        rule,
                        secret: char_bounds(text, secret),
                    });
                }
            }
            Outcome::LowEntropy => report.add(rule, Kind::LowEntropy),
            Outcome::Allowlisted => report.add(rule, Kind::AllowlistedValue),
        });
        let out = (!found.is_empty()).then(|| self.redact(text, &mut found));
        scratch.found = found;
        out
    }

    /// `text` with each run of overlapping secrets replaced by one token,
    /// named for the rule whose secret starts first, the longest on a tie.
    fn redact(&self, text: &[u8], found: &mut [Hit]) -> Vec<u8> {
        found.sort_unstable_by(|a, b| {
            (a.secret.start, b.secret.end, a.rule).cmp(&(b.secret.start, a.secret.end, b.rule))
        });
        let mut out = Vec::with_capacity(text.len() + 32 * found.len());
        let mut at = 0;
        let mut i = 0;
        while i < found.len() {
            let first = &found[i];
            let mut end = first.secret.end;
            let mut j = i + 1;
            while j < found.len() && found[j].secret.start < end {
                end = end.max(found[j].secret.end);
                j += 1;
            }
            out.extend_from_slice(&text[at..first.secret.start]);
            self.redactor.write(
                &mut out,
                &self.compiled().meta[first.rule].token,
                &text[first.secret.start..end],
            );
            at = end;
            i = j;
        }
        out.extend_from_slice(&text[at..]);
        out
    }

    /// Run every rule whose keywords appear, calling `on` with each outcome.
    fn scan(&self, text: &[u8], scratch: &mut ScrubScratch, mut on: impl FnMut(usize, Outcome)) {
        let c = self.compiled();
        if scratch.owner != c.id {
            *scratch = self.scratch();
        }
        if !self.layers.runs(Layer::Secret) {
            return;
        }
        // Clean ASCII text is ruled out before it is copied.
        let ascii = scratch.spellings.plain() || text.is_ascii();
        if ascii && c.unkeyed.is_empty() && !keywords_may_hold(c, text) {
            return;
        }
        rule::fold_into(text, ascii, &mut scratch.lower);
        if !ascii
            && c.unkeyed.is_empty()
            && !c.keyword_starts.may_hold(scratch.lower.iter().copied())
        {
            return;
        }
        scratch.run.clear();
        scratch.run.extend_from_slice(&c.unkeyed);
        let (keyed, run) = (&c.keyed, &mut scratch.run);
        c.keywords
            .for_each_match(&scratch.lower, &mut scratch.hits, |m| {
                run.push(keyed[m.index]);
            });
        scratch.run.sort_unstable();
        scratch.run.dedup();
        if scratch.run.is_empty() {
            return;
        }
        // gitleaks' rules read `\s` as ASCII white space only.
        let read = if ascii {
            text
        } else {
            ascii_spaces(text, &mut scratch.spaced)
        };
        for &i in &scratch.run {
            c.rules[i].run(
                read,
                Allows {
                    config: &c.global,
                    policy: &self.global,
                    own: &self.rule_allow[i],
                },
                self.allow_marker == AllowMarker::Honour,
                &mut scratch.caps[i],
                |o| on(i, o),
            );
        }
    }
}

/// `text` with each white space character past ASCII written as ASCII spaces,
/// one for each of its bytes, so a rule's `\s` reads it and every offset
/// stays. `text` itself when it holds none, else the copy in `out`.
#[inline(never)]
fn ascii_spaces<'t>(text: &'t [u8], out: &'t mut Vec<u8>) -> &'t [u8] {
    let wide = |c: char| !c.is_ascii() && c.is_whitespace();
    if !text
        .utf8_chunks()
        .any(|chunk| chunk.valid().chars().any(wide))
    {
        return text;
    }
    out.clear();
    for chunk in text.utf8_chunks() {
        let mut copied = 0;
        let valid = chunk.valid();
        for (i, c) in valid.char_indices().filter(|&(_, c)| wide(c)) {
            out.extend_from_slice(&valid.as_bytes()[copied..i]);
            out.resize(out.len() + c.len_utf8(), b' ');
            copied = i + c.len_utf8();
        }
        out.extend_from_slice(&valid.as_bytes()[copied..]);
        out.extend_from_slice(chunk.invalid());
    }
    out
}

/// Whether ASCII `text` may hold a keyword of the rules in `c`, read in blocks.
fn keywords_may_hold(c: &Compiled, text: &[u8]) -> bool {
    #[cfg(test)]
    if field::plain_forced_off() {
        return c
            .keyword_starts
            .may_hold(text.iter().map(u8::to_ascii_lowercase));
    }
    c.keyword_starts.may_hold_folded(text, Fold::Lower)
}

/// `r` widened so it neither starts nor ends inside a UTF-8 character, and
/// past the combining marks after it, so none is left to sit on the token.
fn char_bounds(text: &[u8], r: Range<usize>) -> Range<usize> {
    let inside = |i: usize| text.get(i).is_some_and(|b| b & 0xC0 == 0x80);
    let mut start = r.start;
    while start > 0 && inside(start) {
        start -= 1;
    }
    let mut end = r.end;
    while inside(end) {
        end += 1;
    }
    while let Some(mark) = text
        .get(end..text.len().min(end + 4))
        .and_then(|head| head.utf8_chunks().next()?.valid().chars().next())
        .filter(|&c| field::is_mark(c))
    {
        end += mark.len_utf8();
    }
    start..end
}

/// Plane 15's private-use characters, which stand for the invalid sequences
/// of a text read as a string.
const TAGS: std::ops::RangeInclusive<u32> = 0xF_0000..=0xF_FFFD;

/// `bytes` as text with each invalid UTF-8 sequence written as its own tag
/// character, and the sequences in order. A tag is no letter, digit or space,
/// so the credential rules read it as they read U+FFFD, and [`untag`] puts
/// the bytes back wherever a tag survives. `None` when the text already holds
/// a tag character or holds more sequences than there are tags.
fn tag_invalid(bytes: &[u8]) -> Option<(String, Vec<&[u8]>)> {
    let mut read = String::with_capacity(bytes.len());
    let mut invalid = Vec::new();
    for chunk in bytes.utf8_chunks() {
        let valid = chunk.valid();
        if valid.chars().any(|c| TAGS.contains(&u32::from(c))) {
            return None;
        }
        read.push_str(valid);
        if !chunk.invalid().is_empty() {
            let tag = char::from_u32(TAGS.start() + u32::try_from(invalid.len()).ok()?)
                .filter(|c| TAGS.contains(&u32::from(*c)))?;
            read.push(tag);
            invalid.push(chunk.invalid());
        }
    }
    Some((read, invalid))
}

/// `text` as bytes, each tag character from [`tag_invalid`] written back as
/// the sequence it stood for.
fn untag(text: &str, invalid: &[&[u8]]) -> Vec<u8> {
    let mut out = Vec::with_capacity(text.len());
    let mut utf8 = [0; 4];
    for c in text.chars() {
        let tagged = u32::from(c)
            .checked_sub(*TAGS.start())
            .filter(|_| TAGS.contains(&u32::from(c)))
            .and_then(|i| invalid.get(usize::try_from(i).ok()?));
        match tagged {
            Some(bytes) => out.extend_from_slice(bytes),
            None => out.extend_from_slice(c.encode_utf8(&mut utf8).as_bytes()),
        }
    }
    out
}

/// `text` with `f` applied to each valid UTF-8 run, bytes between runs kept.
/// `None` when `f` changed no run.
fn per_chunk(text: &[u8], mut f: impl FnMut(&str) -> Option<String>) -> Option<Vec<u8>> {
    if let Ok(valid) = std::str::from_utf8(text) {
        return f(valid).map(String::into_bytes);
    }
    let mut out: Option<Vec<u8>> = None;
    let (mut at, mut copied) = (0, 0);
    for chunk in text.utf8_chunks() {
        let valid = chunk.valid();
        if let Some(s) = f(valid) {
            let o = out.get_or_insert_with(|| Vec::with_capacity(text.len()));
            o.extend_from_slice(&text[copied..at]);
            o.extend_from_slice(s.as_bytes());
            copied = at + valid.len();
        }
        at += valid.len() + chunk.invalid().len();
    }
    out.map(|mut o| {
        o.extend_from_slice(&text[copied..]);
        o
    })
}

#[cfg(test)]
mod tests;