use std::fmt::Write as _;
use serde_json::Value;
use super::{FieldLayer, Report, ScrubScratch, Scrubber};
impl Scrubber {
pub fn scrub_value(
&self,
value: &mut Value,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> bool {
self.own(report);
let mut path: Vec<&str> = Vec::new();
let mut todo: Vec<(&mut Value, usize, Option<&str>, bool)> = vec![(value, 0, None, false)];
let mut changed = false;
while let Some((node, depth, key, item)) = todo.pop() {
path.truncate(depth);
if let Some(k) = key {
path.push(k);
if matches!(node, Value::Object(_) | Value::Array(_)) {
let text = serde_json::to_string(&*node).unwrap_or_default();
let excepted = self.exceptions.iter().any(|e| e.covers(&path));
match self.field_layer(&path, text.as_bytes(), excepted, scratch, report) {
FieldLayer::Replaced(out) => {
*node = Value::String(String::from_utf8_lossy(&out).into_owned());
changed = true;
continue;
}
FieldLayer::Kept if !excepted => continue,
FieldLayer::Kept | FieldLayer::NotCredential => {}
}
}
}
let out = match node {
Value::Object(map) => {
let below = path.len();
todo.extend(
map.iter_mut()
.rev()
.map(|(k, v)| (v, below, Some(k.as_str()), false)),
);
continue;
}
Value::Array(items) => {
let here = path.len();
let parent = path.last().copied().unwrap_or_default();
let pair = item
&& matches!(items.as_slice(), [Value::String(name), _]
if self.credentials.matches_in(name, parent, &mut scratch.spellings));
if pair {
if let [Value::String(name), value] = items.as_mut_slice() {
todo.push((value, here, Some(name.as_str()), false));
}
} else {
todo.extend(items.iter_mut().rev().map(|v| (v, here, None, true)));
}
continue;
}
Value::Null => continue,
Value::String(s) => self.scrub_field(&path, s.as_bytes(), scratch, report),
Value::Bool(b) => {
let text: &[u8] = if *b { b"true" } else { b"false" };
self.scrub_field(&path, text, scratch, report)
}
Value::Number(n) => {
let mut text = std::mem::take(&mut scratch.number);
text.clear();
let _ = write!(text, "{n}");
let out = self.scrub_number(&path, text.as_bytes(), scratch, report);
scratch.number = text;
out
}
};
if let Some(bytes) = out {
*node = Value::String(String::from_utf8_lossy(&bytes).into_owned());
changed = true;
}
}
changed
}
}