use std::io::{self, BufRead, BufWriter, IsTerminal, Write};
const BUF_SIZE: usize = 32 * 1024;
pub struct Output {
w: BufWriter<io::Stdout>,
}
impl Output {
pub fn new() -> Self {
Self {
w: BufWriter::with_capacity(BUF_SIZE, io::stdout()),
}
}
pub fn finish(&mut self) -> i32 {
let _ = self.w.flush();
0
}
pub fn fail(&mut self, msg: &str) -> i32 {
let _ = self.w.flush();
eprintln!("{msg}");
1
}
}
impl Write for Output {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.w.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.w.flush()
}
}
pub fn stdin_is_pipe() -> bool {
!io::stdin().is_terminal()
}
pub fn write_lines<F>(out: &mut Output, mut f: F)
where
F: FnMut(&str, &mut Output) -> bool,
{
let stdin = io::stdin();
let mut reader = stdin.lock();
let mut line = String::with_capacity(256);
loop {
line.clear();
match reader.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {}
Err(e) => {
let _ = out.flush();
eprintln!("reading stdin: {e}");
return;
}
}
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if !f(trimmed, out) {
return;
}
}
}