Skip to main content

saluki_core/data_model/event/metric/value/
scalar.rs

1use std::{fmt, num::NonZeroU64};
2
3use ordered_float::OrderedFloat;
4
5use super::{
6    iter::{PointsIter, PointsIterRef},
7    TimestampedValue, TimestampedValues,
8};
9
10/// A set of scalar points.
11///
12/// Used to represent the data points of "scalar" metric types, such as counters, gauges, and rates. Each data point is
13/// attached to an optional timestamp.
14#[derive(Clone, Debug, Eq, PartialEq)]
15pub struct ScalarPoints(TimestampedValues<OrderedFloat<f64>, 4>);
16
17impl ScalarPoints {
18    pub(super) fn new() -> Self {
19        Self(TimestampedValues::default())
20    }
21
22    pub(super) fn inner(&self) -> &TimestampedValues<OrderedFloat<f64>, 4> {
23        &self.0
24    }
25
26    pub(super) fn inner_mut(&mut self) -> &mut TimestampedValues<OrderedFloat<f64>, 4> {
27        &mut self.0
28    }
29
30    #[inline]
31    pub(super) fn add_point(&mut self, timestamp: Option<NonZeroU64>, value: f64) {
32        let needs_sort = self.0.values.last().is_some_and(|last| last.timestamp > timestamp);
33        self.0.values.push(TimestampedValue {
34            timestamp,
35            value: OrderedFloat(value),
36        });
37        if needs_sort {
38            self.0.sort_by_timestamp();
39        }
40    }
41
42    pub(super) fn drain_timestamped(&mut self) -> Self {
43        Self(self.0.drain_timestamped())
44    }
45
46    pub(super) fn split_at_timestamp(&mut self, timestamp: u64) -> Option<Self> {
47        self.0.split_at_timestamp(timestamp).map(Self)
48    }
49
50    /// Returns `true` if this set is empty.
51    pub fn is_empty(&self) -> bool {
52        self.0.values.is_empty()
53    }
54
55    /// Returns the number of points in this set.
56    pub fn len(&self) -> usize {
57        self.0.values.len()
58    }
59
60    /// Merges another set of points into this one.
61    ///
62    /// If a point with the same timestamp exists in both sets, the values will be added together. Otherwise, the points
63    /// will appended to the end of the set.
64    pub fn merge<F>(&mut self, other: Self, merge: F)
65    where
66        F: Fn(&mut OrderedFloat<f64>, &mut OrderedFloat<f64>),
67    {
68        let mut needs_sort = false;
69        for other_value in other.0.values {
70            if let Some(existing_value) = self
71                .0
72                .values
73                .iter_mut()
74                .find(|value| value.timestamp == other_value.timestamp)
75            {
76                let mut other = other_value.value;
77                merge(&mut existing_value.value, &mut other);
78            } else {
79                self.0.values.push(other_value);
80                needs_sort = true;
81            }
82        }
83
84        if needs_sort {
85            self.0.sort_by_timestamp();
86        }
87    }
88}
89
90impl From<f64> for ScalarPoints {
91    fn from(value: f64) -> Self {
92        Self(TimestampedValue::from(OrderedFloat(value)).into())
93    }
94}
95
96impl<'a> From<&'a [f64]> for ScalarPoints {
97    fn from(values: &'a [f64]) -> Self {
98        Self(TimestampedValues::from(values.iter().map(|value| OrderedFloat(*value))))
99    }
100}
101
102impl<const N: usize> From<[f64; N]> for ScalarPoints {
103    fn from(values: [f64; N]) -> Self {
104        Self(TimestampedValues::from(values.iter().map(|value| OrderedFloat(*value))))
105    }
106}
107
108impl From<(u64, f64)> for ScalarPoints {
109    fn from((ts, value): (u64, f64)) -> Self {
110        Self(TimestampedValue::from((ts, OrderedFloat(value))).into())
111    }
112}
113
114impl<'a> From<&'a [(u64, f64)]> for ScalarPoints {
115    fn from(values: &'a [(u64, f64)]) -> Self {
116        Self(TimestampedValues::from(
117            values.iter().map(|(ts, value)| (*ts, OrderedFloat(*value))),
118        ))
119    }
120}
121
122impl<const N: usize> From<[(u64, f64); N]> for ScalarPoints {
123    fn from(values: [(u64, f64); N]) -> Self {
124        Self(TimestampedValues::from(
125            values.iter().map(|(ts, value)| (*ts, OrderedFloat(*value))),
126        ))
127    }
128}
129
130impl<T> FromIterator<T> for ScalarPoints
131where
132    T: Into<TimestampedValue<OrderedFloat<f64>>>,
133{
134    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
135        Self(TimestampedValues::from(iter))
136    }
137}
138
139impl IntoIterator for ScalarPoints {
140    type Item = (Option<NonZeroU64>, f64);
141    type IntoIter = PointsIter;
142
143    fn into_iter(self) -> Self::IntoIter {
144        PointsIter::scalar(self.0.values.into_iter())
145    }
146}
147
148impl<'a> IntoIterator for &'a ScalarPoints {
149    type Item = (Option<NonZeroU64>, f64);
150    type IntoIter = PointsIterRef<'a>;
151
152    fn into_iter(self) -> Self::IntoIter {
153        PointsIterRef::scalar(self.0.values.iter())
154    }
155}
156
157impl fmt::Display for ScalarPoints {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        write!(f, "[")?;
160        for (i, (timestamp, value)) in self.into_iter().enumerate() {
161            if i > 0 {
162                write!(f, ",")?;
163            }
164
165            let ts = timestamp.map(|ts| ts.get()).unwrap_or_default();
166            write!(f, "({}, {})", ts, value)?;
167        }
168        write!(f, "]")
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn ts(v: u64) -> Option<NonZeroU64> {
177        NonZeroU64::new(v)
178    }
179
180    #[test]
181    fn add_point_maintains_sorted_timestamp_order() {
182        let mut points = ScalarPoints::new();
183        points.add_point(None, 1.0);
184        points.add_point(None, 2.0);
185        points.add_point(ts(10), 3.0);
186        points.add_point(ts(20), 4.0);
187        points.add_point(ts(15), 5.0);
188        points.add_point(None, 6.0);
189        points.add_point(ts(10), 7.0);
190
191        let collected: Vec<_> = (&points).into_iter().collect();
192        assert_eq!(
193            collected,
194            vec![
195                (None, 1.0),
196                (None, 2.0),
197                (None, 6.0),
198                (ts(10), 3.0),
199                (ts(10), 7.0),
200                (ts(15), 5.0),
201                (ts(20), 4.0),
202            ]
203        );
204    }
205}