use std::borrow::Cow;
#[cfg(feature = "record")]
use std::fmt::Write as _;
use super::{FieldLayer, Layer, Report, Scope, ScrubScratch, Scrubber};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Shape {
Str,
Scalar,
Null,
List,
Map,
}
#[derive(Debug)]
pub(super) struct Event<'a, P> {
depth: usize,
key: Option<Cow<'a, str>>,
shape: Shape,
pos: P,
next: usize,
name: bool,
}
impl<'a, P> Event<'a, P> {
pub(super) const fn new(depth: usize, key: Option<Cow<'a, str>>, shape: Shape, pos: P) -> Self {
Self {
depth,
key,
shape,
pos,
next: 0,
name: false,
}
}
}
pub(super) trait Values<'a, P> {
fn bytes(&self, pos: P) -> Option<Cow<'a, [u8]>>;
fn scalar(&self, pos: P, out: &mut String) -> Option<()>;
fn container(&self, pos: P) -> Option<String>;
}
#[derive(Debug)]
pub(super) struct Malformed;
impl Scrubber {
pub(super) fn scrub_events<'a, P: Copy>(
&self,
events: &mut [Event<'a, P>],
values: &impl Values<'a, P>,
scratch: &mut ScrubScratch,
report: &mut Report,
masked: impl FnMut(P, Vec<u8>),
) -> Result<(), Malformed> {
self.own(report);
let mut stack = std::mem::take(&mut scratch.stack);
let mut path: Vec<&str> = recycle(std::mem::take(&mut scratch.path));
link(events, &mut stack);
self.mark_pairs(events, values, scratch, &mut stack);
let done = self.scrub_linked(
events, values, scratch, report, masked, &mut stack, &mut path,
);
scratch.stack = stack;
scratch.path = recycle(path);
done
}
#[allow(clippy::too_many_arguments, reason = "the walk's working buffers")]
fn scrub_linked<'a, 'e, P: Copy>(
&self,
events: &'e [Event<'a, P>],
values: &impl Values<'a, P>,
scratch: &mut ScrubScratch,
report: &mut Report,
mut masked: impl FnMut(P, Vec<u8>),
lens: &mut Vec<usize>,
path: &mut Vec<&'e str>,
) -> Result<(), Malformed> {
lens.clear();
let mut i = 0;
while let Some(e) = events.get(i) {
lens.truncate(e.depth);
path.truncate(lens.last().copied().unwrap_or(0));
if let Some(k) = e.key.as_deref() {
path.push(k);
}
lens.push(path.len());
i += 1;
if e.name {
continue;
}
match self.scope_of(path) {
Scope::In => {}
Scope::Above => continue,
Scope::Out => {
i = e.next;
continue;
}
}
let out = match e.shape {
Shape::Null => None,
Shape::List | Shape::Map => {
if e.key.is_none() {
continue;
}
let excepted = self.exceptions.iter().any(|x| x.covers(path));
let text = || {
values.container(e.pos).unwrap_or_else(|| {
let empty = if e.shape == Shape::List { "[]" } else { "{}" };
empty.to_owned()
})
};
let layer = self.container_layer(path, excepted, text, scratch, report);
match layer {
FieldLayer::Replaced(out) => {
i = e.next;
Some(out)
}
FieldLayer::Kept if !excepted => {
i = e.next;
None
}
FieldLayer::Kept | FieldLayer::NotCredential => None,
}
}
Shape::Str => {
let bytes = values.bytes(e.pos).ok_or(Malformed)?;
self.scrub_field(path, &bytes, scratch, report)
}
Shape::Scalar => {
let mut text = std::mem::take(&mut scratch.number);
text.clear();
let read = values.scalar(e.pos, &mut text);
let out = read
.and_then(|()| self.scrub_number(path, text.as_bytes(), scratch, report));
scratch.number = text;
read.ok_or(Malformed)?;
out
}
};
if let Some(out) = out {
masked(e.pos, out);
}
}
Ok(())
}
fn container_layer(
&self,
path: &[&str],
excepted: bool,
text: impl FnOnce() -> String,
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)
|| name.is_empty()
|| !self
.credentials
.matches_in(name, parent, &mut scratch.spellings)
{
return FieldLayer::NotCredential;
}
self.field_layer(path, text().as_bytes(), excepted, scratch, report)
}
fn mark_pairs<'a, P: Copy>(
&self,
events: &mut [Event<'a, P>],
values: &impl Values<'a, P>,
scratch: &mut ScrubScratch,
keyed: &mut Vec<usize>,
) {
keyed.clear();
for i in 0..events.len() {
let (depth, end) = (events[i].depth, events[i].next);
while keyed.last().is_some_and(|&j| events[j].depth >= depth) {
keyed.pop();
}
if events[i].key.is_some() {
keyed.push(i);
continue;
}
let first = i + 1;
let item = depth > 0 && events[i].shape == Shape::List;
if !item || first >= end || events[first].shape != Shape::Str {
continue;
}
let second = events[first].next;
if second >= end || events[second].next != end {
continue;
}
let Some(name) = values.bytes(events[first].pos).and_then(utf8) else {
continue;
};
let parent = keyed
.last()
.and_then(|&j| events[j].key.as_deref())
.unwrap_or_default();
if self
.credentials
.matches_in(&name, parent, &mut scratch.spellings)
{
events[second].key = Some(name);
events[first].name = true;
}
}
}
}
fn link<P>(events: &mut [Event<'_, P>], open: &mut Vec<usize>) {
open.clear();
for i in 0..events.len() {
while let Some(&j) = open.last() {
if events[j].depth < events[i].depth {
break;
}
events[j].next = i;
open.pop();
}
open.push(i);
}
for &j in &*open {
events[j].next = events.len();
}
}
pub(super) fn recycle<T, U>(mut v: Vec<T>) -> Vec<U> {
v.clear();
v.into_iter().filter_map(|_| None).collect()
}
fn utf8(bytes: Cow<'_, [u8]>) -> Option<Cow<'_, str>> {
match bytes {
Cow::Borrowed(b) => std::str::from_utf8(b).ok().map(Cow::Borrowed),
Cow::Owned(b) => String::from_utf8(b).ok().map(Cow::Owned),
}
}
#[cfg(feature = "record")]
pub(super) fn number_text(raw: &str, out: &mut String) {
let digits = raw.strip_prefix('-').unwrap_or(raw);
let plain = raw == "0"
|| (digits.len() <= 18
&& digits.bytes().all(|b| b.is_ascii_digit())
&& digits.bytes().next().is_some_and(|b| b != b'0'));
match serde_json::from_str::<serde_json::Number>(raw) {
Ok(n) if !plain => {
let _ = write!(out, "{n}");
}
_ => out.push_str(raw),
}
}
#[cfg(feature = "record")]
pub(super) fn json_text(text: &str) -> String {
serde_json::from_str::<serde_json::Value>(text)
.map_or_else(|_| text.to_owned(), |v| v.to_string())
}
#[cfg(feature = "record")]
pub(super) struct RecordValues<R>(pub(super) R);
#[cfg(feature = "record")]
impl<'a, R: crate::record::Walk<'a>> Values<'a, R::At> for RecordValues<R> {
fn bytes(&self, at: R::At) -> Option<Cow<'a, [u8]>> {
self.0.bytes(at).ok()
}
fn scalar(&self, at: R::At, out: &mut String) -> Option<()> {
number_text(&self.0.text(at).ok()?, out);
Some(())
}
fn container(&self, at: R::At) -> Option<String> {
self.0.text(at).ok().map(|text| json_text(&text))
}
}
#[cfg(feature = "record")]
pub(super) const fn shape(kind: crate::record::Kind) -> Shape {
use crate::record::Kind;
match kind {
Kind::Str => Shape::Str,
Kind::Number | Kind::Bool => Shape::Scalar,
Kind::Null => Shape::Null,
Kind::List => Shape::List,
Kind::Map => Shape::Map,
}
}