wtrenderlib 0.1.0

Dependency-free terminal rendering primitives for RGB and RGBA frames
Documentation
use std::io::Write;

use crate::Result;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Multiplexer {
    Tmux,
    Screen,
}

pub fn write_passthrough<W: Write>(
    payload: &[u8],
    output: &mut W,
    multiplexer: Multiplexer,
) -> Result<()> {
    match multiplexer {
        Multiplexer::Tmux => {
            output.write_all(b"\x1bPtmux;\x1b")?;
            for byte in payload {
                output.write_all(&[*byte])?;
                if *byte == 0x1b {
                    output.write_all(b"\x1b")?;
                }
            }
            output.write_all(b"\x1b\\")?;
        }
        Multiplexer::Screen => {
            output.write_all(b"\x1bP")?;
            output.write_all(payload)?;
            output.write_all(b"\x1b\\")?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn escapes_escape_bytes_for_tmux() {
        let mut output = Vec::new();
        write_passthrough(b"\x1b]1337;\x07", &mut output, Multiplexer::Tmux).unwrap();
        assert_eq!(output, b"\x1bPtmux;\x1b\x1b\x1b]1337;\x07\x1b\\");
    }

    #[test]
    fn wraps_screen_payload_without_tmux_escaping() {
        let mut output = Vec::new();
        write_passthrough(b"abc", &mut output, Multiplexer::Screen).unwrap();
        assert_eq!(output, b"\x1bPabc\x1b\\");
    }
}