Skip to content

Commit

Permalink
πŸ”‚ use BufWriter in list command to avoid println! in a loop (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
arcstur authored May 24, 2024
1 parent 892c6d9 commit 4048970
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::models;
use api::client::ApiClient;
use colored::Colorize;
use models::ResultWithDefaultError;
use std::io::{self, BufWriter, Write};

pub struct ListCommand;

Expand All @@ -19,19 +20,31 @@ impl ListCommand {
"Couldn't fetch time entries the from API".red(),
error
),
Ok(entities) => match entity.unwrap_or(Entity::TimeEntry) {
Entity::TimeEntry => entities
.time_entries
.iter()
.take(count.unwrap_or(usize::max_value()))
.for_each(|time_entry| println!("{}", time_entry)),
Ok(entities) => {
// use this to avoid calling println! in a loop:
// <https://rust-cli.github.io/book/tutorial/output.html#a-note-on-printing-performance>
let stdout = io::stdout();
let mut handle = BufWriter::new(stdout);

Entity::Project => entities
.projects
.iter()
.take(count.unwrap_or(usize::max_value()))
.for_each(|(_, projects)| println!("{}", projects)),
},
// TODO: better error handling for writeln!
match entity.unwrap_or(Entity::TimeEntry) {
Entity::TimeEntry => entities
.time_entries
.iter()
.take(count.unwrap_or(usize::max_value()))
.for_each(|time_entry| {
writeln!(handle, "{}", time_entry).expect("failed to print")
}),

Entity::Project => entities
.projects
.iter()
.take(count.unwrap_or(usize::max_value()))
.for_each(|(_, projects)| {
writeln!(handle, "{}", projects).expect("failed to print")
}),
};
}
}
Ok(())
}
Expand Down

0 comments on commit 4048970

Please sign in to comment.