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
use std::{
    collections::HashMap,
    io::{Error, ErrorKind, Result},
    sync::{Arc, RwLock},
    time::{Duration, Instant},
};

use sessions_core::{Data, Storage};

#[derive(Debug, Clone)]
pub struct State(Instant, Data);

impl State {
    fn new(i: Instant, d: Data) -> Self {
        Self(i, d)
    }
}

#[derive(Debug, Clone, Default)]
pub struct MemoryStorage {
    inner: Arc<RwLock<HashMap<String, State>>>,
}

impl MemoryStorage {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets a reference to the underlying data.
    #[must_use]
    pub fn get_ref(&self) -> &RwLock<HashMap<String, State>> {
        &self.inner
    }
}

impl Storage for MemoryStorage {
    async fn get(&self, key: &str) -> Result<Option<Data>> {
        let state = self
            .get_ref()
            .read()
            .map_err(into_io_error)?
            .get(key)
            .cloned();

        if let Some(State(time, data)) = state {
            if time >= Instant::now() {
                return Ok(Some(data));
            }
            self.remove(key).await?;
        }

        Ok(None)
    }

    async fn set(&self, key: &str, val: Data, exp: &Duration) -> Result<()> {
        self.get_ref()
            .write()
            .map_err(into_io_error)?
            .insert(key.to_string(), State::new(Instant::now() + *exp, val));
        Ok(())
    }

    async fn remove(&self, key: &str) -> Result<()> {
        self.get_ref().write().map_err(into_io_error)?.remove(key);
        Ok(())
    }

    async fn reset(&self) -> Result<()> {
        self.get_ref().write().map_err(into_io_error)?.clear();
        Ok(())
    }
}

#[inline]
fn into_io_error<E: std::error::Error>(e: E) -> Error {
    Error::new(ErrorKind::Other, e.to_string())
}