ddsketch/agent/
bin.rs

1//! Sketch bin representation.
2
3const MAX_BIN_WIDTH: u16 = u16::MAX;
4
5/// A sketch bin.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
8pub struct Bin {
9    /// The bin index.
10    pub(crate) k: i16,
11
12    /// The number of observations within the bin.
13    pub(crate) n: u16,
14}
15
16impl Bin {
17    /// Returns the key of the bin.
18    pub fn key(&self) -> i32 {
19        self.k as i32
20    }
21
22    /// Returns the number of observations within the bin.
23    pub fn count(&self) -> u32 {
24        self.n as u32
25    }
26
27    #[allow(clippy::cast_possible_truncation)]
28    pub(crate) fn increment(&mut self, n: u64) -> u64 {
29        let next = n + u64::from(self.n);
30        if next > u64::from(MAX_BIN_WIDTH) {
31            self.n = MAX_BIN_WIDTH;
32            return next - u64::from(MAX_BIN_WIDTH);
33        }
34
35        // SAFETY: We already know `next` is less than or equal to `MAX_BIN_WIDTH` if we got here, and `MAX_BIN_WIDTH`
36        // is u16, so next can't possibly be larger than a u16.
37        self.n = next as u16;
38        0
39    }
40}