storey_storage/
backend.rs

1use super::storage::{Storage, StorageMut};
2
3/// A trait for immutably accessing a storage backend.
4///
5/// A collection of basic read operations that can be performed on a storage backend.
6///
7/// You should only have to interact with this trait if you are implementing a custom storage backend.
8pub trait StorageBackend {
9    /// Get the value associated with the given key.
10    fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
11
12    /// Check if the given key exists in the storage backend.
13    fn has(&self, key: &[u8]) -> bool {
14        self.get(key).is_some()
15    }
16}
17
18/// A trait for mutably accessing a storage backend.
19///
20/// A collection of basic write operations that can be performed on a storage backend.
21///
22/// You should only have to interact with this trait if you are implementing a custom storage backend.
23pub trait StorageBackendMut {
24    /// Set the value associated with the given key.
25    fn set(&mut self, key: &[u8], value: &[u8]);
26
27    /// Remove the value associated with the given key.
28    fn remove(&mut self, key: &[u8]);
29}
30
31impl<B> Storage for B
32where
33    B: StorageBackend + ?Sized,
34{
35    fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
36        StorageBackend::get(self, key)
37    }
38
39    fn has(&self, key: &[u8]) -> bool {
40        StorageBackend::has(self, key)
41    }
42
43    fn get_meta(&self, key: &[u8]) -> Option<Vec<u8>> {
44        StorageBackend::get(self, &meta_key(key))
45    }
46
47    fn has_meta(&self, key: &[u8]) -> bool {
48        StorageBackend::has(self, &meta_key(key))
49    }
50}
51
52impl<B> StorageMut for B
53where
54    B: StorageBackendMut + ?Sized,
55{
56    fn set(&mut self, key: &[u8], value: &[u8]) {
57        StorageBackendMut::set(self, key, value)
58    }
59
60    fn remove(&mut self, key: &[u8]) {
61        StorageBackendMut::remove(self, key)
62    }
63
64    fn set_meta(&mut self, key: &[u8], value: &[u8]) {
65        StorageBackendMut::set(self, &meta_key(key), value)
66    }
67
68    fn remove_meta(&mut self, key: &[u8]) {
69        StorageBackendMut::remove(self, &meta_key(key))
70    }
71}
72
73fn meta_key(key: &[u8]) -> Vec<u8> {
74    let mut meta_key = Vec::with_capacity(key.len() + 1);
75    meta_key.push(255);
76    meta_key.extend_from_slice(key);
77    meta_key
78}