1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9
10pub const SPLIT: usize = 0;
12pub const VALIDATE: usize = 1;
13pub const PARSE: usize = 2;
14pub const EXPORT: usize = 3;
15pub const MERGE: usize = 4;
16pub const COUNT: usize = 5;
18
19pub const NAMES: [&str; COUNT] = ["split", "validate", "parse", "export", "merge"];
21
22static ENABLED: AtomicBool = AtomicBool::new(false);
23static NANOS: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT];
24static CALLS: [AtomicU64; COUNT] = [const { AtomicU64::new(0) }; COUNT];
25
26#[inline]
28pub fn enabled() -> bool {
29 ENABLED.load(Ordering::Relaxed)
30}
31
32pub fn reset() {
34 for i in 0..COUNT {
35 NANOS[i].store(0, Ordering::Relaxed);
36 CALLS[i].store(0, Ordering::Relaxed);
37 }
38 ENABLED.store(true, Ordering::Relaxed);
39}
40
41pub fn disable() {
43 ENABLED.store(false, Ordering::Relaxed);
44}
45
46#[inline]
48pub fn add(stage: usize, nanos: u64) {
49 if enabled() {
50 NANOS[stage].fetch_add(nanos, Ordering::Relaxed);
51 CALLS[stage].fetch_add(1, Ordering::Relaxed);
52 }
53}
54
55pub fn snapshot() -> Vec<(&'static str, u64, u64)> {
57 (0..COUNT)
58 .map(|i| {
59 (
60 NAMES[i],
61 NANOS[i].load(Ordering::Relaxed),
62 CALLS[i].load(Ordering::Relaxed),
63 )
64 })
65 .collect()
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 #[test]
73 fn counters_accumulate_only_while_enabled() {
74 disable();
75 add(PARSE, 100);
76 assert_eq!(snapshot()[PARSE].1, 0, "no accounting while disabled");
77
78 reset();
79 add(PARSE, 5);
80 add(PARSE, 7);
81 let s = snapshot();
82 assert_eq!(s[PARSE].1, 12);
83 assert_eq!(s[PARSE].2, 2);
84 assert_eq!(s[SPLIT].1, 0);
85 disable();
86 }
87}