pub trait Output {
fn print(&mut self, what: String) -> std::io::Result<()>;
fn output(&self) -> Option<String>;
}
pub struct Stdout;
impl Stdout {
pub fn new() -> Box<Self> {
Box::new(Self)
}
}
impl Output for Stdout {
fn print(&mut self, what: String) -> std::io::Result<()> {
println!("{what}");
Ok(())
}
fn output(&self) -> Option<String> {
None
}
}
pub struct Capture {
buf: std::io::BufWriter<Vec<u8>>,
}
impl Capture {
pub fn new() -> Box<Self> {
Box::new(Self {
buf: std::io::BufWriter::new(Vec::new()),
})
}
}
impl Output for Capture {
fn print(&mut self, what: String) -> std::io::Result<()> {
use std::io::Write;
writeln!(self.buf, "{what}")
}
fn output(&self) -> Option<String> {
String::from_utf8(self.buf.buffer().into()).ok()
}
}