io_arg/
output.rs

1use std::{fs::File, io::{self, BufWriter, Stdout, Write, stdout}};
2
3use crate::IoArg;
4
5/// An opend outup stream which can provide a `io::Write` interface.
6pub enum Output {
7    StdOut(Stdout),
8    File(File),
9}
10
11impl Output {
12    /// Either calls `stdout` or `File::create` depending on `io_arg`.
13    pub fn new(io_arg: IoArg) -> io::Result<Self> {
14        let ret = match io_arg {
15            IoArg::StdStream => Output::StdOut(stdout()),
16            IoArg::File(path) => Output::File(File::create(path)?),
17        };
18        Ok(ret)
19    }
20
21    /// Wraps either standard out or the file in a `Box<dyn Write>`. In case of [`Output::StdOut`]
22    /// standard out will be locked. In case of [`Output::File`] the file will be wrapped in
23    /// [`std::io::BufWriter`] in order to minimize system calls.
24    pub fn into_write(self) -> Box<dyn Write> {
25        match self {
26            Output::StdOut(stream) => Box::new(stream.lock()),
27            Output::File(file) => Box::new(BufWriter::new(file)),
28        }
29    }
30}