use std::ops::Range;
#[cfg(test)]
mod tests;
pub(super) fn masked(text: String, spans: &[Range<usize>]) -> Option<String> {
let mut bytes = text.into_bytes();
for span in spans {
mask(&mut bytes, span.clone())?;
}
if multi_line_holds_op(&bytes) {
return None;
}
let mut from = 0;
while let Some(start) = find(&bytes, b"op://", from) {
let end = find(&bytes, b"\n", start).unwrap_or(bytes.len());
mask(&mut bytes, start..end)?;
from = end;
}
String::from_utf8(bytes).ok()
}
fn multi_line_holds_op(bytes: &[u8]) -> bool {
let mut from = 0;
loop {
let opened = [b"\"\"\"", b"'''"]
.into_iter()
.filter_map(|quotes| find(bytes, quotes, from).map(|at| (at, quotes)))
.min();
let Some((start, quotes)) = opened else {
return false;
};
let body = start + quotes.len();
let end = find(bytes, quotes, body).unwrap_or(bytes.len());
if find(bytes.get(body..end).unwrap_or_default(), b"op:", 0).is_some() {
return true;
}
from = end + quotes.len();
}
}
fn mask(bytes: &mut [u8], span: Range<usize>) -> Option<()> {
let text = std::str::from_utf8(bytes).ok()?;
if !text.is_char_boundary(span.start) || !text.is_char_boundary(span.end) {
return None;
}
for byte in bytes.get_mut(span)? {
if !matches!(byte, b'\n' | b'\r') {
*byte = b'*';
}
}
Some(())
}
fn find(bytes: &[u8], needle: &[u8], from: usize) -> Option<usize> {
bytes
.get(from..)?
.windows(needle.len())
.position(|window| window == needle)
.map(|at| at + from)
}