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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use std::{convert::TryFrom, marker::PhantomData};

use oasis_core_runtime::storage::mkvs;

use super::Store;

/// A key-value store that transparently handles serialization/deserialization.
pub struct TypedStore<S: Store> {
    parent: S,
}

impl<S: Store> TypedStore<S> {
    /// Create a new typed store.
    pub fn new(parent: S) -> Self {
        Self { parent }
    }

    /// Fetch entry with given key.
    pub fn get<K: AsRef<[u8]>, T: cbor::Decode>(&self, key: K) -> Option<T> {
        self.parent
            .get(key.as_ref())
            .map(|data| cbor::from_slice(&data).unwrap())
    }

    /// Update entry with given key to the given value.
    pub fn insert<K: AsRef<[u8]>, T: cbor::Encode>(&mut self, key: K, value: T) {
        self.parent.insert(key.as_ref(), &cbor::to_vec(value))
    }

    /// Remove entry with given key.
    pub fn remove<K: AsRef<[u8]>>(&mut self, key: K) {
        self.parent.remove(key.as_ref())
    }

    pub fn iter<'store, K, V>(&'store self) -> TypedStoreIterator<'store, K, V>
    where
        K: for<'k> TryFrom<&'k [u8]>,
        V: cbor::Decode + Default,
    {
        TypedStoreIterator::new(self.parent.iter())
    }
}

/// An iterator over the `TypedStore`.
pub struct TypedStoreIterator<'store, K, V>
where
    K: for<'k> TryFrom<&'k [u8]>,
    V: Default + cbor::Decode,
{
    inner: Box<dyn mkvs::Iterator + 'store>,

    _key: PhantomData<K>,
    _value: PhantomData<V>,
}

impl<'store, K, V> TypedStoreIterator<'store, K, V>
where
    K: for<'k> TryFrom<&'k [u8]>,
    V: cbor::Decode + Default,
{
    fn new(inner: Box<dyn mkvs::Iterator + 'store>) -> Self {
        Self {
            inner,
            _key: PhantomData,
            _value: PhantomData,
        }
    }
}

impl<'store, K, V, E> Iterator for TypedStoreIterator<'store, K, V>
where
    K: for<'k> TryFrom<&'k [u8], Error = E>,
    E: std::fmt::Display,
    V: cbor::Decode + Default,
{
    type Item = (K, V);

    fn next(&mut self) -> Option<Self::Item> {
        Iterator::next(&mut self.inner).map(|(k, v)| {
            let key = K::try_from(&k).unwrap_or_else(|e| panic!("corrupted storage key: {e}"));
            let value = if v.is_empty() {
                // Ignore empty values as those would fail CBOR decoding.
                Default::default()
            } else {
                cbor::from_slice(&v).unwrap()
            };
            (key, value)
        })
    }
}