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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//------------------------------------------------------------------------------------------------//
// other modules

use io::stdout;
use io::Write;
use std::cmp::min;
use std::fmt;
use std::io;
use std::ops;

//------------------------------------------------------------------------------------------------//

pub trait Bar: fmt::Display {
    fn bar_len(&self) -> usize;

    /// Do not shorten the length before reprinting since the line will be overwritten, not cleared.
    ///
    /// `[========> ]` becomes `[====>]==> ]` instead of `[====>]     `.
    fn set_bar_len(&mut self, new_bar_len: usize);

    /// Returns the printable progressbar.
    fn display(&self) -> String {
        format!("{}", self)
    }

    fn write_to_stdout<S: Into<String>>(&self, msg: S) -> Result<(), String> {
        let mut output = stdout();
        match output.write(msg.into().as_bytes()) {
            Ok(_) => (),
            Err(e) => return Err(format!("{}", e)),
        };
        match output.flush() {
            Ok(_) => (),
            Err(e) => return Err(format!("{}", e)),
        };

        Ok(())
    }

    /// Prints a progressbar using given progress.
    /// Does not print a newline-character.
    /// Use `println(...)` for printing a newline-character.
    /// Use `reprint(...)` for overwriting the current stdout-line.
    ///
    /// Will return error if writing to `stdout` throws an error.
    fn print(&self) -> Result<(), String> {
        self.write_to_stdout(format!("{}", self))
    }

    /// Prints a progressbar using given progress.
    /// In additon to `print(...)`, this function prints a new line.
    /// Use `reprintln(...)` for overwriting the current stdout-line.
    ///
    /// Will return error if writing to `stdout` throws an error.
    fn println(&self) -> Result<(), String> {
        self.write_to_stdout(format!("{}\n", self))
    }

    /// Prints the current line again with progressbar using given progress.
    /// Does not print a newline-character.
    /// Use `reprintln(...)` for reprinting with a newline-character.
    ///
    /// Will return error if writing to `stdout` throws an error.
    fn reprint(&self) -> Result<(), String> {
        self.write_to_stdout(format!("\r{}", self))
    }

    /// Prints the current line again with progressbar using given progress.
    /// In additon to `reprint(...)`, this function prints a new line.
    /// Use `println(...)` for always printing a newline-character.
    ///
    /// Will return error if writing to `stdout` throws an error.
    fn reprintln(&self) -> Result<(), String> {
        self.write_to_stdout(format!("\r{}\n", self))
    }

    //--------------------------------------------------------------------------------------------//

    type Progress;

    fn progress(&self) -> Self::Progress;

    /// Sets the progress to the given value
    fn set<P: Into<Self::Progress>>(&mut self, new_progress: P) -> &mut Self;

    /// Adds the given progress to the current progress
    fn add<P: Into<Self::Progress>>(&mut self, delta: P) -> &mut Self;
}

//------------------------------------------------------------------------------------------------//
// default bar clamping to [0; 1]

/// Only optimized for single-length-strings, but strings are more handy than chars.
#[derive(Debug)]
pub struct ClampingBar {
    bar_len: usize,
    prefix: String,
    left_bracket: String,
    right_bracket: String,
    line: String,
    empty_line: String,
    hat: String,
    progress: f32,
}

impl Default for ClampingBar {
    fn default() -> Self {
        ClampingBar {
            bar_len: 42,
            prefix: String::from(""),
            left_bracket: String::from("["),
            right_bracket: String::from("]"),
            line: String::from("="),
            empty_line: String::from(" "),
            hat: String::from(">"),
            progress: 0.0,
        }
    }
}

impl ClampingBar {
    pub fn new() -> ClampingBar {
        ClampingBar {
            ..Default::default()
        }
    }

    pub fn from(bar_len: usize, prefix: String) -> ClampingBar {
        ClampingBar {
            bar_len,
            prefix,
            ..Default::default()
        }
    }

