tinylfu_cached/cache/
clock.rs

1use std::time::SystemTime;
2
3/// Defines a boxed pointer to [`Clock`].
4pub type ClockType = Box<dyn Clock + Send + Sync>;
5
6/// The default implementation of the [`Clock`] trait. `SystemClock` is cloneable.
7#[derive(Clone)]
8pub struct SystemClock {}
9
10/// BoxedClockClone represents a trait get an instance of [`ClockType`].
11pub trait BoxedClockClone {
12    fn clone_box(&self) -> ClockType;
13}
14
15/// Clock represents a trait to get the current [`std::time::SystemTime`].
16///
17/// The default implementation of Clock is [`SystemClock`].
18///
19/// Clients can provide their implementation of Clock using [`crate::cache::config::Config`] and
20/// since Clock is considered to be a lightweight object, Clock is of type [`BoxedClockClone`].
21pub trait Clock: Send + Sync + BoxedClockClone {
22    fn now(&self) -> SystemTime;
23
24    fn has_passed(&self, time: &SystemTime) -> bool {
25        self.now().gt(time)
26    }
27}
28
29impl<T> BoxedClockClone for T
30    where
31        T: 'static + Clock + Clone {
32    fn clone_box(&self) -> ClockType {
33        Box::new(self.clone())
34    }
35}
36
37impl Clone for Box<dyn Clock> {
38    fn clone(&self) -> Box<dyn Clock> {
39        self.clone_box()
40    }
41}
42
43impl Clock for SystemClock {
44    fn now(&self) -> SystemTime {
45        SystemTime::now()
46    }
47}
48
49impl SystemClock {
50    /// Creates a new instance of SystemClock.
51    pub fn new() -> SystemClock {
52        SystemClock {}
53    }
54
55    /// Creates a boxed pointer to [`Clock`].
56    pub fn boxed() -> ClockType {
57        Box::new(SystemClock::new())
58    }
59}
60
61impl Default for SystemClock {
62    fn default() -> Self {
63        SystemClock::new()
64    }
65}