oasis_core_runtime/storage/
mod.rs

1//! Runtime storage interfaces and implementations.
2use std::{
3    collections::HashMap,
4    sync::{Arc, Mutex},
5};
6
7use crate::types::Error;
8
9pub mod mkvs;
10
11// Re-exports.
12pub use self::mkvs::MKVS;
13
14/// Trivial key/value storage.
15pub trait KeyValue: Send + Sync {
16    /// Fetch the value for a specific key.
17    fn get(&self, key: Vec<u8>) -> Result<Vec<u8>, Error>;
18
19    /// Store a specific key/value into storage.
20    fn insert(&self, key: Vec<u8>, value: Vec<u8>) -> Result<(), Error>;
21}
22
23impl<T: ?Sized + KeyValue> KeyValue for Arc<T> {
24    fn get(&self, key: Vec<u8>) -> Result<Vec<u8>, Error> {
25        KeyValue::get(&**self, key)
26    }
27
28    fn insert(&self, key: Vec<u8>, value: Vec<u8>) -> Result<(), Error> {
29        KeyValue::insert(&**self, key, value)
30    }
31}
32
33/// Untrusted key/value storage which stores arbitrary binary key/value pairs
34/// in memory.
35pub struct UntrustedInMemoryStorage {
36    store: Mutex<HashMap<Vec<u8>, Vec<u8>>>,
37}
38
39impl UntrustedInMemoryStorage {
40    pub fn new() -> Self {
41        Self {
42            store: Mutex::new(HashMap::new()),
43        }
44    }
45}
46
47impl KeyValue for UntrustedInMemoryStorage {
48    fn get(&self, key: Vec<u8>) -> Result<Vec<u8>, Error> {
49        // Return an empty vector if the key is not found.
50        let cache = self.store.lock().unwrap();
51        let value = cache.get(&key).cloned().unwrap_or_default();
52        Ok(value)
53    }
54
55    fn insert(&self, key: Vec<u8>, value: Vec<u8>) -> Result<(), Error> {
56        let mut cache = self.store.lock().unwrap();
57        cache.insert(key, value);
58        Ok(())
59    }
60}
61
62impl Default for UntrustedInMemoryStorage {
63    fn default() -> Self {
64        Self::new()
65    }
66}