use std::borrow::Cow;
use std::convert::Infallible;
use super::{Report, ScrubScratch, Scrubber};
pub trait Scrub: Clone {
type Error;
fn scrub_in_place(
&mut self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Self::Error>;
fn scrubbed(
&self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Self>, Self::Error>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextBytes(pub Vec<u8>);
impl Scrub for TextBytes {
type Error = Infallible;
fn scrub_in_place(
&mut self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, Infallible> {
let Some(out) = scrubber.scrub_text(&self.0, scratch, report) else {
return Ok(false);
};
self.0.clear();
self.0.extend_from_slice(&out);
Ok(true)
}
fn scrubbed(
&self,
scrubber: &Scrubber,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Option<Self>, Infallible> {
Ok(scrubber.scrub_text(&self.0, scratch, report).map(Self))
}
}
impl Scrubber {
pub fn scrub_in_place<T: Scrub>(
&self,
target: &mut T,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<bool, T::Error> {
self.counted(scratch, report, |s, r| target.scrub_in_place(self, s, r))
}
pub fn scrub<'t, T: Scrub>(
&self,
target: &'t T,
scratch: &mut ScrubScratch,
report: &mut Report,
) -> Result<Cow<'t, T>, T::Error> {
let copy = self.counted(scratch, report, |s, r| target.scrubbed(self, s, r))?;
Ok(copy.map_or(Cow::Borrowed(target), Cow::Owned))
}
fn counted<R, E>(
&self,
scratch: &mut ScrubScratch,
report: &mut Report,
scrub: impl FnOnce(&mut ScrubScratch, &mut Report) -> Result<R, E>,
) -> Result<R, E> {
let mut pending = scratch.pending.take().unwrap_or_else(|| self.report());
self.own(&mut pending);
pending.clear();
let done = scrub(scratch, &mut pending);
if done.is_ok() {
self.own(report);
report.absorb(&pending);
}
scratch.pending = Some(pending);
done
}
}