Skip to content

Commit

Permalink
src/metrics: Introduce const types
Browse files Browse the repository at this point in the history
Signed-off-by: Max Inden <mail@max-inden.de>
  • Loading branch information
mxinden committed Dec 10, 2022
1 parent c337017 commit c9f59eb
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/metrics/counter.rs
Expand Up @@ -187,6 +187,38 @@ where
}
}

/// As [`Counter`] but constant, that is can not change once created.
///
/// Needed for advanced use-cases, e.g. in combination with [`Collector`](crate::registry::Collector).
#[derive(Debug, Default)]
pub struct ConstCounter<N = u64> {
value: N,
}

impl<N> ConstCounter<N> {
/// Creates a new [`ConstCounter`].
pub fn new(value: N) -> Self {
Self { value }
}
}

impl<N> TypedMetric for ConstCounter<N> {
const TYPE: MetricType = MetricType::Counter;
}

impl<N> EncodeMetric for ConstCounter<N>
where
N: crate::encoding::EncodeCounterValue,
{
fn encode(&self, mut encoder: MetricEncoder) -> Result<(), std::fmt::Error> {
encoder.encode_counter::<(), _, u64>(&self.value, None)
}

fn metric_type(&self) -> MetricType {
Self::TYPE
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
21 changes: 21 additions & 0 deletions src/metrics/family.rs
Expand Up @@ -326,6 +326,27 @@ where
}
}

// TODO: When we split the dispatched type for the standard registered metrics
// and the collector metrics and only require Sync for the former, we can use a
// RefCell here.
impl<S: EncodeLabelSet, M: EncodeMetric + TypedMetric, T: Iterator<Item = (S, M)>> EncodeMetric
for parking_lot::Mutex<T>
{
fn encode(&self, mut encoder: MetricEncoder<'_, '_>) -> Result<(), std::fmt::Error> {
let mut iter = self.lock();

while let Some((label_set, m)) = iter.next() {
let encoder = encoder.encode_family(&label_set)?;
m.encode(encoder)?;
}
Ok(())
}

fn metric_type(&self) -> MetricType {
M::TYPE
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
31 changes: 31 additions & 0 deletions src/metrics/gauge.rs
Expand Up @@ -253,6 +253,37 @@ where
}
}

/// As [`Gauge`] but constant, that is can not change once created.
///
/// Needed for advanced use-cases, e.g. in combination with [`Collector`](crate::registry::Collector).
#[derive(Debug, Default)]
pub struct ConstGauge<N = i64> {
value: N,
}

impl<N> ConstGauge<N> {
/// Creates a new [`ConstGauge`].
pub fn new(value: N) -> Self {
Self { value }
}
}

impl<N> TypedMetric for ConstGauge<N> {
const TYPE: MetricType = MetricType::Gauge;
}

impl<N> EncodeMetric for ConstGauge<N>
where
N: EncodeGaugeValue,
{
fn encode(&self, mut encoder: MetricEncoder) -> Result<(), std::fmt::Error> {
encoder.encode_gauge(&self.value)
}
fn metric_type(&self) -> MetricType {
Self::TYPE
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit c9f59eb

Please sign in to comment.