1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use core::borrow::Borrow;
use core::ops::Deref;

use super::tick::Tick;
use super::tickable::Tickable;
use time::OffsetDateTime;

/// Value with timestamp.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TickValue<T> {
    /// Tick.
    pub tick: Tick,
    /// Value.
    pub value: T,
}

impl<T> TickValue<T> {
    /// Create a new [`TickValue`] with the given `value`
    /// and the `BIG_BANG` tick.
    pub fn big_bang(value: T) -> Self {
        Self {
            tick: Tick::BIG_BANG,
            value,
        }
    }

    /// Create a new [`TickValue`] from `ts` and `value`.
    pub fn new(ts: OffsetDateTime, value: T) -> Self {
        Self {
            tick: Tick::new(ts),
            value,
        }
    }

    /// Map over the tick value.
    pub fn map<U, F>(self, f: F) -> TickValue<U>
    where
        F: FnOnce(T) -> U,
    {
        TickValue {
            tick: self.tick,
            value: (f)(self.value),
        }
    }
}

impl<T> Tickable for TickValue<T> {
    type Value = T;

    fn tick(&self) -> Tick {
        self.tick
    }

    fn value(&self) -> &Self::Value {
        &self.value
    }

    fn into_tick_value(self) -> TickValue<Self::Value> {
        self
    }
}

impl<T> core::fmt::Display for TickValue<T>
where
    T: core::fmt::Display,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if let Some(ts) = self.tick.ts() {
            write!(f, "({ts}, {})", self.value)
        } else {
            write!(f, "(*, {})", self.value)
        }
    }
}

impl<T> Deref for TickValue<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> Borrow<T> for TickValue<T> {
    fn borrow(&self) -> &T {
        &self.value
    }
}