use std::io::{BufWriter, Write};
use std::sync::Mutex;
use crate::ports::EventSink;
pub struct WriterSink<W: Write + Send> {
writer: Mutex<BufWriter<W>>,
}
impl<W: Write + Send> WriterSink<W> {
pub fn new(writer: W) -> Self {
Self {
writer: Mutex::new(BufWriter::new(writer)),
}
}
}
pub fn new_stdout_sink() -> WriterSink<std::io::Stdout> {
WriterSink::new(std::io::stdout())
}
impl<W: Write + Send + Sync + 'static> EventSink for WriterSink<W> {
fn emit(&self, payload: &str) {
if let Ok(mut w) = self.writer.lock() {
let _ = writeln!(w, "{payload}");
let _ = w.flush();
}
}
fn flush(&self) {
if let Ok(mut w) = self.writer.lock() {
let _ = w.flush();
}
}
}