Skip to main content

bitwarden_test/
persisted_value.rs

1use std::sync::{Arc, Mutex};
2
3use bitwarden_state::{
4    Persist, PersistedValue, PersistedValueError, PersistedValueKey, PersistedValueTrait,
5};
6
7/// A simple in-memory persisted value backend. The data is only stored in memory and will not
8/// persist beyond the lifetime of the backend instance.
9///
10/// Primary use case is for unit and integration tests.
11pub struct MemoryPersistedValue<T> {
12    value: Mutex<Option<T>>,
13}
14
15impl<T: Clone + Persist> MemoryPersistedValue<T> {
16    /// Create a persisted value handle backed by a fresh in-memory store.
17    pub fn create<K: PersistedValueKey<Value = T>>() -> PersistedValue<K> {
18        PersistedValue::new(Arc::new(Self {
19            value: Mutex::new(None),
20        }))
21    }
22}
23
24#[async_trait::async_trait]
25impl<T: Clone + Persist> PersistedValueTrait<T> for MemoryPersistedValue<T> {
26    async fn get(&self) -> Result<Option<T>, PersistedValueError> {
27        Ok(self.value.lock().expect("Mutex is not poisoned").clone())
28    }
29
30    async fn set(&self, value: T) -> Result<(), PersistedValueError> {
31        *self.value.lock().expect("Mutex is not poisoned") = Some(value);
32        Ok(())
33    }
34
35    async fn remove(&self) -> Result<(), PersistedValueError> {
36        *self.value.lock().expect("Mutex is not poisoned") = None;
37        Ok(())
38    }
39}