lib/
cache_task.rs

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
use std::any::Any;
use std::cmp::Ordering;
use std::time::{SystemTime, UNIX_EPOCH};

pub enum CacheTask {
    INVALIDATION { exp_time: u128, cache_id: &'static str, key: Box<dyn Any + Send> }
}


impl CacheTask {
    pub fn invalidation(expires_in: u64, cache_id: &'static str, key: Box<dyn Any + Send>) -> CacheTask {
        let exp_time = SystemTime::now().duration_since(UNIX_EPOCH)
            .expect("Time went backwards").as_millis() + expires_in as u128;

        CacheTask::INVALIDATION {
            exp_time,
            cache_id,
            key,
        }
    }

    pub fn exp_time(&self) -> u128 {
        match self {
            CacheTask::INVALIDATION { exp_time, .. } => {
                *exp_time
            }
        }
    }
    pub fn is_expired(&self) -> bool {
        self.exp_time() <= SystemTime::now().duration_since(UNIX_EPOCH)
            .expect("Time went backwards").as_millis()
    }
}

impl Eq for CacheTask {}

impl PartialEq<Self> for CacheTask {
    fn eq(&self, other: &Self) -> bool {
        self.exp_time() == other.exp_time()
    }
}

impl PartialOrd<Self> for CacheTask {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for CacheTask {
    // Ordering as priority
    fn cmp(&self, other: &Self) -> Ordering {
        if self.exp_time() > other.exp_time() {
            return Ordering::Less;
        }

        Ordering::Greater
    }
}