    fn inner_bar_len(&self) -> usize {
        self.bar_len() - self.brackets_len()
    }

    fn brackets_len(&self) -> usize {
        self.left_bracket.len() + self.right_bracket.len()
    }
}

impl Bar for ClampingBar {
    type Progress = f32;

    fn bar_len(&self) -> usize {
        self.bar_len
    }

    /// panics if length is `< 3`
    fn set_bar_len(&mut self, new_bar_len: usize) {
        assert!(new_bar_len > self.brackets_len());
        self.bar_len = new_bar_len;
    }

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

    fn set<P: Into<f32>>(&mut self, new_progress: P) -> &mut Self {
        let mut new_progress = new_progress.into();

        if new_progress < 0.0 {
            new_progress = 0.0;
        }
        if 1.0 < new_progress {
            new_progress = 1.0;
        }
        self.progress = new_progress;
        self
    }

    fn add<P: Into<f32>>(&mut self, delta: P) -> &mut Self {
        self.set(self.progress + delta.into())
    }
}

impl fmt::Display for ClampingBar {
    /// Progress is clamped to `[0, 1]`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // calc progress
        // -> bar needs to be calculated
        // -> no brackets involved
        let reached = (self.progress * (self.inner_bar_len() as f32)) as usize;

        let line = self.line.repeat(reached);
        // crop hat if end of bar is reached
        let hat = &self.hat[0..min(self.hat.len(), self.inner_bar_len() - reached)];
        // fill up rest with empty line
        let empty_line = self
            .empty_line
            .repeat(self.inner_bar_len() - reached - hat.len());
        let bar = format!("{}{}{}", line, hat, empty_line);
        write!(
            f,
            "{}{}{}{}",
            self.prefix, self.left_bracket, bar, self.right_bracket
        )
    }
}

//------------------------------------------------------------------------------------------------//
// bar mapping [min, max] to [0, 1]

#[derive(Debug)]
pub struct MappingBar<N> {
    bar: ClampingBar,
    range: ops::RangeInclusive<N>,
    k: N,
}

impl<N> MappingBar<N>
where
    MappingBar<N>: Default,
{
    pub fn new(range: ops::RangeInclusive<N>) -> MappingBar<N> {
        MappingBar {
            range,
            ..Default::default()
        }
    }
}

//------------------------------------------------------------------------------------------------//

impl Default for MappingBar<u32> {
    fn default() -> Self {
        MappingBar {
            bar: ClampingBar::default(),
            range: 0..=100,
            k: 0,
        }
    }
}

impl MappingBar<u32> {
    fn start(&self) -> u32 {
        *(self.range.start())
    }

    fn end(&self) -> u32 {
        *(self.range.end())
    }
}

impl Bar for MappingBar<u32> {
    type Progress = u32;

    fn bar_len(&self) -> usize {
        self.bar.bar_len()
    }

    fn set_bar_len(&mut self, new_bar_len: usize) {
        self.bar.set_bar_len(new_bar_len)
    }

    fn progress(&self) -> u32 {
        self.k
    }

    fn set<P: Into<u32>>(&mut self, new_progress: P) -> &mut Self {
        let new_progress = new_progress.into();
        self.k = new_progress;

        // calculate new progress
        let k_min = self.start() as f32;
        let k_max = self.end() as f32;
        let k = new_progress as f32;
        self.bar.set((k - k_min) / (k_max - k_min));

        // return self
        self
    }

    fn add<P: Into<u32>>(&mut self, delta: P) -> &mut Self {
        self.set(self.k + delta.into())
    }
}

impl fmt::Display for MappingBar<u32> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({} / {})", self.bar, self.k, self.end())
    }
}

//------------------------------------------------------------------------------------------------//

impl Default for MappingBar<i32> {
    fn default() -> Self {
        MappingBar {
            bar: ClampingBar::default(),
            range: 0..=100,
            k: 0,
        }
    }
}

