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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
extern crate alloc;

pub trait Storage {
    type Error;

    fn contains(&self, key: impl AsRef<str>) -> Result<bool, Self::Error>;

    fn remove(&mut self, key: impl AsRef<str>) -> Result<bool, Self::Error>;

    fn len(&self, key: impl AsRef<str>) -> Result<Option<usize>, Self::Error> {
        Ok(self.get_raw(key)?.map(|v| v.len()))
    }

    fn get_raw(&self, key: impl AsRef<str>) -> Result<Option<alloc::vec::Vec<u8>>, Self::Error>;

    fn put_raw(
        &mut self,
        key: impl AsRef<str>,
        value: impl Into<alloc::vec::Vec<u8>>,
    ) -> Result<bool, Self::Error>;

    #[cfg(feature = "use_serde")]
    fn get<T: serde::de::DeserializeOwned>(
        &self,
        key: impl AsRef<str>,
    ) -> Result<Option<T>, Self::Error> {
        let data = self.get_raw(key)?;

        Ok(data.map(|data| serde_json::from_slice::<T>(&data).unwrap()))
    }

    #[cfg(feature = "use_serde")]
    fn put(
        &mut self,
        key: impl AsRef<str>,
        value: &impl serde::Serialize,
    ) -> Result<bool, Self::Error> {
        self.put_raw(key, &*serde_json::to_vec(value).unwrap()) // TODO
    }
}

pub struct AnyhowStorage<T>(pub T);

impl<E, S> Storage for AnyhowStorage<S>
where
    E: Into<anyhow::Error>,
    S: Storage<Error = E>,
{
    type Error = anyhow::Error;

    fn contains(&self, key: impl AsRef<str>) -> Result<bool, Self::Error> {
        self.0.contains(key).map_err(Into::into)
    }

    fn remove(&mut self, key: impl AsRef<str>) -> Result<bool, Self::Error> {
        self.0.remove(key).map_err(Into::into)
    }

    fn len(&self, key: impl AsRef<str>) -> Result<Option<usize>, Self::Error> {
        self.0.len(key).map_err(Into::into)
    }

    fn get_raw(&self, key: impl AsRef<str>) -> Result<Option<alloc::vec::Vec<u8>>, Self::Error> {
        self.0.get_raw(key).map_err(Into::into)
    }

    fn put_raw(
        &mut self,
        key: impl AsRef<str>,
        value: impl Into<alloc::vec::Vec<u8>>,
    ) -> Result<bool, Self::Error> {
        self.0.put_raw(key, value).map_err(Into::into)
    }

    #[cfg(feature = "use_serde")]
    fn get<T: serde::de::DeserializeOwned>(
        &self,
        key: impl AsRef<str>,
    ) -> Result<Option<T>, Self::Error> {
        self.0.get(key).map_err(Into::into)
    }

    #[cfg(feature = "use_serde")]
    fn put(
        &mut self,
        key: impl AsRef<str>,
        value: &impl serde::Serialize,
    ) -> Result<bool, Self::Error> {
        self.0.put(key, value).map_err(Into::into)
    }
}

pub struct MemoryStorage(alloc::collections::BTreeMap<alloc::string::String, alloc::vec::Vec<u8>>);

impl MemoryStorage {
    pub fn new() -> Self {
        Self(alloc::collections::BTreeMap::new())
    }
}

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

impl Storage for MemoryStorage {
    type Error = core::convert::Infallible;

    fn contains(&self, key: impl AsRef<str>) -> Result<bool, Self::Error> {
        Ok(self.0.contains_key(key.as_ref()))
    }

    fn remove(&mut self, key: impl AsRef<str>) -> Result<bool, Self::Error> {
        Ok(self.0.remove(key.as_ref()).is_some())
    }

    fn get_raw(&self, key: impl AsRef<str>) -> Result<Option<alloc::vec::Vec<u8>>, Self::Error> {
        Ok(self.0.get(key.as_ref()).map(Clone::clone))
    }

    fn put_raw(
        &mut self,
        key: impl AsRef<str>,
        value: impl Into<alloc::vec::Vec<u8>>,
    ) -> Result<bool, Self::Error> {
        Ok(if let Some(r) = self.0.get_mut(key.as_ref()) {
            *r = value.into();
            true
        } else {
            self.0
                .insert(key.as_ref().to_owned(), value.into())
                .is_some()
        })
    }
}

pub struct StorageCache<T: Storage>(T, core::cell::RefCell<MemoryStorage>);

impl<T: Storage> StorageCache<T> {
    pub fn new(storage: T) -> Self {
        Self(storage, core::cell::RefCell::new(MemoryStorage::new()))
    }

    pub fn flush(&mut self) {
        self.1 = core::cell::RefCell::new(MemoryStorage::new());
    }
}

impl<T: Storage> Storage for StorageCache<T> {
    type Error = T::Error;

    fn contains(&self, key: impl AsRef<str>) -> Result<bool, Self::Error> {
        Ok(self.1.borrow().contains(&key).unwrap() || self.0.contains(key)?)
    }

    fn remove(&mut self, key: impl AsRef<str>) -> Result<bool, Self::Error> {
        self.1.borrow_mut().remove(&key).unwrap(); // TODO
        self.0.remove(key)
    }

    fn get_raw(&self, key: impl AsRef<str>) -> Result<Option<alloc::vec::Vec<u8>>, Self::Error> {
        if let Some(data) = self.1.borrow().get_raw(&key).unwrap() {
            Ok(Some(data))
        } else if let Some(data) = self.0.get_raw(&key)? {
            self.1.borrow_mut().put_raw(&key, data.clone()).unwrap(); // TODO
            Ok(Some(data))
        } else {
            self.1.borrow_mut().remove(key).unwrap();
            Ok(None)
        }
    }

    fn put_raw(
        &mut self,
        key: impl AsRef<str>,
        value: impl Into<alloc::vec::Vec<u8>>,
    ) -> Result<bool, Self::Error> {
        let value = value.into();
        self.1.borrow_mut().put_raw(&key, value.clone()).unwrap(); // TODO
        self.0.put_raw(key, value)
    }
}