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
// Copyright (C) 2024  The Software Heritage developers
// See the AUTHORS file at the top-level directory of this distribution
// License: GNU General Public License version 3, or any later version
// See top-level LICENSE file for more information

use std::ops::DerefMut;
use std::sync::{Arc, Mutex};

use dsi_progress_logger::ProgressLog;

pub const DEFAULT_THRESHOLD: u16 = 32768;

/// Like [`ProgressLog`], but only allows updates (ie. no start/stop/done/configuration)
pub trait MinimalProgressLog {
    fn update(&mut self);
    fn update_with_count(&mut self, count: usize);
    fn light_update(&mut self);
    fn update_and_display(&mut self);
}

impl<T: ProgressLog> MinimalProgressLog for T {
    fn update(&mut self) {
        ProgressLog::update(self)
    }
    fn update_with_count(&mut self, count: usize) {
        ProgressLog::update_with_count(self, count)
    }
    fn light_update(&mut self) {
        ProgressLog::light_update(self)
    }
    fn update_and_display(&mut self) {
        ProgressLog::update_and_display(self)
    }
}

#[derive(Debug)]
/// A wrapper for `Arc<Mutex<ProgressLog>>` that buffers writes to the underlying
/// [`ProgressLog`] to avoid taking the lock too often.
///
/// This is useful when writing to a common [`ProgressLog`] from multiple threads.
pub struct BufferedProgressLogger<T: DerefMut<Target: MinimalProgressLog>> {
    inner: Arc<Mutex<T>>,
    count: u16,
    threshold: u16,
}

impl<T: DerefMut<Target: MinimalProgressLog>> BufferedProgressLogger<T> {
    pub fn new(pl: Arc<Mutex<T>>) -> Self {
        Self::with_threshold(pl, DEFAULT_THRESHOLD)
    }

    /// Creates a new `BufferedProgressLogger` that buffers its writes up to `threshold`,
    /// before flushing to the underlying [`MinimalProgressLog`].
    pub fn with_threshold(pl: Arc<Mutex<T>>, threshold: u16) -> Self {
        Self {
            inner: pl,
            count: 0,
            threshold,
        }
    }

    pub fn inner(&self) -> &Arc<Mutex<T>> {
        &self.inner
    }

    pub fn flush(&mut self) {
        if self.count > 0 {
            self.inner
                .lock()
                .unwrap()
                .update_with_count(self.count.into());
            self.count = 0;
        }
    }
}

impl<T: DerefMut<Target: MinimalProgressLog>> MinimalProgressLog for BufferedProgressLogger<T> {
    #[inline(always)]
    fn update(&mut self) {
        self.update_with_count(1)
    }
    #[inline(always)]
    fn update_with_count(&mut self, count: usize) {
        match usize::from(self.count).checked_add(count) {
            None => {
                // Sum overflows, update in two steps
                let mut inner = self.inner.lock().unwrap();
                inner.update_with_count(self.count.into());
                inner.update_with_count(count);
                self.count = 0;
            }
            Some(total_count) => {
                if total_count >= usize::from(self.threshold) {
                    // Threshold reached, time to flush to the inner ProgressLog
                    let mut inner = self.inner.lock().unwrap();
                    inner.update_with_count(total_count);
                    self.count = 0;
                } else {
                    // total_count is lower than self.threshold, which is a u16;
                    // so total_count fits in u16.
                    self.count = total_count as u16;
                }
            }
        }
    }
    #[inline(always)]
    fn light_update(&mut self) {
        self.update_with_count(1)
    }
    #[inline(always)]
    fn update_and_display(&mut self) {
        let mut inner = self.inner.lock().unwrap();
        inner.update_with_count(self.count.into());
        self.count = 0;
        inner.update_and_display()
    }
}

/// Flush count buffer to the inner [`MinimalProgressLog`]
impl<T: DerefMut<Target: MinimalProgressLog>> Drop for BufferedProgressLogger<T> {
    fn drop(&mut self) {
        if self.count > 0 {
            self.inner
                .lock()
                .unwrap()
                .update_with_count(self.count.into());
            self.count = 0;
        }
    }
}

impl<T: DerefMut<Target: MinimalProgressLog>> Clone for BufferedProgressLogger<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            count: 0, // Not copied or it would cause double-counting!
            threshold: self.threshold,
        }
    }
}

#[derive(Debug)]
/// A wrapper for [`ProgressLog`] that provides access to the total counter.
pub struct CountingProgressLogger<T: DerefMut<Target: ProgressLog>> {
    inner: T,
    count: usize,
}

impl<T: DerefMut<Target: ProgressLog>> CountingProgressLogger<T> {
    pub fn new(pl: T) -> Self {
        CountingProgressLogger {
            inner: pl,
            count: 0,
        }
    }

    pub fn inner(&self) -> &T {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.inner
    }

    pub fn into_inner(self) -> T {
        self.inner
    }

    /// Returns the current counter value
    pub fn total(&self) -> usize {
        self.count
    }
}

impl<T: DerefMut<Target: ProgressLog>> MinimalProgressLog for CountingProgressLogger<T> {
    fn update(&mut self) {
        self.count += 1;
        self.inner.update()
    }
    fn update_with_count(&mut self, count: usize) {
        self.count += count;
        self.inner.update_with_count(count)
    }
    fn light_update(&mut self) {
        self.count += 1;
        self.inner.light_update()
    }
    fn update_and_display(&mut self) {
        self.count += 1;
        self.inner.update_and_display()
    }
}