append_db/backend/
memory.rs

1pub use crate::backend::class::{SnapshotedUpdate, State, StateBackend};
2use async_trait::async_trait;
3use std::{convert::Infallible, sync::Arc};
4use tokio::sync::Mutex;
5
6#[derive(Clone)]
7pub struct InMemory<St: State> {
8    pub updates: Arc<Mutex<Vec<SnapshotedUpdate<St>>>>,
9}
10
11impl<St: State> InMemory<St> {
12    pub fn new() -> Self {
13        InMemory {
14            updates: Arc::new(Mutex::new(vec![])),
15        }
16    }
17}
18
19impl<St: State> Default for InMemory<St> {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25#[async_trait]
26impl<St: Clone + State + 'static + Send> StateBackend for InMemory<St> {
27    type State = St;
28    type Err = Infallible;
29
30    async fn write(&self, upd: SnapshotedUpdate<Self::State>) -> Result<(), Self::Err> {
31        self.updates.lock().await.push(upd);
32        Ok(())
33    }
34
35    async fn updates(&self) -> Result<Vec<SnapshotedUpdate<Self::State>>, Self::Err> {
36        let mut res = vec![];
37
38        for v in self.updates.lock().await.iter().rev() {
39            res.push(v.clone());
40            if v.is_snapshot() {
41                break;
42            }
43        }
44        res.reverse();
45        Ok(res)
46    }
47}