seq_marked/expirable/
mod.rs

1//! Expirable trait for types that can have an expiration time.
2//!
3//! This module provides the `Expirable` trait which allows types to define
4//! and query their expiration time in milliseconds since the Unix epoch.
5//! It's used to implement time-to-live (TTL) functionality for stored values.
6
7mod expirable_impl;
8
9/// A trait for evaluating and returning the absolute expiration time.
10pub trait Expirable {
11    /// Returns the optional expiration time in milliseconds since the Unix epoch (January 1, 1970).
12    fn expires_at_ms_opt(&self) -> Option<u64>;
13
14    /// Evaluates and returns the absolute expiration time in milliseconds since the Unix epoch
15    /// (January 1, 1970).
16    ///
17    /// If there is no expiration time, it returns `u64::MAX`.
18    fn expires_at_ms(&self) -> u64 {
19        self.expires_at_ms_opt().unwrap_or(u64::MAX)
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    #[derive(Clone, Copy)]
28    struct ExpirableImpl {
29        expires_at_ms: Option<u64>,
30    }
31
32    impl Expirable for ExpirableImpl {
33        fn expires_at_ms_opt(&self) -> Option<u64> {
34            self.expires_at_ms
35        }
36    }
37
38    #[test]
39    fn test_expirable() {
40        let e1 = ExpirableImpl {
41            expires_at_ms: Some(1),
42        };
43        assert_eq!(e1.expires_at_ms_opt(), Some(1));
44        assert_eq!(e1.expires_at_ms(), 1);
45
46        let e2 = ExpirableImpl {
47            expires_at_ms: None,
48        };
49        assert_eq!(e2.expires_at_ms_opt(), None);
50        assert_eq!(e2.expires_at_ms(), u64::MAX);
51
52        // Test with a reference
53
54        {
55            let e1_ref = &e1;
56            assert_eq!(e1_ref.expires_at_ms_opt(), Some(1));
57            assert_eq!(e1_ref.expires_at_ms(), 1);
58        }
59
60        {
61            let e2_ref = &e2;
62            assert_eq!(e2_ref.expires_at_ms_opt(), None);
63            assert_eq!(e2_ref.expires_at_ms(), u64::MAX);
64        }
65
66        // Test with Option
67
68        {
69            let e1_opt = Some(e1);
70            assert_eq!(e1_opt.expires_at_ms_opt(), Some(1));
71            assert_eq!(e1_opt.expires_at_ms(), 1);
72        }
73
74        {
75            let e1_opt = None::<ExpirableImpl>;
76            assert_eq!(e1_opt.expires_at_ms_opt(), None);
77            assert_eq!(e1_opt.expires_at_ms(), u64::MAX);
78        }
79
80        {
81            let e2_opt = Some(e1);
82            assert_eq!(e2_opt.expires_at_ms_opt(), Some(1));
83            assert_eq!(e2_opt.expires_at_ms(), 1);
84        }
85    }
86}