pistonite-cu 0.8.2

Battery-included common utils to speed up development of rust tools
Documentation
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use std::sync::{Arc, Mutex};
use std::time::Instant;

use crate::cli::Tick;
use crate::cli::fmt::ansi;
use crate::cli::printer::PRINTER;
use crate::cli::progress::{
    BarFormatter, BarResult, ChildState, ChildStateStrong, Estimater, ProgressBarBuilder,
};

const CHAR_BAR_TICK: char = '\u{251C}'; // |>
const CHAR_BAR: char = '\u{2502}'; // |
const CHAR_TICK: char = '\u{2514}'; // >

/// Handle for a progress bar (This is the internal state, the handle is `Arc<ProgressBar>`)
///
/// See [Progress Bars](fn@crate::progress)
#[derive(Debug)]
pub struct ProgressBar {
    pub(crate) state: StateImmut,
    state_mut: Mutex<State>,
}
impl ProgressBar {
    pub(crate) fn spawn(
        state: StateImmut,
        state_mut: State,
        parent: Option<Arc<Self>>,
    ) -> Arc<Self> {
        let bar = Arc::new(Self {
            state,
            state_mut: Mutex::new(state_mut),
        });
        match parent {
            Some(p) => {
                if let Ok(mut p) = p.state_mut.lock() {
                    p.add_child(&bar);
                }
            }
            None => {
                if let Ok(mut printer) = PRINTER.lock() {
                    if let Some(printer) = printer.as_mut() {
                        printer.add_progress_bar(&bar);
                    }
                }
            }
        }
        bar
    }
    #[doc(hidden)]
    #[inline(always)]
    pub fn __set(self: &Arc<Self>, current: u64, message: Option<String>) {
        if let Ok(mut bar) = self.state_mut.lock() {
            bar.unreal_current = current;
            if let Some(x) = message {
                bar.set_message(&x);
            }
        }
    }

    #[doc(hidden)]
    #[inline(always)]
    pub fn __inc(self: &Arc<Self>, amount: u64, message: Option<String>) {
        if let Ok(mut bar) = self.state_mut.lock() {
            bar.unreal_current = bar.unreal_current.saturating_add(amount);
            if let Some(x) = message {
                bar.set_message(&x);
            }
        }
    }

    /// Set the total steps (if the progress is finite)
    pub fn set_total(&self, total: u64) {
        if total == 0 {
            // 0 is a special value, so we do not allow setting it
            return;
        }
        if let Ok(mut bar) = self.state_mut.lock() {
            bar.unreal_total = total;
        }
    }

    /// Start building a child progress bar
    ///
    /// Note that the child builder will keep this bar alive (displayed), even
    /// if the child is not spawned
    #[inline(always)]
    pub fn child(self: &Arc<Self>, message: impl Into<String>) -> ProgressBarBuilder {
        ProgressBarBuilder::new(message.into()).parent(Some(Arc::clone(self)))
    }

    /// Set the message to be printed and mark the bar as done
    pub fn done_with_message(self: Arc<Self>, message: &str) {
        self.set_done_message(message);
        self.done();
    }

    /// Set the message to be printed and mark the bar as done
    pub fn done_by_ref_with_message(&self, message: &str) {
        self.set_done_message(message);
        self.done_by_ref();
    }

    /// Change the message to be printed when the bar is done.
    /// Useful if information is not available yet when the bar is spawned.
    ///
    /// This does NOT mark the bar as done, use [`done_with_message`](Self::done_with_message)
    /// for that.
    pub fn set_done_message(&self, message: &str) {
        if let Ok(mut bar) = self.state_mut.lock() {
            bar.set_done_message(message);
        }
    }

    /// Change the message to be printed when the bar is interrupted.
    /// Useful if information is not available yet when the bar is spawned.
    pub fn set_interrupted_message(&self, message: &str) {
        if let Ok(mut bar) = self.state_mut.lock() {
            bar.set_interrupted_message(message);
        }
    }

    /// Mark the progress bar as done and drop the handle.
    ///
    /// This needs to be called if the bar is unbounded. Otherwise,
    /// the bar will display in the interrupted state when dropped.
    ///
    /// If the progress is finite, then interrupted state is automatically
    /// determined (`current != total`)
    pub fn done(self: Arc<Self>) {
        if self.state.unbounded {
            if let Ok(mut bar) = self.state_mut.lock() {
                bar.unreal_current = 1;
                bar.unreal_total = 1;
            }
        }
    }

    /// Same as [`done`](Self::done), but does not drop the bar.
    pub fn done_by_ref(&self) {
        if self.state.unbounded {
            if let Ok(mut bar) = self.state_mut.lock() {
                bar.unreal_current = 1;
                bar.unreal_total = 1;
            }
        }
    }

