confluent_kafka/common/metrics/stats/
cumulative_sum.rs1use std::sync::atomic::{AtomicU64, Ordering};
19
20use crate::common::metrics::{Measurable, MetricConfig, Stat};
21
22#[derive(Debug)]
28#[doc(alias = "org.apache.kafka.common.metrics.stats.CumulativeSum")]
29pub struct CumulativeSum {
34 total: AtomicU64,
35}
36
37impl CumulativeSum {
38 #[doc(alias = "org.apache.kafka.common.metrics.stats.CumulativeSum#CumulativeSum")]
40 pub fn new() -> Self {
41 Self::with_value(0.0)
42 }
43
44 #[doc(alias = "org.apache.kafka.common.metrics.stats.CumulativeSum#CumulativeSum")]
50 pub fn with_value(value: f64) -> Self {
51 Self { total: AtomicU64::new(value.to_bits()) }
52 }
53}
54
55impl Default for CumulativeSum {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61impl Stat for CumulativeSum {
62 fn record(&self, _config: &MetricConfig, value: f64, _now: i64) {
63 let mut current = self.total.load(Ordering::Relaxed);
64 loop {
65 let updated = (f64::from_bits(current) + value).to_bits();
66 match self
67 .total
68 .compare_exchange_weak(current, updated, Ordering::SeqCst, Ordering::Relaxed)
69 {
70 Ok(_) => break,
71 Err(observed) => current = observed,
72 }
73 }
74 }
75}
76
77impl Measurable for CumulativeSum {
78 fn measure(&self, _config: &MetricConfig, _now: i64) -> f64 {
79 f64::from_bits(self.total.load(Ordering::SeqCst))
80 }
81}
82
83impl std::fmt::Display for CumulativeSum {
84 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 let total = f64::from_bits(self.total.load(Ordering::SeqCst));
87 write!(
88 f,
89 "CumulativeSum(total={})",
90 crate::common::config::config_def::java_double_to_string(total)
91 )
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn to_string_follows_java() {
101 let sum = CumulativeSum::new();
102 sum.record(&MetricConfig::new(), 1.5, 0);
103 assert_eq!(sum.to_string(), "CumulativeSum(total=1.5)");
104 assert_eq!(CumulativeSum::with_value(1e8).to_string(), "CumulativeSum(total=1.0E8)");
105 }
106
107 #[test]
108 fn test_cumulative_sum() {
109 let config = MetricConfig::new();
110 let s = CumulativeSum::new();
111 assert_eq!(s.measure(&config, 0), 0.0);
112 s.record(&config, 5.0, 0);
113 s.record(&config, 2.5, 1);
114 s.record(&config, -1.0, 2);
115 assert_eq!(s.measure(&config, 2), 6.5);
116 }
117
118 #[test]
119 fn test_with_value_seed() {
120 let config = MetricConfig::new();
121 let s = CumulativeSum::with_value(10.0);
122 assert_eq!(s.measure(&config, 0), 10.0);
123 s.record(&config, 5.0, 0);
124 assert_eq!(s.measure(&config, 0), 15.0);
125 }
126}