windowed_stats/
aggregations.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use num::traits::SaturatingAdd;
6use std::ops::Add;
7
8pub fn create_saturating_add_fn<T: SaturatingAdd>() -> Box<dyn Fn(&T, &T) -> T + Send> {
9    Box::new(|value1, value2| value1.saturating_add(value2))
10}
11
12#[derive(Debug, Clone, Copy, PartialEq, Default)]
13pub struct SumAndCount {
14    pub sum: u32,
15    pub count: u32,
16}
17
18impl SumAndCount {
19    pub fn avg(&self) -> f64 {
20        self.sum as f64 / self.count as f64
21    }
22}
23
24// `Add` implementation is required to implement `SaturatingAdd` down below.
25impl Add for SumAndCount {
26    type Output = Self;
27
28    fn add(self, other: Self) -> Self {
29        Self { sum: self.sum + other.sum, count: self.count + other.count }
30    }
31}
32
33impl SaturatingAdd for SumAndCount {
34    fn saturating_add(&self, other: &Self) -> Self {
35        Self {
36            sum: self.sum.saturating_add(other.sum),
37            count: self.count.saturating_add(other.count),
38        }
39    }
40}