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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! # Yet Another Progress Bar
//!
//! This library provides lightweight tools for rendering Unicode progress indicators. Unlike most similar libraries, it
//! performs no IO internally, instead providing `Display` implementations. Handling the details of any particular
//! output device is left to the user.
//!
//! # Examples
//! The `termion` crate can be used to implement good behavior on an ANSI terminal:
//!
//! ```no_run
//! extern crate yapb;
//! extern crate termion;
//! use std::{thread, time};
//! use std::io::{self, Write};
//! use yapb::{Bar, Progress};
//!
//! fn main() {
//!   let mut bar = Bar::new();
//!   print!("{}", termion::cursor::Save);
//!   for i in 0..100 {
//!     bar.set(i as f32 / 100.0);
//!     let (width, _) = termion::terminal_size().unwrap();
//!     print!("{}{}[{:width$}]",
//!            termion::clear::AfterCursor, termion::cursor::Restore,
//!            bar, width = width as usize - 2);
//!     io::stdout().flush().unwrap();
//!     thread::sleep(time::Duration::from_millis(100));
//!   }
//! }
//! ```

use std::fmt::{self, Write, Display};

/// Indicators that communicate a proportion of progress towards a known end point
pub trait Progress: Display {
    /// Set the amount of progress
    ///
    /// `value` must be in [0, 1]. Implementations should be trivial, with any complexity deferred to the
    /// `Display` implementation.
    fn set(&mut self, value: f32);
}

/// A high-resolution progress bar using block elements
///
/// # Examples
/// ```
/// # use yapb::*;
/// let mut bar = Bar::new();
/// bar.set(0.55);
/// assert_eq!(format!("[{:10}]", bar), "[█████▌    ]");
/// ```
#[derive(Debug, Copy, Clone)]
pub struct Bar {
    progress: f32,
}

impl Bar {
    pub fn new() -> Self { Bar {
        progress: 0.0,
    }}

    pub fn get(&self) -> f32 { self.progress }
}

impl Progress for Bar {
    fn set(&mut self, value: f32) { self.progress = value; }
}

impl Display for Bar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let width = f.width().unwrap_or(80) as u32;
        // Scale by width, rounding to nearest
        let count = width as f32 * self.progress;
        let whole = count.trunc() as u32;
        for _ in 0..whole {
            f.write_char('█')?;
        }
        let fraction = (count.fract() * 8.0).trunc() as u32;
        let fill = f.fill();
        if whole < width {
            f.write_char(match fraction {
                0 => fill,
                1 => '▏',
                2 => '▎',
                3 => '▍',
                4 => '▌',
                5 => '▋',
                6 => '▊',
                7 => '▉',
                _ => unreachable!(),
            })?;
            for _ in whole..(width - 1) {
                f.write_char(fill)?;
            }
        }
        Ok(())
    }
}

/// Indicators that animate through some number of states to indicate activity with indefinite duration
///
/// Incrementing a state by 1 advances by one frame of animation. Implementations of these two setters should only be a
/// handful of instructions, with all complexity deferred to the `Display` impl.
pub trait Spinner: Display {
    /// Set a specific state
    fn set(&mut self, value: u32);
    /// Advance the current state `count` times.
    fn step(&mut self, count: u32);
}

/// A spinner that cycles through 256 states by counting in binary using braille
///
/// # Examples
/// ```
/// # use yapb::*;
/// let mut spinner = Counter256::new();
/// assert_eq!(format!("{}", spinner), "⠀");
/// spinner.step(0x0F);	
/// assert_eq!(format!("{}", spinner), "⡇");
/// spinner.step(0xF0);
/// assert_eq!(format!("{}", spinner), "⣿");
/// ```
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct Counter256 {
    state: u8
}

impl Counter256 {
    pub fn new() -> Self { Self { state: 0 } }
}

impl Spinner for Counter256 {
    fn set(&mut self, state: u32) { self.state = state as u8; }
    fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8); }
}

fn braille_binary(value: u8) -> char {
    // Rearrange bits for consistency
    let value = (value & 0b10000111)
        | ((value & 0b00001000) << 3)
        | ((value & 0b01110000) >> 1);
    unsafe { ::std::char::from_u32_unchecked(0x2800 + value as u32) }
}

impl Display for Counter256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_char(braille_binary(self.state))
    }
}

/// A spinner that cycles through 8 states with a single spinning braille dot
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct Spinner8 {
    state: u8
}

const SPINNER8_STATES: [char; 8] = ['⡀', '⠄', '⠂', '⠁', '⠈', '⠐', '⠠', '⢀'];

impl Spinner8 {
    pub fn new() -> Self { Self { state: 0 } }
}

impl Spinner for Spinner8 {
    fn set(&mut self, state: u32) { self.state = state as u8 % SPINNER8_STATES.len() as u8; }
    fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8) % SPINNER8_STATES.len() as u8; }
}

impl Display for Spinner8 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_char(*unsafe { SPINNER8_STATES.get_unchecked(self.state as usize) })
    }
}

