src/render/mode/stream.rs

//! Streaming output: one line in, one line out.
//!
//! This is the default mode. It's the fastest because there is no buffering
//! or alignment. Each line is wrapped with the origin color tag and written
//! directly to stdout.

use std::io::{self, Write};

use crate::render::ansi::hash::source_color::pick_color;
use crate::render::ansi::sgr::writer::SgrWriter;

pub struct StreamRenderer<W: Write> {
    sink: SgrWriter<W>,
    show_origin: bool,
}

impl<W: Write> StreamRenderer<W> {
    pub fn new(sink: W, show_origin: bool, color: bool) -> Self {
        Self {
            sink: SgrWriter::new(sink, color),
            show_origin,
        }
    }

    pub fn render(&mut self, origin: &str, line: &str) -> io::Result<()> {
        if self.show_origin {
            let color = pick_color(origin);
            self.sink.with_fg(color, |w| {
                write!(w, "{}", origin)
            })?;
            self.sink.raw().write_all(b" | ")?;
        }
        self.sink.raw().write_all(line.as_bytes())?;
        self.sink.raw().write_all(b"\n")?;
        Ok(())
    }

    pub fn flush(&mut self) -> io::Result<()> {
        self.sink.raw().flush()
    }
}