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;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ScrubError {
#[error("scrub: the rule config doesn't parse: {0}")]
Config(#[from] toml::de::Error),
#[error("scrub: an allowlist doesn't build: {reason}")]
GlobalAllowlist {
reason: String,
},
#[error("scrub: {target} can't run: {reason}")]
Skipped {
target: SkipTarget,
reason: SkipReason,
},
#[error("scrub: unknown rule ids: {}", unknown_names(.unknown))]
UnknownRules {
unknown: Vec<UnknownRule>,
},
#[error("scrub: the credential term {term:?} has no letter or digit to match")]
CredentialTerm {
term: String,
},
#[error("scrub: allow_rules names \"credential-field\", which takes no allowlist")]
FieldRuleAllowlist,
#[error("scrub: the policy runs layers the rules weren't compiled with")]
LayersNotCompiled {
asked: Layers,
compiled: Layers,
},
#[error("scrub: a built-in PII pattern doesn't compile: {source}")]
Builtin {
#[source]
source: Box<regex_automata::meta::BuildError>,
},
#[error(transparent)]
Keywords(#[from] SignatureError),
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum SkipReason {
#[error("it matches on a file path")]
PathGated,
#[error("it has no regex")]
NoRegex,
#[error("a regex doesn't compile: {0}")]
BadRegex(String),
#[error("the field path is malformed")]
BadFieldPath,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SkipTarget {
Rule(String),
FieldPath(String),
}
impl SkipTarget {
#[must_use]
pub fn name(&self) -> &str {
match self {
Self::Rule(id) | Self::FieldPath(id) => id,
}
}
#[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:?}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skipped {
pub target: SkipTarget,
pub reason: SkipReason,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RuleList {
Only,
Without,
Allow,
Observe,
}
impl RuleList {
#[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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UnknownRule {
pub list: RuleList,
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(", ")
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AllowMarker {
#[default]
Ignore,
Honour,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Strictness {
#[default]
Lenient,
Strict,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding<'s> {
pub rule: &'s str,
pub matched: Range<usize>,
pub secret: Range<usize>,
}
pub const FIELD_RULE: &str = "credential-field";
#[must_use]
pub fn rule_token(id: &str) -> String {
RuleMeta::new(id, Layer::Secret).token.into()
}
pub const PII_RULES: &[&str] = &[
"credit-card",
"iban",
"email",
#[cfg(feature = "scrub-phone")]
"phone",
"au-abn",
"au-acn",
"au-medicare",
"au-tfn",
];
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)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Layers(u8);
impl Layers {
pub const SECRET: Self = Self(1);
pub const FIELD: Self = Self(2);
pub const PII: Self = Self(4);
pub const TEXT: Self = Self(8);
pub const ALL: Self = Self(15);
#[must_use]
pub const fn with(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[must_use]
pub const fn without(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
#[must_use]
pub const fn within(self, other: Self) -> bool {
self.0 & !other.0 == 0
}
#[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
}
}
#[derive(Debug, Clone)]
struct FieldException {
segments: Vec<String>,
compared: Vec<String>,
below: bool,
}
impl FieldException {
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)
}
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,
}
}
}
#[inline(never)]
fn same_skeleton(segment: &str, skeleton: &str, key: &str) -> bool {
!(segment.is_ascii() && key.is_ascii()) && skeleton == field::key_skeleton(key)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
In,
Above,
Out,
}
#[derive(Debug)]
pub struct Scrubber {
rules: ScrubRules,
layers: Layers,
redactor: Redactor,
credentials: CredentialMatcher,
exceptions: Vec<FieldException>,
scope: Vec<FieldException>,
global: Vec<Allow>,
rule_allow: Vec<Vec<Allow>>,
pii_allow: Vec<Vec<Allow>>,
observe: Box<[bool]>,
allow_marker: AllowMarker,
pair_token: String,
tokens_plain: bool,
skipped: Vec<Skipped>,
}
#[derive(Debug, Clone)]
struct Hit {
rule: usize,
secret: Range<usize>,
}
pub struct ScrubScratch {
owner: u64,
lower: Vec<u8>,
spaced: Vec<u8>,
hits: SignatureScratch,
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,
#[cfg(any(feature = "scrub-json", feature = "record"))]
stack: Vec<usize>,
#[cfg(any(feature = "scrub-json", feature = "record"))]
path: Vec<&'static str>,
#[cfg(feature = "record")]
events: Vec<walk::Event<'static, &'static str>>,
#[cfg(feature = "record")]
json: crate::record::WalkBufs,
#[cfg(feature = "record")]
spliced: Vec<u8>,
pending: Option<Report>,
}
impl std::fmt::Debug for ScrubScratch {
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,
}
}
}
enum FieldLayer {
NotCredential,
Kept,
Replaced(Vec<u8>),
}
impl Scrubber {
fn compiled(&self) -> &Compiled {
&self.rules.0
}
fn own(&self, report: &mut Report) {
if report.owner() != self.compiled().id {
*report = self.report();
}
}
fn scope_of(&self, path: &[&str]) -> Scope {
if self.scope.is_empty() {
return Scope::In;
}
self.scoped(path)
}
#[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
}
pub fn builder() -> ScrubberBuilder {
ScrubberBuilder::new()
}
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);
if out == value {
return FieldLayer::Kept;
}
report.add(field, Kind::Redacted);
report.set_changed();
FieldLayer::Replaced(out)
}
#[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,
}
}
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)
}
pub fn new(config: &RuleConfig) -> Result<Self, ScrubError> {
Self::builder().build(config)
}
pub fn gitleaks() -> Result<Self, ScrubError> {
Self::new(&RuleConfig::from_toml(GITLEAKS)?)
}
#[must_use]
pub const fn scrub_rules(&self) -> &ScrubRules {
&self.rules
}
#[must_use]
pub const fn layers(&self) -> Layers {
self.layers
}
#[must_use]
pub fn len(&self) -> usize {
self.compiled().rules.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.compiled().rules.is_empty()
}
#[must_use]
pub fn skipped(&self) -> &[Skipped] {
&self.skipped
}
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,
})
}
#[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)
}
#[must_use]
pub fn scratch(&self) -> ScrubScratch {
self.rules.scratch()
}
#[must_use]
pub fn report(&self) -> Report {
self.rules.report()
}
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
}
pub fn scrub_text(
&self,
text: &[u8],
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Option<Vec<u8>> {
self.own(report);
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
}
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
}
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;
};
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)
}
fn observes(&self, row: usize) -> bool {
self.redactor.observes() || self.observe[row]
}
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, ¤t, report) {
report.add(rule, Kind::Redacted);
let o = out.get_or_insert_with(|| String::with_capacity(current.len() + 32));
o.push_str(¤t[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(¤t[copied..]);
current = Cow::Owned(o);
candidates = c.pii_gate.candidates(¤t, seen);
}
}
match current {
Cow::Owned(s) => Some(s),
Cow::Borrowed(_) => None,
}
}
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;
}
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);
let mut first = 0;
for m in &exempt {
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
}
fn pii_base(&self) -> usize {
self.compiled().rules.len() + 2
}
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
}
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
}
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;
}
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;
}
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),
);
}
}
}
#[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
}
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)
}
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
}
const TAGS: std::ops::RangeInclusive<u32> = 0xF_0000..=0xF_FFFD;
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))
}
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
}
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;