Skip to content

Commit

Permalink
Unify the line writer logic for files and stdout
Browse files Browse the repository at this point in the history
  • Loading branch information
havenwood committed May 17, 2024
1 parent cda5d39 commit d3cd391
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::args::Args;
use anyhow::Result;
use clap::Parser;
use std::fs::File;
use std::io::{LineWriter, Write};
use std::io::{self, LineWriter, Write};
use unescaper::unescape;
use word_tally::*;

Expand Down Expand Up @@ -55,24 +55,22 @@ fn main() -> Result<()> {
eprintln!();
}

match args.output {
let mut writer: Box<dyn Write> = match args.output {
Some(path) => {
let file = File::create(path)?;
let mut writer = LineWriter::new(file);

for (word, count) in word_tally.tally() {
let line = format!("{word}{delimiter}{count}\n");
writer.write_all(line.as_bytes())?;
}

writer.flush()?;
}
None => {
for (word, count) in word_tally.tally() {
println!("{word}{delimiter}{count}");
}
Box::new(LineWriter::new(file))
}
None => Box::new(io::stdout()),
};

for (word, count) in word_tally.tally() {
let line = format!("{word}{delimiter}{count}\n");

writer.write_all(line.as_bytes())?;
}

writer.flush()?;

Ok(())
}

0 comments on commit d3cd391

Please sign in to comment.