use crate::access::get_metrics;
use crate::{Id, MetricsHandle, Tags};
use std::ops::Deref;
pub struct Counter {
id: Id,
handle: &'static MetricsHandle,
}
impl std::fmt::Debug for Counter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Counter").field("id", &self.id).finish()
}
}
impl Counter {
pub fn new(name: &str, tags: Tags) -> Self {
let metrics = get_metrics();
let counter_id = metrics.new_counter(name, tags);
Self {
id: counter_id,
handle: metrics,
}
}
pub fn new_with_id(id: Id) -> Self {
let metrics = get_metrics();
Self { id, handle: metrics }
}
}
impl Drop for Counter {
fn drop(&mut self) {
self.handle.delete_counter(self.id);
}
}
pub trait CounterOps {
fn increment(&self);
fn increment_by(&self, delta: u64);
}
impl CounterOps for Counter {
#[inline]
fn increment(&self) {
self.handle.increment_counter(self.id);
}
#[inline]
fn increment_by(&self, delta: u64) {
self.handle.increment_counter_by(self.id, delta);
}
}
impl<T> CounterOps for T
where
T: Deref<Target = Counter>,
{
#[inline]
fn increment(&self) {
self.deref().increment()
}
#[inline]
fn increment_by(&self, delta: u64) {
self.deref().increment_by(delta)
}
}