/// A spinner that cycles through 16 states by counting in binary using block elements
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct Counter16 {
    state: u8
}

const COUNTER16_STATES: [char; 16] = [' ', '▘', '▖', '▌', '▝', '▀', '▞', '▛', '▗', '▚', '▄', '▙', '▐', '▜', '▟', '█'];

impl Counter16 {
    pub fn new() -> Self { Self { state: 0 } }
}

impl Spinner for Counter16 {
    fn set(&mut self, state: u32) { self.state = state as u8 % COUNTER16_STATES.len() as u8; }
    fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8) % COUNTER16_STATES.len() as u8; }
}

impl Display for Counter16 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_char(*unsafe { COUNTER16_STATES.get_unchecked(self.state as usize) })
    }
}

/// A spinner that cycles through 4 states with a single spinning block element
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct Spinner4 {
    state: u8
}

const SPINNER4_STATES: [char; 4] = ['▖', '▘', '▝', '▗'];

impl Spinner4 {
    pub fn new() -> Self { Self { state: 0 } }
}

impl Spinner for Spinner4 {
    fn set(&mut self, state: u32) { self.state = state as u8 % SPINNER4_STATES.len() as u8; }
    fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8) % SPINNER4_STATES.len() as u8; }
}

impl Display for Spinner4 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_char(*unsafe { SPINNER4_STATES.get_unchecked(self.state as usize) })
    }
}

/// A spinner that cycles through many states with a snake made of 1-6 braille dots
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)]
pub struct Snake {
    state: u32
}

impl Snake {
    pub fn new() -> Self { Self { state: 0 } }
}

impl Spinner for Snake {
    fn set(&mut self, state: u32) { self.state = state; }
    fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count); }
}

impl Display for Snake {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        const WOBBLE: u32 = 5;
        let length = (((self.state % (2*WOBBLE)) as i32 - (WOBBLE as i32)).abs() + 1) as u32;
        let bits = !(0xFFu8 << length);
        let position = (WOBBLE * (self.state / (2*WOBBLE)) + (self.state % (2*WOBBLE)).saturating_sub(WOBBLE)) as u8;
        let snake = bits.rotate_right(position as u32);
        // Reverse most significant nybble
        let value = snake & 0xF
            | ((snake & 0b10000000) >> 3)
            | ((snake & 0b01000000) >> 1)
            | ((snake & 0b00100000) << 1)
            | ((snake & 0b00010000) << 3);
        f.write_char(braille_binary(value))
    }
}

/// Exponential moving average, useful for computing throughput
#[derive(Debug, Copy, Clone)]
pub struct MovingAverage {
    alpha: f32,
    value: f32,
}

impl MovingAverage {
    /// `alpha` is in (0, 1] describing how responsive to be to each update
    pub fn new(alpha: f32, initial: f32) -> Self { Self { alpha, value: initial } }

    /// Update with a new sample
    pub fn update(&mut self, value: f32) {
        self.value = self.alpha * value + (1.0 - self.alpha) * self.value;
    }

    /// Get the current average value
    pub fn get(&self) -> f32 { self.value }
}

/// Given an exact value `x`, return the same value scaled to the nearest lesser binary prefix, and the prefix in
/// question.
pub fn binary_prefix(x: f64) -> (f64, Option<&'static str>) {
    const TABLE: [&'static str; 8] = [
        "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"
    ];

    let mut divisor = 1024.0;
    if x < divisor { return (x, None); }
    let (last, most) = TABLE.split_last().unwrap();
    for prefix in most {
        let next = divisor * 1024.0;
        if next > x {
            return (x / divisor, Some(prefix));
        }
        divisor = next;
    }
    (x / divisor, Some(last))
}

/// Given an exact value `x`, return the same value scaled to the nearest lesser SI prefix, and the prefix in question.
pub fn si_prefix(x: f64) -> (f64, Option<&'static str>) {
    const TABLE: [&'static str; 8] = [
        "K", "M", "G", "T", "P", "E", "Z", "Y"
    ];

    let mut divisor = 1000.0;
    if x < divisor { return (x, None); }
    let (last, most) = TABLE.split_last().unwrap();
    for prefix in most {
        let next = divisor * 1e3;
        if next > x {
            return (x / divisor, Some(prefix));
        }
        divisor = next;
    }
    (x / divisor, Some(last))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bar_sanity() {
        let mut bar = Bar::new();
        assert_eq!(format!("{:10}", bar), "          ");
        bar.set(1.0);
        assert_eq!(format!("{:10}", bar), "██████████");
    }

    #[test]
    fn binary_prefixes() {
        assert_eq!(binary_prefix(2.0 * 1024.0), (2.0, Some("Ki")));
        assert_eq!(binary_prefix(2.0 * 1024.0 * 1024.0), (2.0, Some("Mi")));
    }

    #[test]
    fn si_prefixes() {
        assert_eq!(si_prefix(2e3), (2.0, Some("K")));
        assert_eq!(si_prefix(2e6), (2.0, Some("M")));
    }
}