1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Crossing {
6 Above,
7 Below,
8}
9
10pub(crate) struct UnexpectedSlot;
11
12pub(crate) struct Samples<V> {
13 next: Option<i64>,
14 latest: Option<(i64, V)>,
15 threshold: Option<i64>,
16 pub(crate) periodic: bool,
17}
18
19impl<V: Copy> Samples<V> {
20 pub(crate) fn new(first_utc: i64, periodic: bool, threshold: Option<i64>) -> Self {
21 Self {
22 next: Some(first_utc),
23 latest: None,
24 threshold,
25 periodic,
26 }
27 }
28
29 pub(crate) fn record(
31 &mut self,
32 utc: i64,
33 value: Option<V>,
34 magnitude: impl Fn(V) -> i64,
35 ) -> Result<Option<(V, Option<Crossing>)>, UnexpectedSlot> {
36 if self.next != Some(utc) {
37 return Err(UnexpectedSlot);
38 }
39 self.next = utc.checked_add(60);
40 let previous = self.latest.take();
41 let Some(value) = value else {
42 return Ok(None);
43 };
44 self.latest = Some((utc, value));
45 let crossing = previous
46 .zip(self.threshold)
47 .and_then(|((_, last), threshold)| {
48 let old = magnitude(last);
49 let new = magnitude(value);
50 if old <= threshold && new > threshold {
51 Some(Crossing::Above)
52 } else if old >= threshold && new < threshold {
53 Some(Crossing::Below)
54 } else {
55 None
56 }
57 });
58 Ok((self.periodic || crossing.is_some()).then_some((value, crossing)))
59 }
60
61 pub(crate) fn current(&self, now: i64) -> Option<(i64, V)> {
62 self.latest
63 .filter(|(utc, _)| now >= *utc && now.abs_diff(*utc) < 60)
64 }
65}