1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::io::{self, Write};
use terminal::{error, Action, Clear, Retrieved, Value};
pub struct Prgrs<T: Iterator> {
iter: T,
size: usize,
curr: usize,
}
impl<T: Iterator> Prgrs<T> {
pub fn new(it: T, size: usize) -> Self {
Prgrs::<T> {
iter: it,
size,
curr: 0,
}
}
fn create_bar(&self) -> String {
let steps = 50;
let symbol = "#";
let mut buf = String::new();
buf.push_str("[");
let ratio = self.curr as f32 / self.size as f32;
let num_symbols = (ratio * steps as f32) as u32;
for _ in 0..num_symbols {
buf.push_str(symbol);
}
for _ in 0..steps - num_symbols {
buf.push_str(" ");
}
buf.push_str("]");
buf
}
fn print_bar(&mut self) -> error::Result<()> {
let mut terminal = terminal::stdout();
if let Retrieved::CursorPosition(_x, y) = terminal.get(Value::CursorPosition)? {
self.curr += 1;
terminal.batch(Action::MoveCursorTo(0, y))?;
let mut percentage = (self.curr as f32 / self.size as f32) * 100.;
if percentage > 100. {
percentage = 100.;
}
terminal.write(format!("{} ({:.0}%)", self.create_bar(), percentage).as_bytes())?;
terminal.flush_batch()?;
}
Ok(())
}
}
impl<T: Iterator> Iterator for Prgrs<T> {
type Item = T::Item;
fn next(&mut self) -> std::option::Option<Self::Item> {
let next = self.iter.next();
match self.print_bar() {
Err(_e) => {
let mut percentage = (self.curr as f32 / self.size as f32) * 100.;
if percentage > 100. {
percentage = 100.;
}
print!("{} ({:.0}%)\r", self.create_bar(), percentage);
match io::stdout().flush() {
Err(_) => {}
Ok(_) => {}
}
}
Ok(_) => {}
}
match next {
Some(n) => Some(n),
None => {
println!("");
None
}
}
}
}
pub fn writeln(text: &str) -> error::Result<()> {
let mut terminal = terminal::stdout();
if let Retrieved::CursorPosition(_x, y) = terminal.get(Value::CursorPosition)? {
terminal.batch(Action::MoveCursorTo(0, y))?;
terminal.act(Action::ClearTerminal(Clear::FromCursorDown))?;
terminal.write(format!("{}\n", text).as_bytes())?;
terminal.flush_batch()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use crate::Prgrs;
#[test]
fn test_prgrs() {
assert_eq!(Prgrs::new(1..100, 100).next(), (1..100).next());
assert_eq!(Prgrs::new(1..100, 100).last(), (1..100).last());
}
}