Skip to content

Commit

Permalink
refactor: create enum to wrap STDIN/file variation
Browse files Browse the repository at this point in the history
  • Loading branch information
Aankhen committed Oct 14, 2023
1 parent a3e5f85 commit 1f45be5
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions challenge-1-wc/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
ffi::OsString,
fs::File,
io::{stdin, BufReader, Read},
io::{stdin, Read, StdinLock},
};

use anyhow::{anyhow, bail, Result};
Expand All @@ -16,6 +16,21 @@ struct Args {
file: Option<OsString>,
}

#[derive(Debug)]
enum ReadWrapper<'a> {
Stdin(StdinLock<'a>),
File(File),
}

impl<'a> Read for ReadWrapper<'a> {
fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
match self {
ReadWrapper::Stdin(ref mut stdin) => stdin.read(buf),
ReadWrapper::File(ref mut file) => file.read(buf),
}
}
}

fn main() -> Result<()> {
let args = {
use lexopt::prelude::*;
Expand All @@ -36,10 +51,10 @@ fn main() -> Result<()> {
args
};

let mut input: Box<dyn Read> = if let Some(ref p) = args.file {
Box::new(BufReader::new(File::open(p)?))
let mut input = if let Some(ref p) = args.file {
ReadWrapper::File(File::open(p)?)
} else {
Box::new(BufReader::new(stdin().lock()))
ReadWrapper::Stdin(stdin().lock())
};

let count = if args.bytes {
Expand Down

0 comments on commit 1f45be5

Please sign in to comment.