impl MappingBar<i32> {
    fn start(&self) -> i32 {
        *(self.range.start())
    }

    fn end(&self) -> i32 {
        *(self.range.end())
    }
}

impl Bar for MappingBar<i32> {
    type Progress = i32;

    fn bar_len(&self) -> usize {
        self.bar.bar_len()
    }

    fn set_bar_len(&mut self, new_bar_len: usize) {
        self.bar.set_bar_len(new_bar_len)
    }

    fn progress(&self) -> i32 {
        self.k
    }

    fn set<P: Into<i32>>(&mut self, new_progress: P) -> &mut Self {
        let new_progress = new_progress.into();
        self.k = new_progress;

        // calculate new progress
        let k_min = self.start() as f32;
        let k_max = self.end() as f32;
        let k = new_progress as f32;
        self.bar.set((k - k_min) / (k_max - k_min));

        // return self
        self
    }

    fn add<P: Into<i32>>(&mut self, delta: P) -> &mut Self {
        self.set(self.k + delta.into())
    }
}

impl fmt::Display for MappingBar<i32> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({} / {})", self.bar, self.k, self.end())
    }
}

//------------------------------------------------------------------------------------------------//
// bar counting success and failures

#[derive(Copy, Clone)]
pub struct BernoulliProgress {
    pub successes: u32,
    pub attempts: u32,
}

impl BernoulliProgress {
    pub fn new() -> Self {
        BernoulliProgress {
            successes: 0,
            attempts: 0,
        }
    }
}

impl From<(u32, u32)> for BernoulliProgress {
    fn from((successes, attempts): (u32, u32)) -> Self {
        BernoulliProgress {
            successes,
            attempts,
        }
    }
}

impl From<u32> for BernoulliProgress {
    fn from(successes: u32) -> Self {
        BernoulliProgress {
            successes,
            attempts: successes,
        }
    }
}

impl From<bool> for BernoulliProgress {
    fn from(is_successful: bool) -> Self {
        let successes = if is_successful { 1 } else { 0 };
        BernoulliProgress {
            successes,
            attempts: 1,
        }
    }
}

impl ops::Add for BernoulliProgress {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            successes: self.successes + other.successes,
            attempts: self.attempts + other.attempts,
        }
    }
}

impl ops::AddAssign for BernoulliProgress {
    fn add_assign(&mut self, other: Self) {
        *self = *self + other;
    }
}

//------------------------------------------------------------------------------------------------//

#[derive(Debug)]
pub struct BernoulliBar {
    bar: MappingBar<u32>,
    attempts: u32,
}

impl Default for BernoulliBar {
    fn default() -> Self {
        BernoulliBar {
            bar: MappingBar::default(),
            attempts: 0,
        }
    }
}

impl BernoulliBar {
    pub fn from_goal(n: u32) -> BernoulliBar {
        BernoulliBar {
            bar: MappingBar::new(0..=n),
            ..Default::default()
        }
    }
}

impl Bar for BernoulliBar {
    type Progress = BernoulliProgress;

    fn bar_len(&self) -> usize {
        self.bar.bar_len()
    }

    fn set_bar_len(&mut self, new_bar_len: usize) {
        self.bar.set_bar_len(new_bar_len)
    }

    fn progress(&self) -> BernoulliProgress {
        BernoulliProgress {
            successes: self.bar.progress(),
            attempts: self.attempts,
        }
    }

    fn set<P: Into<BernoulliProgress>>(&mut self, outcome: P) -> &mut Self {
        let outcome = outcome.into();
        self.bar.set(outcome.successes);
        self.attempts = outcome.attempts;
        self
    }

    fn add<P: Into<BernoulliProgress>>(&mut self, outcome: P) -> &mut Self {
        self.set(self.progress() + outcome.into())
    }
}

impl fmt::Display for BernoulliBar {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} ({} / {} # {})",
            self.bar.bar,
            self.bar.k,
            self.bar.end(),
            self.attempts
        )
    }
}