Counter

Struct Counter 

Source
#[repr(align(64))]
pub struct Counter { /* private fields */ }
Expand description

Ultra-fast atomic counter

Optimized for maximum throughput with minimal memory overhead. Cache-line aligned to prevent false sharing.

Implementations§

Source§

impl Counter

Source

pub fn new() -> Self

Create new counter starting at zero

Source

pub fn with_value(initial: u64) -> Self

Create counter with initial value

Source

pub fn inc(&self)

Increment by 1 - THE FASTEST PATH

This is optimized to be as fast as physically possible:

  • Single atomic fetch_add instruction
  • Relaxed memory ordering for maximum speed
  • Inlined for zero function call overhead
Source

pub fn try_inc(&self) -> Result<()>

Try to increment by 1 with overflow check

Returns Ok(()) on success, or Err(MetricsError::Overflow) if the increment would overflow u64::MAX.

Example

use metrics_lib::{Counter, MetricsError};
let c = Counter::with_value(u64::MAX - 1);
c.try_inc().unwrap();
assert_eq!(c.get(), u64::MAX);
assert!(matches!(c.try_inc(), Err(MetricsError::Overflow)));
Source

pub fn add(&self, amount: u64)

Add arbitrary amount - also blazingly fast

Zero branch optimization - if amount is 0, still does the atomic operation to maintain consistent performance characteristics

Source

pub fn try_add(&self, amount: u64) -> Result<()>

Try to add an arbitrary amount with overflow check

Returns Ok(()) on success, or Err(MetricsError::Overflow) if the addition would overflow u64::MAX.

Example

use metrics_lib::{Counter, MetricsError};
let c = Counter::with_value(u64::MAX - 5);
assert!(c.try_add(4).is_ok());
assert!(matches!(c.try_add(2), Err(MetricsError::Overflow)));
Source

pub fn get(&self) -> u64

Get current value - single atomic load

Source

pub fn reset(&self)

Reset to zero - use sparingly

Note: This uses SeqCst ordering to ensure all threads see the reset

Source

pub fn set(&self, value: u64)

Set to specific value - use sparingly

Note: This uses SeqCst ordering for consistency

Source

pub fn try_set(&self, value: u64) -> Result<()>

Try to set to a specific value (always succeeds for u64)

This method never fails and always returns Ok(()).

Source

pub fn compare_and_swap(&self, expected: u64, new: u64) -> Result<u64, u64>

Atomic compare-and-swap

Returns Ok(previous_value) if successful, Err(current_value) if failed

Source

pub fn fetch_add(&self, amount: u64) -> u64

Add amount and return previous value

Source

pub fn try_fetch_add(&self, amount: u64) -> Result<u64>

Checked fetch_add that returns the previous value or error on overflow

Returns the previous value on success, or Err(MetricsError::Overflow) if adding amount would overflow u64::MAX.

Example

use metrics_lib::{Counter, MetricsError};
let c = Counter::with_value(u64::MAX - 1);
assert_eq!(c.try_fetch_add(1).unwrap(), u64::MAX - 1);
assert!(matches!(c.try_fetch_add(1), Err(MetricsError::Overflow)));
Source

pub fn add_and_get(&self, amount: u64) -> u64

Add amount and return new value

Source

pub fn inc_and_get(&self) -> u64

Increment and return new value

Source

pub fn try_inc_and_get(&self) -> Result<u64>

Checked increment that returns new value or error on overflow

Returns the new value, or Err(MetricsError::Overflow) if the increment would overflow u64::MAX.

Example

use metrics_lib::{Counter, MetricsError};
let c = Counter::with_value(u64::MAX - 1);
assert_eq!(c.try_inc_and_get().unwrap(), u64::MAX);
assert!(matches!(c.try_inc_and_get(), Err(MetricsError::Overflow)));
Source

pub fn stats(&self) -> CounterStats

Get comprehensive statistics

Source

pub fn age(&self) -> Duration

Get age since creation

Source

pub fn is_zero(&self) -> bool

Check if counter is zero

Source

pub fn rate_per_second(&self) -> f64

Get rate per second since creation

Source

pub fn saturating_add(&self, amount: u64)

Saturating add - won’t overflow past u64::MAX

Source§

impl Counter

Batch counter operations for even better performance

Source

pub fn batch_inc(&self, count: usize)

Batch increment - for very high throughput scenarios

When you have many increments to do, batch them for better performance

Source

pub fn inc_if(&self, condition: bool)

Conditional increment - only increment if condition is true

Source

pub fn inc_max(&self, max_value: u64) -> bool

Increment with maximum value

Trait Implementations§

Source§

impl Debug for Counter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Counter

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Counter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Send for Counter

Source§

impl Sync for Counter

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.