msg_tool\utils/
counter.rs

1//! A simple counter for tracking script execution results.
2use crate::types::*;
3use std::sync::atomic::AtomicUsize;
4use std::sync::atomic::Ordering::SeqCst;
5
6/// A counter for tracking script execution results.
7pub struct Counter {
8    ok: AtomicUsize,
9    ignored: AtomicUsize,
10    error: AtomicUsize,
11    warning: AtomicUsize,
12}
13
14impl Counter {
15    /// Creates a new Counter instance.
16    pub fn new() -> Self {
17        Self {
18            ok: AtomicUsize::new(0),
19            ignored: AtomicUsize::new(0),
20            error: AtomicUsize::new(0),
21            warning: AtomicUsize::new(0),
22        }
23    }
24
25    /// Increments the count of errors.
26    pub fn inc_error(&self) {
27        self.error.fetch_add(1, SeqCst);
28    }
29
30    /// Increments the count of warnings.
31    pub fn inc_warning(&self) {
32        self.warning.fetch_add(1, SeqCst);
33    }
34
35    /// Increments the count of script executions.
36    pub fn inc(&self, result: ScriptResult) {
37        match result {
38            ScriptResult::Ok => {
39                self.ok.fetch_add(1, SeqCst);
40            }
41            ScriptResult::Ignored => {
42                self.ignored.fetch_add(1, SeqCst);
43            }
44            ScriptResult::Uncount => {}
45        }
46    }
47
48    /// Returns true if all jobs failed. (ok == 0 && error > 0)
49    pub fn all_failed(&self) -> bool {
50        let ok = self.ok.load(SeqCst);
51        let error = self.error.load(SeqCst);
52        ok == 0 && error > 0
53    }
54
55    /// Returns true if there were any errors.
56    pub fn has_error(&self) -> bool {
57        let error = self.error.load(SeqCst);
58        error > 0
59    }
60}
61
62impl std::fmt::Display for Counter {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(
65            f,
66            "OK: {}, Ignored: {}, Error: {}, Warning: {}",
67            self.ok.load(SeqCst),
68            self.ignored.load(SeqCst),
69            self.error.load(SeqCst),
70            self.warning.load(SeqCst),
71        )
72    }
73}