Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Last active April 7, 2021 11:43
Show Gist options
  • Save cameronp98/a6043d725b3397e80d99ada9ac5888ef to your computer and use it in GitHub Desktop.
Save cameronp98/a6043d725b3397e80d99ada9ac5888ef to your computer and use it in GitHub Desktop.
Rust console loading percentage for iterator
use std::io::{self, prelude::*};
use std::thread;
use std::time::Duration;
struct Loader<I> {
iter: I,
len: usize,
progress: usize,
}
impl<I: ExactSizeIterator> Loader<I> {
fn new(iter: I) -> Self {
Loader {
len: iter.len(),
iter,
progress: 0,
}
}
fn run(mut self) -> io::Result<()> {
while self.iter.next().is_some() {
self.progress += 1;
print!("\rLoading... {:.0}%", (self.progress as f32 / self.len as f32) * 100.0);
io::stdout().flush()?;
}
println!("\rLoading... Done.");
Ok(())
}
}
fn loading() -> io::Result<()> {
let items: Vec<_> = (0..100).collect();
let time_per_item = (2000 / items.len()) as u64;
Loader::new(items.iter().map(|item| {
thread::sleep(Duration::from_millis(time_per_item));
item
})).run()
}
fn main() {
if let Err(e) = loading() {
eprintln!("Error: {:?}", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment