Last active
April 7, 2021 11:43
-
-
Save cameronp98/a6043d725b3397e80d99ada9ac5888ef to your computer and use it in GitHub Desktop.
Rust console loading percentage for iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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