progress_bar/
progress_bar.rs

1#![allow(unused_must_use)]
2
3extern crate stijl;
4use stijl::*;
5
6use std::{thread, time};
7use std::io::{self, Cursor, Read, Write};
8
9fn main() {
10    let quarter_sec = time::Duration::from_millis(250);
11    let mut completion = 0.0f32;
12    while completion <= 1.0 {
13        draw_progress(completion);
14        thread::sleep(quarter_sec);
15        completion += 0.03125 // 1/32
16    }
17    println!();
18}
19
20fn draw_progress(completion: f32) {
21    let mut stream = stijl::stdout(DoStyle::Auto);
22    let sz = stream.get_size();
23    // Use (cols - 1) for Windows 7 compatibility.
24    stream.write_all(&progress_str((sz.cols - 1) as usize, completion));
25    stream.rewind_lines(1);
26}
27
28fn progress_str(cols: usize, completion: f32) -> Vec<u8> {
29    let mut pstr = Cursor::new(Vec::with_capacity(cols));
30    // minimum updatable: "Processing: 100%"
31    if cols < 16 {
32        write!(
33            &mut pstr,
34            "{}",
35            "Processing...".chars().take(cols).collect::<String>()
36        );
37        return pstr.into_inner();
38    }
39    write!(&mut pstr, "Processing:{}", if cols > 16 { " " } else { "" });
40    if cols > 17 {
41        let cols = (cols - 17) as u64;
42        let fill = (completion * (cols as f32)) as u64;
43        io::copy(&mut io::repeat(b'#').take(fill), &mut pstr);
44        io::copy(&mut io::repeat(b' ').take(cols - fill), &mut pstr);
45    }
46    write!(&mut pstr, "{: >4}%", (completion * 100.0) as u32);
47    pstr.into_inner()
48}