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
//! Runtime storage interfaces and implementations.
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

use crate::types::Error;

pub mod mkvs;

// Re-exports.
pub use self::mkvs::MKVS;

/// Trivial key/value storage.
pub trait KeyValue: Send + Sync {
    /// Fetch the value for a specific key.
    fn get(&self, key: Vec<u8>) -> Result<Vec<u8>, Error>;

    /// Store a specific key/value into storage.
    fn insert(&self, key: Vec<u8>, value: Vec<u8>) -> Result<(), Error>;
}

impl<T: ?Sized + KeyValue> KeyValue for Arc<T> {
    fn get(&self, key: Vec<u8>) -> Result<Vec<u8>, Error> {
        KeyValue::get(&**self, key)
    }

    fn insert(&self, key: Vec<u8>, value: Vec<u8>) -> Result<(), Error> {
        KeyValue::insert(&**self, key, value)
    }
}

/// Untrusted key/value storage which stores arbitrary binary key/value pairs
/// in memory.
pub struct UntrustedInMemoryStorage {
    store: Mutex<HashMap<Vec<u8>, Vec<u8>>>,
}

impl UntrustedInMemoryStorage {
    pub fn new() -> Self {
        Self {
            store: Mutex::new(HashMap::new()),
        }
    }
}

impl KeyValue for UntrustedInMemoryStorage {
    fn get(&self, key: Vec<u8>) -> Result<Vec<u8>, Error> {
        // Return an empty vector if the key is not found.
        let cache = self.store.lock().unwrap();
        let value = cache.get(&key).cloned().unwrap_or_default();
        Ok(value)
    }

    fn insert(&self, key: Vec<u8>, value: Vec<u8>) -> Result<(), Error> {
        let mut cache = self.store.lock().unwrap();
        cache.insert(key, value);
        Ok(())
    }
}

impl Default for UntrustedInMemoryStorage {
    fn default() -> Self {
        Self::new()
    }
}