use std::io::{self, Write};
pub struct MatchingWriter<'a> {
expected: &'a [u8],
position: usize,
matches: bool,
}
impl<'a> MatchingWriter<'a> {
#[must_use]
pub const fn new(expected: &'a [u8]) -> Self {
Self {
expected,
position: 0,
matches: true,
}
}
#[must_use]
pub const fn is_complete_match(&self) -> bool {
self.matches && self.position == self.expected.len()
}
}
impl Write for MatchingWriter<'_> {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let end = self.position.checked_add(buffer.len()).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "byte position exceeds usize")
})?;
if self.expected.get(self.position..end) != Some(buffer) {
self.matches = false;
}
self.position = end;
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests;