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
use crate::{CryptoKVStorage, Error, GetResponse, KVStorage};
use diem_time_service::{TimeService, TimeServiceTrait};
use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;
#[derive(Default)]
pub struct InMemoryStorage {
data: HashMap<String, Vec<u8>>,
time_service: TimeService,
}
impl InMemoryStorage {
pub fn new() -> Self {
Self::new_with_time_service(TimeService::real())
}
}
impl InMemoryStorage {
pub fn new_with_time_service(time_service: TimeService) -> Self {
Self {
data: HashMap::new(),
time_service,
}
}
}
impl KVStorage for InMemoryStorage {
fn available(&self) -> Result<(), Error> {
Ok(())
}
fn get<V: DeserializeOwned>(&self, key: &str) -> Result<GetResponse<V>, Error> {
let response = self
.data
.get(key)
.ok_or_else(|| Error::KeyNotSet(key.to_string()))?;
serde_json::from_slice(response).map_err(|e| e.into())
}
fn set<V: Serialize>(&mut self, key: &str, value: V) -> Result<(), Error> {
let now = self.time_service.now_secs();
self.data.insert(
key.to_string(),
serde_json::to_vec(&GetResponse::new(value, now))?,
);
Ok(())
}
#[cfg(any(test, feature = "testing"))]
fn reset_and_clear(&mut self) -> Result<(), Error> {
self.data.clear();
Ok(())
}
}
impl CryptoKVStorage for InMemoryStorage {}