gdritter repos rrecutils / 71ee2b2
Remove bad input abstraction in favor of boxed trait Getty Ritter 6 years ago
1 changed file(s) with 14 addition(s) and 44 deletion(s). Collapse all Expand all
44 pub const AUTHOR: &'static str =
55 "Getty Ritter <rrecutils@infinitenegativeutility.com>";
66
7 pub enum Input {
8 Stdin(io::BufReader<io::Stdin>),
9 File(io::BufReader<fs::File>),
10 }
11
12 impl io::Read for Input {
13 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
14 match self {
15 &mut Input::Stdin(ref mut stdin) =>
16 stdin.read(buf),
17 &mut Input::File(ref mut file) =>
18 file.read(buf),
7 /// If this doesn't name a path, or if the path is `"-"`, then return
8 /// a buffered reader from stdin; otherwise, attempt to open the file
9 /// named by the path and return a buffered reader around it
10 pub fn input_from_spec<'a>(
11 spec: Option<&'a str>
12 ) -> io::Result<io::BufReader<Box<io::Read>>> {
13 match spec.unwrap_or("-") {
14 "-" => Ok(io::BufReader::new(Box::new(io::stdin()))),
15 path => {
16 let f = fs::File::open(path)?;
17 Ok(io::BufReader::new(Box::new(f)))
1918 }
2019 }
2120 }
2221
23 impl io::BufRead for Input {
24 fn fill_buf(&mut self) -> io::Result<&[u8]> {
25 match self {
26 &mut Input::Stdin(ref mut stdin) =>
27 stdin.fill_buf(),
28 &mut Input::File(ref mut file) =>
29 file.fill_buf(),
30 }
31 }
32
33 fn consume(&mut self, amt: usize) {
34 match self {
35 &mut Input::Stdin(ref mut stdin) =>
36 stdin.consume(amt),
37 &mut Input::File(ref mut file) =>
38 file.consume(amt),
39 }
40 }
41 }
42
43 pub fn input_from_spec<'a>(
44 spec: Option<&'a str>
45 ) -> io::Result<Input> {
46 match spec.unwrap_or("-") {
47 "-" => Ok(Input::Stdin(io::BufReader::new(io::stdin()))),
48 path => {
49 let f = fs::File::open(path)?;
50 Ok(Input::File(io::BufReader::new(f)))
51 }
52 }
53 }
54
22 /// If this doesn't name a path, or if the path is `"-"`, then return
23 /// a buffered writer to stdout; otherwise, attempt to open the file
24 /// named by the path and return a writer around it
5525 pub fn output_from_spec<'a>(
5626 spec: Option<&'a str>
5727 ) -> io::Result<Box<io::Write>>