    /// Format the bar
    #[inline(always)]
    pub(crate) fn format(&self, fmt: &mut BarFormatter<'_, '_, '_>) -> i32 {
        self.format_at_depth(0, &mut String::new(), fmt)
    }

    /// Format the bar at depth
    fn format_at_depth(
        &self,
        depth: usize,
        hierarchy: &mut String,
        fmt: &mut BarFormatter<'_, '_, '_>,
    ) -> i32 {
        let Ok(mut bar) = self.state_mut.lock() else {
            return 0;
        };
        bar.format_at_depth(depth, hierarchy, fmt, &self.state)
    }
}

impl Drop for ProgressBar {
    fn drop(&mut self) {
        let result = match self.state_mut.lock() {
            Err(_) => BarResult::DontKeep,
            Ok(bar) => bar.check_result(&self.state),
        };
        if let Some(parent) = &self.state.parent {
            // inform parent our result
            if let Ok(mut parent_state) = parent.state_mut.lock() {
                parent_state.child_done(self.state.id, result.clone());
            }
        }
        let handle = {
            // scope for printer lock
            let Ok(mut printer) = PRINTER.lock() else {
                return;
            };
            let Some(printer) = printer.as_mut() else {
                return;
            };
            printer.print_bar_done(&result, self.state.parent.is_none());
            printer.take_print_task_if_should_join()
        };
        if let Some(x) = handle {
            let _: Result<(), _> = x.join();
        }
    }
}

/// Internal, immutable state of progress bar
#[derive(Debug)]
pub struct StateImmut {
    /// An ID
    pub id: usize,
    /// Parent of this bar
    pub parent: Option<Arc<ProgressBar>>,
    /// The prefix message (corresponds to message in the builder)
    pub prefix: String,
    /// If percentage field is shown
    pub show_percentage: bool,
    /// If the steps are unbounded
    pub unbounded: bool,
    /// Display the progress using bytes format
    pub display_bytes: bool,
    /// Max number of children to display,
    /// children after the limit will only display one line "... and X more"
    pub max_display_children: usize,
}

/// Internal mutable state
#[derive(Debug)]
pub struct State {
    unreal_total: u64,
    unreal_current: u64,
    message: String,
    /// None means don't keep the progress bar printed
    /// (the default done message is formatted at spawn time)
    done_message: Option<String>,
    /// None means use the default
    interrupted_message: Option<String>,
    eta: Option<Estimater>,
    children: Vec<ChildState>,
}
impl State {
    pub fn new(
        total: u64,
        eta: Option<Estimater>,
        done_message: Option<String>,
        interrupted_message: Option<String>,
    ) -> Self {
        Self {
            unreal_total: total,
            unreal_current: 0,
            message: String::new(),
            done_message,
            interrupted_message,
            eta,
            children: vec![],
        }
    }
    #[inline(always)]
    fn estimate_remaining(
        &mut self,
        unbounded: bool,
        now: &mut Option<Instant>,
        tick: Tick,
    ) -> Option<f32> {
        if unbounded || self.unreal_total == 0 {
            return None;
        }
        self.eta.as_mut()?.update(
            now,
            self.unreal_current.min(self.unreal_total),
            self.unreal_total,
            tick,
        )
    }
    #[inline(always)]
    fn real_current_total(&self, unbounded: bool) -> (u64, Option<u64>) {
        if unbounded {
            (0, None)
        } else if self.unreal_total == 0 {
            // total not known
            (self.unreal_current, None)
        } else {
            (
                self.unreal_current.min(self.unreal_total),
                Some(self.unreal_total),
            )
        }
    }

    pub fn add_child(&mut self, child: &Arc<ProgressBar>) {
        self.children
            .push(ChildState::Progress(child.state.id, Arc::downgrade(child)))
    }

    pub fn child_done(&mut self, child_id: usize, mut result: BarResult) {
        self.children.retain_mut(|child| {
            let ChildState::Progress(id, _) = child else {
                return true;
            };
            if *id != child_id {
                return true;
            }
            match std::mem::take(&mut result) {
                BarResult::DontKeep => false,
                BarResult::Done(message) => {
                    *child = ChildState::Done(message);
                    true
                }
                BarResult::Interrupted(message) => {
                    *child = ChildState::Interrupted(message);
                    true
                }
            }
        });
    }

