hopr_metrics/
guard.rs

1use crate::{SimpleGauge, metrics::MultiGauge};
2
3/// Creates a RAII guard for a simple gauge metric.
4///
5/// The metric is incremented when the guard is created and decremented when it is dropped.
6pub struct GaugeGuard<'a> {
7    metric: &'a SimpleGauge,
8    by: f64,
9}
10
11impl<'a> GaugeGuard<'a> {
12    pub fn new(metric: &'a SimpleGauge, by: f64) -> Self {
13        metric.increment(by);
14        Self { metric, by }
15    }
16}
17
18impl<'a> Drop for GaugeGuard<'a> {
19    fn drop(&mut self) {
20        self.metric.decrement(self.by)
21    }
22}
23
24/// Creates a RAII guard for a multi-gauge metric.
25///
26/// The metric with the given labels is incremented when the guard is created and decremented
27/// when the guard is dropped.
28pub struct MultiGaugeGuard<'a> {
29    metric: &'a MultiGauge,
30    labels: &'a [&'a str],
31    by: f64,
32}
33
34impl<'a> MultiGaugeGuard<'a> {
35    pub fn new(metric: &'a MultiGauge, labels: &'a [&'a str], by: f64) -> Self {
36        metric.increment(labels, by);
37        Self { metric, labels, by }
38    }
39}
40
41impl<'a> Drop for MultiGaugeGuard<'a> {
42    fn drop(&mut self) {
43        self.metric.decrement(self.labels, self.by)
44    }
45}