1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use std::{fs::File, io::{self, BufWriter, Stdout, Write, stdout}};

use crate::IoArg;

/// An opend outup stream which can provide a `io::Write` interface.
pub enum Output {
    StdOut(Stdout),
    File(File),
}

impl Output {
    /// Either calls `stdout` or `File::create` depending on `io_arg`.
    pub fn new(io_arg: IoArg) -> io::Result<Self> {
        let ret = match io_arg {
            IoArg::StdStream => Output::StdOut(stdout()),
            IoArg::File(path) => Output::File(File::create(path)?),
        };
        Ok(ret)
    }

    /// Wraps either standard out or the file in a `Box<dyn Write>`. The resulting writer mutably
    /// borrows the instance, since it may lock standard out. A file will be wrapped in a
    /// `BufWriter` in order to minimize system calls.
    pub fn write(&mut self) -> Box<dyn Write + '_> {
        match self {
            Output::StdOut(stream) => Box::new(stream.lock()),
            Output::File(file) => Box::new(BufWriter::new(file)),
        }
    }
}