r_cache/
item.rs

1use std::time::{Duration, Instant};
2
3#[derive(Clone)]
4pub struct Item<T> {
5    pub object: T,
6    expiry: Option<Instant>,
7}
8
9impl<T> Item<T> {
10    // Creates a new cache item.
11    pub fn new(object: T, item_duration: Option<Duration>) -> Self {
12        let expiry = item_duration.map(|duration| Instant::now() + duration);
13        Item { object, expiry }
14    }
15
16    // Returns true if the item has expired.
17    pub fn expired(&self) -> bool {
18        self.expiry
19            .map(|expiry| expiry < Instant::now())
20            .unwrap_or(false)
21    }
22}
23
24#[cfg(test)]
25mod tests {
26    use async_std::task;
27
28    use crate::item::Item;
29    use std::time::Duration;
30
31    const OBJECT: &str = "OBJECT";
32
33    #[async_std::test]
34    async fn not_expired_when_duration_is_none() {
35        let item = Item::new(OBJECT, None);
36        assert_eq!(item.expired(), false);
37    }
38
39    #[async_std::test]
40    async fn expired_when_duration_is_zero() {
41        let item = Item::new(OBJECT, Some(Duration::new(0, 0)));
42        task::sleep(Duration::from_millis(1)).await;
43        assert_eq!(item.expired(), true);
44    }
45}