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
pub use pbr::ProgressBar;
use std::io::Stdout;
use std::os::raw::{c_int, c_void};

/// A trait that is used to report progress to some consumer.
pub trait ProgressReporter: Send {
    /// Increase the progress counter. Return `false` to abort processing.
    fn increase(&mut self) -> bool;

    /// Mark the progress as done.
    fn done(&mut self, msg: &str);
}

/// No-op progress reporter
pub struct NoProgress {}

/// For C
pub struct ProgressCallback {
    callback: unsafe extern "C" fn(*mut c_void) -> c_int,
    arg: *mut c_void,
}

unsafe impl Send for ProgressCallback {}

impl ProgressCallback {
    pub fn new(callback: unsafe extern "C" fn(*mut c_void) -> c_int, arg: *mut c_void) -> Self {
        Self { callback, arg }
    }
}

impl ProgressReporter for NoProgress {
    fn increase(&mut self) -> bool {
        true
    }
    fn done(&mut self, _msg: &str) {}
}

impl ProgressReporter for ProgressCallback {
    fn increase(&mut self) -> bool {
        unsafe { (self.callback)(self.arg) == 1 }
    }
    fn done(&mut self, _msg: &str) {}
}

/// Implement the progress reporter trait for a progress bar,
/// to make it usable for frame processing reporting.
impl ProgressReporter for ProgressBar<Stdout> {
    fn increase(&mut self) -> bool {
        self.inc();
        true
    }

    fn done(&mut self, msg: &str) {
        self.finish_print(msg);
    }
}