//! Equal-length byte replacement over a stream, safe across read boundaries. //! //! Bytes that could be the start of a pattern at the end of a chunk are held back until the next chunk (or //! [`Rewriter::flush`]), so a pattern split over two reads is still found. Lengths never change, so HTTP //! `Content-Length` stays right. use crate::config::Rewrite; /// A streaming rewriter. #[derive(Debug)] pub struct Rewriter { rules: Vec, held: Vec, } impl Rewriter { /// A rewriter for `rules` (each non-empty, `from.len() == to.len()`, checked by the config). pub fn new(rules: Vec) -> Self { Self { rules, held: Vec::new() } } /// Feeds a chunk; returns the bytes that are safe to send and how many replacements were made. pub fn push(&mut self, chunk: &[u8]) -> (Vec, usize) { if self.rules.is_empty() { return (chunk.to_vec(), 0); } let mut data = std::mem::take(&mut self.held); data.extend_from_slice(chunk); let mut out = Vec::with_capacity(data.len()); let mut count = 0; let mut i = 0; 'scan: while i < data.len() { for r in &self.rules { if data[i..].starts_with(&r.from) { out.extend_from_slice(&r.to); i += r.from.len(); count += 1; continue 'scan; } } // Could `data[i..]` be the beginning of a pattern that the next chunk completes? let rest = &data[i..]; if self.rules.iter().any(|r| rest.len() < r.from.len() && r.from.starts_with(rest)) { self.held = rest.to_vec(); return (out, count); } out.push(data[i]); i += 1; } (out, count) } /// Releases held bytes (end of stream, or a pause in it). pub fn flush(&mut self) -> Vec { std::mem::take(&mut self.held) } /// Whether there are no rules (the rewriter then passes bytes through and never holds any). pub fn is_empty(&self) -> bool { self.rules.is_empty() } /// Bytes currently held back. #[cfg(test)] pub fn held(&self) -> usize { self.held.len() } } #[cfg(test)] mod tests { use super::*; fn lab() -> Rewriter { Rewriter::new(vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }]) } fn run(r: &mut Rewriter, chunks: &[&[u8]]) -> (Vec, usize) { let mut out = Vec::new(); let mut n = 0; for c in chunks { let (o, k) = r.push(c); out.extend(o); n += k; } out.extend(r.flush()); (out, n) } const ANSWER: &[u8] = b"rtsp://127.0.0.2:48010"; #[test] fn replaces_in_one_chunk() { let (out, n) = run(&mut lab(), &[ANSWER]); assert_eq!(n, 1); assert_eq!(out, ANSWER.to_vec().replace_all_for_test()); } #[test] fn replaces_across_every_split_point() { let want = ANSWER.to_vec().replace_all_for_test(); for cut in 0..=ANSWER.len() { let (out, n) = run(&mut lab(), &[&ANSWER[..cut], &ANSWER[cut..]]); assert_eq!(n, 1, "cut {cut}"); assert_eq!(out, want, "cut {cut}"); } } #[test] fn byte_by_byte_works() { let chunks: Vec<&[u8]> = ANSWER.chunks(1).collect(); let (out, n) = run(&mut lab(), &chunks); assert_eq!((out, n), (ANSWER.to_vec().replace_all_for_test(), 1)); } #[test] fn length_never_changes_and_lookalikes_survive() { let input = b"127.0.0.20 127.0.0.2127.0.0.2 127.0.0. 127.0.0.3"; let (out, n) = run(&mut lab(), &[input]); assert_eq!(out.len(), input.len()); assert_eq!(out, b"127.0.0.10 127.0.0.1127.0.0.1 127.0.0. 127.0.0.3"); assert_eq!(n, 3); } #[test] fn holds_only_a_possible_prefix() { let mut r = lab(); let (out, _) = r.push(b"abc127.0."); assert_eq!(out, b"abc"); assert_eq!(r.held(), 6); let (out, n) = r.push(b"x"); assert_eq!((out, n), (b"127.0.x".to_vec(), 0)); assert_eq!(r.held(), 0); } #[test] fn no_rules_is_a_pass_through() { let mut r = Rewriter::new(Vec::new()); assert_eq!(r.push(b"127.0.0.2"), (b"127.0.0.2".to_vec(), 0)); } trait ReplaceAll { fn replace_all_for_test(self) -> Vec; } impl ReplaceAll for Vec { fn replace_all_for_test(self) -> Vec { String::from_utf8(self).unwrap().replace("127.0.0.2", "127.0.0.1").into_bytes() } } }