Skip to main content

confluent_kafka/common/metrics/stats/
value.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! An instantaneous value (`org.apache.kafka.common.metrics.stats.Value`).
16
17use std::sync::atomic::{AtomicU64, Ordering};
18
19use crate::common::metrics::{Measurable, MetricConfig, Stat};
20
21/// An instantaneous value.
22#[derive(Debug)]
23#[doc(alias = "org.apache.kafka.common.metrics.stats.Value")]
24// `record` stores the last value; `measure` returns it. The `f64` is held as
25// its bit pattern in an `AtomicU64` so recording is lock-free, the minimal Rust
26// equivalent of Java guarding the field with the sensor's `synchronized`.
27pub struct Value {
28    value: AtomicU64,
29}
30
31impl Value {
32    /// Create a `Value` initialized to `0`, matching Java's `private double value = 0`.
33    #[doc(alias = "org.apache.kafka.common.metrics.stats.Value#Value")]
34    pub fn new() -> Self {
35        Self { value: AtomicU64::new(0.0f64.to_bits()) }
36    }
37}
38
39impl Default for Value {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl Stat for Value {
46    fn record(&self, _config: &MetricConfig, value: f64, _time_ms: i64) {
47        self.value.store(value.to_bits(), Ordering::SeqCst);
48    }
49}
50
51impl Measurable for Value {
52    fn measure(&self, _config: &MetricConfig, _now: i64) -> f64 {
53        f64::from_bits(self.value.load(Ordering::SeqCst))
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_value_records_last() {
63        let config = MetricConfig::new();
64        let v = Value::new();
65        assert_eq!(v.measure(&config, 0), 0.0);
66        v.record(&config, 1.0, 0);
67        assert_eq!(v.measure(&config, 0), 1.0);
68        v.record(&config, 42.5, 1);
69        assert_eq!(v.measure(&config, 1), 42.5);
70        // Last value wins.
71        v.record(&config, -3.0, 2);
72        assert_eq!(v.measure(&config, 2), -3.0);
73    }
74}