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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#![doc = include_str!("../README.md")]

////////////////////////////////////////////////////////////////////////////////
// Timed Option
////////////////////////////////////////////////////////////////////////////////

/// See [module level documentation][crate]
#[derive(Debug, Copy, Clone)]
pub struct TimedOption<T, Ttl> {
    value: Option<T>,
    ttl: Ttl,
}

impl<T, B> TimedOption<T, B>
where
    B: TtlBackend,
{
    /// Some value of type `T` with a ttl.
    #[inline]
    pub fn new(value: T, ttl: B::Duration) -> Self {
        TimedOption {
            value: Some(value),
            ttl: B::now().add(ttl),
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // consumption + as_refs
    ////////////////////////////////////////////////////////////////////////////

    /// Returns an `Option<T>`. If the value is some but expired a `None` is returned.
    #[inline]
    pub fn into_option(self) -> Option<T> {
        match self.ttl.is_valid() {
            true => self.value,
            false => None,
        }
    }

    /// Returns an `Option<&T>`. If the value is some but expired a `None` is returned.
    #[inline]
    pub fn as_option(&self) -> Option<&T> {
        self.as_ref().into_option()
    }

    /// Returns an `TimedValue<T>`.
    #[inline]
    pub fn into_timed_value(self) -> TimedValue<T> {
        match (self.value, self.ttl.is_valid()) {
            (Some(value), true) => TimedValue::Valid(value),
            (Some(value), false) => TimedValue::Expired(value),
            (None, _) => TimedValue::None,
        }
    }

    /// Returns an `TimedValue<&T>`.
    #[inline]
    pub fn as_timed_value(&self) -> TimedValue<&T> {
        self.as_ref().into_timed_value()
    }

    /// Converts from `&TimedOption<T>` to `TimedOption<&T>`.
    #[inline]
    pub fn as_ref(&self) -> TimedOption<&T, B> {
        TimedOption {
            value: self.value.as_ref(),
            ttl: self.ttl.clone(),
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // mutations
    ////////////////////////////////////////////////////////////////////////////

    /// Expires the current ttl.
    pub fn expire(&mut self) {
        self.ttl = B::expired();
    }

    /// Sets value to [`None`].
    pub fn clear(&mut self) {
        self.value = None;
    }

    /// Takes the value out of the [`TimedOption`], returning an [`Option`] and
    /// leaving a [`None`] in its place.
    pub fn take(&mut self) -> Option<T> {
        let value = self.value.take();
        match self.ttl.is_valid() {
            true => value,
            false => None,
        }
    }

    /// Takes the value out of the [`TimedOption`], Returning a [`TimedValue`]
    /// and leaving a [`None`] in its place.
    pub fn take_timed_value(&mut self) -> TimedValue<T> {
        match (self.value.take(), self.ttl.is_valid()) {
            (Some(value), true) => TimedValue::Valid(value),
            (Some(value), false) => TimedValue::Expired(value),
            (None, _) => TimedValue::None,
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // utility functions
    ////////////////////////////////////////////////////////////////////////////

    /// Returns `true` if the timed-option is `Some` value and has not expired.
    #[inline]
    pub fn is_some(&self) -> bool {
        self.value.is_some() & self.ttl.is_valid()
    }

    /// Returns `true` if the timed-option is `None` value or it has expired.
    #[inline]
    pub fn is_none(&self) -> bool {
        self.value.is_none() | self.ttl.is_expired()
    }
}

////////////////////////////////////////////////////////////////////////////////
// Timed Value
////////////////////////////////////////////////////////////////////////////////

/// An enum representing a value that is associated with a time validity status.
///
/// `TimedValue` can be used to indicate whether a value is valid, expired, or absent (none).
///
/// # Variants
///
/// * `Valid(T)` - Contains a value of type `T` that is considered valid.
/// * `Expired(T)` - Contains a value of type `T` that has expired and is no longer considered valid.
/// * `None` - Indicates the absence of a value.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum TimedValue<T> {
    Valid(T),
    Expired(T),
    None,
}

impl<T> TimedValue<T> {
    /// Returns `true` if the [`TimedValue`]` is `Valid`.
    #[inline]
    pub const fn is_valid(&self) -> bool {
        match self {
            TimedValue::Valid(_) => true,
            TimedValue::Expired(_) => false,
            TimedValue::None => false,
        }
    }

    /// Returns `true` if the TimedValue is `Expired`.
    #[inline]
    pub const fn is_expired(&self) -> bool {
        match self {
            TimedValue::Valid(_) => false,
            TimedValue::Expired(_) => true,
            TimedValue::None => false,
        }
    }

    /// Returns `true` if the TimedValue is `None`.
    #[inline]
    pub const fn is_none(&self) -> bool {
        match self {
            TimedValue::Valid(_) => false,
            TimedValue::Expired(_) => false,
            TimedValue::None => true,
        }
    }

    /// Returns `true` if the TimedValue is `Valid` or `Expired`.
    #[inline]
    pub const fn has_value(&self) -> bool {
        match self {
            TimedValue::Valid(_) => true,
            TimedValue::Expired(_) => true,
            TimedValue::None => false,
        }
    }

    /// Converts from `&TimedValue<T>` to `TimedValue<&T>`.
    #[inline]
    pub const fn as_ref(&self) -> TimedValue<&T> {
        match *self {
            TimedValue::Valid(ref inner) => TimedValue::Valid(inner),
            TimedValue::Expired(ref inner) => TimedValue::Expired(inner),
            TimedValue::None => TimedValue::None,
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// Conversion
////////////////////////////////////////////////////////////////////////////////

impl<T, B> From<TimedOption<T, B>> for Option<T>
where
    B: TtlBackend,
{
    fn from(value: TimedOption<T, B>) -> Self {
        value.into_option()
    }
}

impl<T, B> From<TimedOption<T, B>> for TimedValue<T>
where
    B: TtlBackend,
{
    fn from(value: TimedOption<T, B>) -> Self {
        value.into_timed_value()
    }
}

////////////////////////////////////////////////////////////////////////////////
// TTL Backent
////////////////////////////////////////////////////////////////////////////////

pub trait TtlBackend: Clone {
    type Duration;

    fn now() -> Self;
    fn expired() -> Self;
    fn add(self, dt: Self::Duration) -> Self;
    fn is_valid(&self) -> bool;
    fn is_expired(&self) -> bool;
}

impl TtlBackend for std::time::Instant {
    type Duration = std::time::Duration;

    #[inline]
    fn now() -> Self {
        std::time::Instant::now()
    }

    #[inline]
    fn expired() -> Self {
        std::time::Instant::now()
    }

    fn add(self, dt: Self::Duration) -> Self {
        self + dt
    }

    #[inline]
    fn is_valid(&self) -> bool {
        *self > std::time::Instant::now()
    }

    #[inline]
    fn is_expired(&self) -> bool {
        *self <= std::time::Instant::now()
    }
}

#[cfg(feature = "chrono")]
impl TtlBackend for chrono::DateTime<chrono::Utc> {
    type Duration = chrono::Duration;

    fn now() -> Self {
        chrono::Utc::now()
    }

    fn expired() -> Self {
        chrono::Utc::now()
    }

    fn add(self, dt: Self::Duration) -> Self {
        self + dt
    }

    fn is_valid(&self) -> bool {
        *self > chrono::Utc::now()
    }

    fn is_expired(&self) -> bool {
        *self <= chrono::Utc::now()
    }
}