diff --git a/CHANGELOG.md b/CHANGELOG.md index 342eb37..3a8f53b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.21.0] + +### Changed + +- Replace `impl EncodeMetric for RefCell` with a new type `ConstFamily` implementing `EncodeMetric`. + ## [0.20.0] ### Added diff --git a/Cargo.toml b/Cargo.toml index f3d1aad..627f361 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "prometheus-client" -version = "0.20.0" +version = "0.21.0" authors = ["Max Inden "] edition = "2021" description = "Open Metrics client library allowing users to natively instrument applications." diff --git a/src/metrics/family.rs b/src/metrics/family.rs index 3b70eeb..15c3c9a 100644 --- a/src/metrics/family.rs +++ b/src/metrics/family.rs @@ -327,11 +327,31 @@ where } } -impl> EncodeMetric - for RefCell +/// As a [`Family`], but constant, meaning it cannot change once created. +/// +/// Needed for advanced use-cases, e.g. in combination with [`Collector`](crate::collector::Collector). +/// +/// Note that a [`ConstFamily`], given that it is based on an [`Iterator`], can +/// only be [`EncodeMetric::encode`]d once. While consecutive +/// [`EncodeMetric::encode`] calls won't panic, they won't return any metrics as +/// the provided [`Iterator`] will return [`Iterator::next`] [`None`]. Thus you +/// should not return the same [`ConstFamily`] in more than one +/// [`Collector::collect`](crate::collector::Collector::collect) calls. +#[derive(Debug, Default)] +pub struct ConstFamily(RefCell); + +impl ConstFamily { + /// Creates a new [`ConstFamily`]. + pub fn new(iter: I) -> Self { + Self(RefCell::new(iter)) + } +} + +impl> EncodeMetric + for ConstFamily { fn encode(&self, mut encoder: MetricEncoder<'_, '_>) -> Result<(), std::fmt::Error> { - let mut iter = self.borrow_mut(); + let mut iter = self.0.borrow_mut(); for (label_set, m) in iter.by_ref() { let encoder = encoder.encode_family(&label_set)?;