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
/*!
Validators are used when working with caches and determine for how long
a specific cache entry stays valid.

This validator limits the cache time based on an actual time instant.
Internally it uses the [coarsetime](https://docs.rs/coarsetime/0.1.14/coarsetime/) crate as a less
computation intensive alternative for [std::time](https://doc.rust-lang.org/std/time/index.html).
Therefor the Duration has to be converted (e.g. via the .into() trait) when constructing this validator.

The default implementation will set the cache time to 1 second.
*/
use std::prelude::v1::*;

use super::CacheValidator;
use coarsetime::{Duration, Instant};

/// Validator for limiting the cache time based on a time `Instant`
///
/// # Remarks
///
/// This validator is only available when being compiled with `std`.
/// When using `no_std` you might want to use another validator.
/// TODO: add other validators here
#[derive(Clone)]
pub struct TimedCacheValidator {
    time: Vec<Instant>,
    valid_time: Duration,
    last_time: Instant,
}

/// Creates a validator with a cache timeout of 1 second.
impl Default for TimedCacheValidator {
    fn default() -> Self {
        Self::new(Duration::from_millis(1000))
    }
}

impl TimedCacheValidator {
    /// Creates a new TimedCacheValidator with a customizable Duration.
    ///
    /// # Examples:
    /// ```
    /// use std::time::Duration;
    /// use memflow::mem::TimedCacheValidator;
    ///
    /// let _ = TimedCacheValidator::new(Duration::from_millis(5000).into());
    /// ```
    pub fn new(valid_time: Duration) -> Self {
        Self {
            time: vec![],
            valid_time,
            last_time: Instant::now(),
        }
    }
}

impl CacheValidator for TimedCacheValidator {
    #[inline]
    fn allocate_slots(&mut self, slot_count: usize) {
        self.time
            .resize(slot_count, self.last_time - self.valid_time);
    }

    #[inline]
    fn update_validity(&mut self) {
        self.last_time = Instant::now()
    }

    #[inline]
    fn is_slot_valid(&self, slot_id: usize) -> bool {
        self.last_time.duration_since(self.time[slot_id]) <= self.valid_time
    }

    #[inline]
    fn validate_slot(&mut self, slot_id: usize) {
        self.time[slot_id] = self.last_time;
    }

    #[inline]
    fn invalidate_slot(&mut self, slot_id: usize) {
        self.time[slot_id] = self.last_time - self.valid_time
    }
}