io_arg/
input.rs

1use std::{
2    fs::File,
3    io::{self, stdin, BufRead, BufReader, Stdin},
4};
5
6use crate::IoArg;
7
8/// An opend input stream which can provide a `io::Read` interface.
9pub enum Input {
10    StdIn(Stdin),
11    File(File),
12}
13
14impl Input {
15    /// Either calls `stdin` or `File::open` depending on `io_arg`.
16    pub fn new(io_arg: IoArg) -> io::Result<Self> {
17        let ret = match io_arg {
18            IoArg::StdStream => Input::StdIn(stdin()),
19            IoArg::File(path) => Input::File(File::open(path)?),
20        };
21        Ok(ret)
22    }
23
24    /// Either locks stdin or wraps the file in a `BufReader`.
25    pub fn buf_read(&mut self) -> Box<dyn BufRead + '_> {
26        match self {
27            Input::StdIn(stream) => Box::new(stream.lock()),
28            Input::File(file) => Box::new(BufReader::new(file)),
29        }
30    }
31}