easy_io/
output_writer.rs

1/*
2  A fast and dead-simple writer for competitive programming in Rust
3
4  Author: Axel Lindeberg, github.com/AxlLind
5  Repository: https://github.com/AxlLind/easy_io
6  License: MIT
7  2020
8*/
9#![allow(dead_code)]
10use std::io::{self, Write, Stdout, Result};
11use std::fs::{File, OpenOptions};
12use std::fmt::{Display};
13
14pub struct OutputWriter<W: Write> {
15  writer: W,
16  buf: Vec<u8>,
17}
18
19impl OutputWriter<Stdout> {
20  pub fn new() -> Self { Self::from_writer(io::stdout()) }
21}
22
23impl OutputWriter<File> {
24  pub fn from_file(path: &str) -> Self {
25    let file = OpenOptions::new()
26      .write(true)
27      .create(true)
28      .open(path);
29    Self::from_writer(file.unwrap())
30  }
31}
32
33impl<W: Write> OutputWriter<W> {
34  pub fn from_writer(writer: W) -> Self {
35    let buf = Vec::with_capacity(1 << 16);
36    Self { writer, buf }
37  }
38
39  pub fn print<T: Display>(&mut self, t: T) {
40    write!(self, "{}", t).unwrap();
41  }
42
43  pub fn prints<T: Display>(&mut self, t: T) {
44    write!(self, "{} ", t).unwrap();
45  }
46
47  pub fn println<T: Display>(&mut self, t: T) {
48    writeln!(self, "{}", t).unwrap();
49  }
50}
51
52impl<W: Write> Write for OutputWriter<W> {
53  fn write(&mut self, bytes: &[u8]) -> Result<usize> {
54    self.buf.extend(bytes);
55    Ok(bytes.len())
56  }
57
58  fn flush(&mut self) -> Result<()> {
59    self.writer.write_all(&self.buf)?;
60    self.writer.flush()?;
61    self.buf.clear();
62    Ok(())
63  }
64}
65
66impl<W: Write> Drop for OutputWriter<W> {
67  fn drop(&mut self) { self.flush().unwrap(); }
68}