confluent_kafka/common/metrics/stats/
avg.rs1use crate::common::metrics::stats::sampled_stat::{Sample, SampledStat, SampledStatKind};
18use crate::common::metrics::{Measurable, MetricConfig, Stat};
19
20#[derive(Debug)]
22#[doc(alias = "org.apache.kafka.common.metrics.stats.Avg")]
23pub struct Avg {
24 inner: SampledStat,
25}
26
27struct AvgKind;
28
29impl SampledStatKind for AvgKind {
30 fn update(&self, sample: &mut Sample, _config: &MetricConfig, value: f64, _now: i64) {
31 sample.value += value;
32 }
33
34 fn combine(&self, samples: &[Sample], _config: &MetricConfig, _now: i64) -> f64 {
35 let mut total = 0.0;
36 let mut count: i64 = 0;
37 for s in samples {
38 total += s.value;
39 count += s.event_count;
40 }
41 if count == 0 { f64::NAN } else { total / count as f64 }
42 }
43}
44
45impl Avg {
46 #[doc(alias = "org.apache.kafka.common.metrics.stats.Avg#Avg")]
48 pub fn new() -> Self {
49 Self { inner: SampledStat::new(0.0, Box::new(AvgKind)) }
50 }
51}
52
53impl Default for Avg {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59impl Stat for Avg {
60 fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
61 self.inner.record(config, value, time_ms);
62 }
63}
64
65impl Measurable for Avg {
66 fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
67 self.inner.measure(config, now)
68 }
69}
70
71impl std::fmt::Display for Avg {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 std::fmt::Display::fmt(&self.inner, f)
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn average_of_records() {
84 let config = MetricConfig::new();
85 let avg = Avg::new();
86 for i in 0..10 {
87 avg.record(&config, i as f64, 0);
88 }
89 assert_eq!(4.5, avg.measure(&config, 0));
90 }
91
92 #[test]
93 fn nan_when_no_events() {
94 let config = MetricConfig::new();
95 let avg = Avg::new();
96 assert!(avg.measure(&config, 0).is_nan());
97 }
98}