From a3c065ede5bca814070d3f1f07a7ee756a779c00 Mon Sep 17 00:00:00 2001 From: katelyn martin Date: Thu, 22 Jan 2026 00:00:00 +0000 Subject: [PATCH] feat(metrics/family): `len()` returns the number of metrics this commit introduces a `len()` method to `Family`, which returns the number of series within a metric family. see also #245, which allows callers to check if a family `contains()` a given label set. ```shell $ cargo clippy --all-features --all-targets --tests Compiling prometheus-client v0.23.0 (/path/to/prometheus-client) warning: struct `Family` has a public `len` method, but no `is_empty` method --> src/metrics/family.rs:309:5 | 309 | pub fn len(&self) -> usize { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#len_without_is_empty = note: `#[warn(clippy::len_without_is_empty)]` on by default warning: `prometheus-client` (lib) generated 1 warning warning: `prometheus-client` (lib test) generated 1 warning (1 duplicate) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.63s ``` Signed-off-by: katelyn martin --- CHANGELOG.md | 3 +++ src/metrics/family.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index eda1011..733e209 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,11 +17,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 feature is enabled. See [PR 242]. - `Family` now exposes a `contains()` method when the `test-util` feature is enabled. See [PR 245]. +- `Family` now exposes `len()` and `is_empty()` methods when the + `test-util` feature is enabled. See [PR 246]. [PR 279]: https://github.com/prometheus/client_rust/pull/279 [PR 281]: https://github.com/prometheus/client_rust/pull/281 [PR 242]: https://github.com/prometheus/client_rust/pull/242 [PR 245]: https://github.com/prometheus/client_rust/pull/245 +[PR 246]: https://github.com/prometheus/client_rust/pull/246 ## [0.24.0] diff --git a/src/metrics/family.rs b/src/metrics/family.rs index d54bec8..b81d394 100644 --- a/src/metrics/family.rs +++ b/src/metrics/family.rs @@ -362,6 +362,35 @@ impl> Family, Counter>::default(); + /// assert_eq!(family.len(), 0); + /// + /// // Will create the metric with label `method="GET"` on first call and + /// // return a reference. + /// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc(); + /// assert_eq!(family.len(), 1); + /// + /// // Clear the family of all label sets. + /// family.clear(); + /// assert_eq!(family.len(), 0); + /// ``` + #[cfg(any(test, feature = "test-util"))] + pub fn len(&self) -> usize { + self.metrics.read().len() + } + + /// Returns `true` if the family contains no metrics. + #[cfg(any(test, feature = "test-util"))] + pub fn is_empty(&self) -> bool { + self.metrics.read().is_empty() + } + pub(crate) fn read(&self) -> RwLockReadGuard<'_, HashMap> { self.metrics.read() }