I am using the following macro to increment-and-then-decrement a gauge, and was wondering whether a better pattern already exists in the library that I've missed:
pub struct GaugeDecrement<F: FnOnce() -> ()>(Option<F>);
impl<F: FnOnce() -> ()> GaugeDecrement<F> {
pub fn new(f: F) -> Self {
GaugeDecrement(Some(f))
}
}
impl<F: FnOnce() -> ()> Drop for GaugeDecrement<F> {
fn drop(&mut self) {
self.0.take().unwrap()()
}
}
/// Temporarily increments a gauge, and returns a guard that will decrement the metric when
/// dropped.
#[macro_export]
macro_rules! with_incremented_gauge {
($name:literal, $value:literal $($tail:tt)*) => {{
metrics::increment_gauge!($name, $value $($tail)*);
$crate::GaugeDecrement::new(|| metrics::decrement_gauge!($name, $value $($tail)*))
}};
}
Nope, you haven't missed any other pattern/approach for doing this. :) If I was going to write something for metrics itself, this is likely how I'd approach it.
I am using the following macro to increment-and-then-decrement a gauge, and was wondering whether a better pattern already exists in the library that I've missed: