use std::io::Write;
pub struct TmuxWriter<W: Write> {
inner: W,
wrote_first: bool
}
impl<W: Write> TmuxWriter<W> {
pub fn new(inner: W) -> Self {
Self {
inner,
wrote_first: false
}
}
}
impl<W: Write> Write for TmuxWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if !self.wrote_first {
self.inner.write_all(b"\x1bPtmux;")?;
self.wrote_first = true;
}
let mut last_x1b = 0;
for found_idx in memchr::memmem::find_iter(buf, b"\x1b") {
self.inner.write_all(&buf[last_x1b..found_idx])?;
self.inner.write_all(&[0x1b])?;
last_x1b = found_idx;
}
self.inner.write_all(&buf[last_x1b..])?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.write_all(b"\x1b\\")?;
self.wrote_first = false;
self.inner.flush()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_encode_that_we_know_of() {
let mut writer = TmuxWriter::new(Vec::new());
writer
.write_all(b"\x1b]1337;SetProfile=NewProfileName\x07")
.unwrap();
writer.flush().unwrap();
let resulting = String::from_utf8(writer.inner).unwrap();
assert_eq!(
resulting,
"\x1bPtmux;\x1b\x1b]1337;SetProfile=NewProfileName\x07\x1b\\"
);
}
}