    pub fn check_result(&self, state: &StateImmut) -> BarResult {
        let is_interrupted = (self.unreal_current == 0 && self.unreal_total == 0)
            || (self.unreal_current < self.unreal_total);
        if !is_interrupted {
            match &self.done_message {
                None => BarResult::DontKeep,
                Some(message) => {
                    let message =
                        self.format_finish_message(message, state.unbounded, state.display_bytes);
                    BarResult::Done(message)
                }
            }
        } else {
            match &self.interrupted_message {
                None => {
                    let message = if state.prefix.is_empty() {
                        self.format_finish_message(
                            "interrupted",
                            state.unbounded,
                            state.display_bytes,
                        )
                    } else {
                        self.format_finish_message(
                            &format!("{}: interrupted", state.prefix),
                            state.unbounded,
                            state.display_bytes,
                        )
                    };
                    BarResult::Interrupted(message)
                }
                Some(message) => {
                    let message =
                        self.format_finish_message(message, state.unbounded, state.display_bytes);
                    BarResult::Interrupted(message)
                }
            }
        }
    }

    pub fn set_message(&mut self, message: &str) {
        self.message.clear();
        self.message.push_str(message);
    }

    pub fn set_done_message(&mut self, message: &str) {
        match &mut self.done_message {
            None => {
                self.done_message = Some(message.to_string());
            }
            Some(msg) => {
                msg.clear();
                msg.push_str(message);
            }
        }
    }

    pub fn set_interrupted_message(&mut self, message: &str) {
        match &mut self.interrupted_message {
            None => {
                self.interrupted_message = Some(message.to_string());
            }
            Some(msg) => {
                msg.clear();
                msg.push_str(message);
            }
        }
    }

    /// Format the bar into the out buffer at the depth
    ///
    /// If depth is 0, the animation character is already formatted.
    /// Otherwise, a "| " should be formatted into the out buffer
    /// at the beginning. The `width` passed in is terminal width minus 2.
    ///
    /// It should also format a new line character into the buffer
    ///
    /// Return number of lines formatted.
    pub fn format_at_depth(
        &mut self,
        depth: usize,
        hierarchy: &mut String,
        fmt: &mut BarFormatter<'_, '_, '_>,
        state: &StateImmut,
    ) -> i32 {
        self.format_self(fmt, fmt.width.saturating_sub((depth + 1) * 2), state);
        fmt.out.push('\n');
        let mut lines = 1;
        // process childrens
        let mut i = 0;
        let mut num_displayed = 0;
        let children_count = self.children.len();
        self.children.retain_mut(|child| {
            let out = &mut *fmt.out;
            let Some(child) = child.upgrade() else {
                i += 1;
                return false; // remove the finished child
            };
            if num_displayed >= state.max_display_children {
                num_displayed += 1;
                return true;
            }
            // format the multi-line syntax
            out.push_str(". ");
            out.push_str(fmt.colors.gray);
            out.push_str(hierarchy);
            if i == children_count - 1 {
                out.push(CHAR_TICK);
                hierarchy.push_str("  ");
            } else {
                out.push(CHAR_BAR_TICK);
                hierarchy.push(CHAR_BAR);
                hierarchy.push(' ');
            }
            out.push(' ');
            let width = fmt.width.saturating_sub((depth + 2) * 2);
            match child {
                ChildStateStrong::Done(message) => {
                    out.push_str(fmt.colors.green);
                    format_message_with_width(out, width, message);
                    out.push('\n');
                    lines += 1;
                    out.push_str(fmt.bar_color);
                }
                ChildStateStrong::Interrupted(message) => {
                    out.push_str(fmt.colors.yellow);
                    format_message_with_width(out, width, message);
                    out.push('\n');
                    lines += 1;
                    out.push_str(fmt.bar_color);
                }
                ChildStateStrong::Progress(child) => {
                    out.push_str(fmt.bar_color);
                    lines += child.format_at_depth(depth + 1, hierarchy, fmt);
                }
            }
            hierarchy.pop();
            hierarchy.pop();
            i += 1;
            num_displayed += 1;
            true
        });
        if num_displayed > state.max_display_children {
            // display the ... and more line
            let out = &mut *fmt.out;
            out.push_str("| ");
            out.push_str(fmt.colors.gray);
            for _ in 0..depth {
                out.push(CHAR_BAR);
                out.push(' ');
            }
            out.push(CHAR_TICK);
            out.push_str(fmt.colors.reset);
            use std::fmt::Write as _;
            let _ = write!(
                out,
                "  ... and {} more",
                num_displayed - state.max_display_children
            );
            out.push_str(fmt.bar_color);
            out.push('\n');
            lines += 1;
        }
        // return number of lines
        lines
    }

