Skip to content

Commit

Permalink
Provide a method to reset a counter
Browse files Browse the repository at this point in the history
  • Loading branch information
zakcutner committed May 28, 2024
1 parent 721d6b0 commit 3c27c22
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/metrics/counter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ impl<N, A: Atomic<N>> Counter<N, A> {
self.value.inc_by(v)
}

/// Resets the [`Counter`] to `0`, returning the previous value.
pub fn reset(&self) -> N {
self.value.reset()
}

/// Get the current value of the [`Counter`].
pub fn get(&self) -> N {
self.value.get()
Expand All @@ -110,6 +115,9 @@ pub trait Atomic<N> {
/// Increase the value.
fn inc_by(&self, v: N) -> N;

/// Reset the value to `0`.
fn reset(&self) -> N;

/// Get the the value.
fn get(&self) -> N;
}
Expand All @@ -124,6 +132,10 @@ impl Atomic<u64> for AtomicU64 {
self.fetch_add(v, Ordering::Relaxed)
}

fn reset(&self) -> u64 {
self.swap(Default::default(), Ordering::Relaxed)
}

fn get(&self) -> u64 {
self.load(Ordering::Relaxed)
}
Expand All @@ -138,6 +150,10 @@ impl Atomic<u32> for AtomicU32 {
self.fetch_add(v, Ordering::Relaxed)
}

fn reset(&self) -> u32 {
self.swap(Default::default(), Ordering::Relaxed)
}

fn get(&self) -> u32 {
self.load(Ordering::Relaxed)
}
Expand All @@ -164,6 +180,10 @@ impl Atomic<f64> for AtomicU64 {
old_f64
}

fn reset(&self) -> f64 {
f64::from_bits(self.swap(Default::default(), Ordering::Relaxed))
}

fn get(&self) -> f64 {
f64::from_bits(self.load(Ordering::Relaxed))
}
Expand Down Expand Up @@ -231,6 +251,14 @@ mod tests {
assert_eq!(1, counter.get());
}

#[test]
fn inc_reset_and_get() {
let counter: Counter = Counter::default();
assert_eq!(0, counter.inc());
assert_eq!(1, counter.reset());
assert_eq!(0, counter.get());
}

#[cfg(not(any(target_arch = "mips", target_arch = "powerpc")))]
#[test]
fn f64_stored_in_atomic_u64() {
Expand Down

0 comments on commit 3c27c22

Please sign in to comment.