    fn format_self(
        &mut self,
        fmt: &mut BarFormatter<'_, '_, '_>,
        mut width: usize,
        state: &StateImmut,
    ) {
        use std::fmt::Write as _;
        let out = &mut *fmt.out;
        let temp = &mut *fmt.temp;

        // not enough width
        match width {
            0 => return,
            1 => {
                out.push('.');
                return;
            }
            2 => {
                out.push_str("..");
                return;
            }
            3 => {
                out.push_str("...");
                return;
            }
            4 => {
                out.push_str("[..]");
                return;
            }
            _ => {}
        }
        let (current, total) = self.real_current_total(state.unbounded);
        // --
        let show_current_total = !state.unbounded;
        let show_prefix = !state.prefix.is_empty();
        // -- :
        let show_percentage = state.show_percentage && total.is_some();
        let eta = self.estimate_remaining(state.unbounded, fmt.now, fmt.tick);
        let show_eta = eta.is_some();
        let show_message = !self.message.is_empty();

        struct Spacing {
            show_separator: bool,
            show_space_before_eta: bool,
            show_space_before_message: bool,
        }

        let spacing = if state.display_bytes {
            Spacing {
                show_separator: show_prefix
                    && (show_current_total || show_percentage || show_eta || show_message),
                show_space_before_eta: show_percentage || show_current_total,
                show_space_before_message: show_percentage || show_current_total || show_eta,
            }
        } else {
            Spacing {
                show_separator: show_prefix && (show_percentage || show_eta || show_message),
                show_space_before_eta: show_percentage,
                show_space_before_message: show_percentage || show_eta,
            }
        };

        if !state.display_bytes && show_current_total {
            temp.clear();
            // _: fmt for string does not fail
            let _ = match total {
                None => write!(temp, "{current}/?"),
                Some(total) => write!(temp, "{current}/{total}"),
            };

            // .len() is safe because / and numbers have the same byte size and width
            // -2 is safe because width > 4 here
            width -= 2;
            out.push('[');
            if temp.len() > width {
                // not enough space
                for _ in 0..width {
                    out.push('.');
                }
                out.push(']');
                return;
            }

            width -= temp.len();
            out.push_str(temp);
            out.push(']');
        }

        if width > 0 {
            out.push(' ');
            width -= 1;
        }

        if show_prefix {
            width = format_message_with_width(out, width, &state.prefix);
        }

        if spacing.show_separator && width > 2 {
            width -= 2;
            out.push_str(": ");
        }

        if state.display_bytes && show_current_total {
            temp.clear();
            // _: fmt for string does not fail
            let _ = match total {
                None => write!(temp, "{}", cu::ByteFormat(current)),
                Some(total) => write!(
                    temp,
                    "{} / {}",
                    cu::ByteFormat(current),
                    cu::ByteFormat(total)
                ),
            };

            if width >= temp.len() {
                width -= temp.len();
                out.push_str(temp);
            }

            if width > 0 {
                out.push(' ');
                width -= 1;
            }
        }

        if show_percentage {
            // unwrap: total is always Some
            let total = total.unwrap();
            if current == total {
                if width >= 4 {
                    width -= 4;
                    out.push_str("100%")
                }
            } else {
                let percentage = current as f32 * 100f32 / total as f32;
                temp.clear();
                // _: fmt for string does not fail
                let _ = write!(temp, "{percentage:.2}%");
                if width >= temp.len() {
                    width -= temp.len();
                    out.push_str(temp);
                }
            }
        }

        if let Some(eta) = eta {
            // ETA SS.SSs
            if spacing.show_space_before_eta && width > 0 {
                out.push(' ');
                width -= 1;
            }
            temp.clear();
            // _: fmt for string does not fail
            let _ = write!(temp, "ETA {eta:.2}s;");
            if width >= temp.len() {
                width -= temp.len();
                out.push_str(temp);
            }
        }

        if show_message {
            if spacing.show_space_before_message && width > 0 {
                out.push(' ');
                width -= 1;
            }
            format_message_with_width(out, width, &self.message);
        }
    }

    fn format_finish_message(&self, message: &str, unbounded: bool, in_bytes: bool) -> String {
        if unbounded {
            return message.to_string();
        }
        let (current, total) = self.real_current_total(unbounded);
        match (total, in_bytes) {
            (None, false) => {
                format!("[{current}/?] {message}")
            }
            (None, true) => {
                let current = cu::ByteFormat(current);
                format!("{message} ({current})")
            }
            (Some(total), false) => {
                format!("[{current}/{total}] {message}")
            }
            (Some(total), true) => {
                let current = cu::ByteFormat(current);
                let total = cu::ByteFormat(total);
                format!("{message} ({current} / {total})")
            }
        }
    }
}

fn format_message_with_width(out: &mut String, mut width: usize, message: &str) -> usize {
    for (c, w) in ansi::with_width(message.chars()) {
        if w > width {
            break;
        }
        width -= w;
        out.push(c);
    }
    width
}