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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use core::fmt;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::borrow::Borrow;
use std::marker::PhantomData;
use tracing::{instrument, trace};
use crate::traits::{byte_store, DataStore};
use crate::Error;
use super::PhantomUnsync;
mod extend;
mod iterator;
/// mimics the API of [`HashMap`][std::collections::HashMap]
pub struct Map<'a, Key, Value, DS>
where
Key: Serialize,
Value: Serialize + DeserializeOwned,
DS: DataStore,
{
phantom_key: PhantomData<&'a Key>,
phantom_val: PhantomData<Value>,
phantom2: PhantomUnsync,
tree: DS,
prefix: u8,
}
#[derive(Serialize)]
pub struct Prefixed<'a, K: ?Sized> {
prefix: u8,
key: &'a K,
}
impl<'a, Key, Value, E, DS> Map<'a, Key, Value, DS>
where
E: fmt::Debug,
Key: Serialize + DeserializeOwned,
Value: Serialize + DeserializeOwned,
DS: DataStore<DbError = E>,
{
#[doc(hidden)]
#[instrument(skip(tree), level = "debug")]
pub fn new(tree: DS, prefix: u8) -> Self {
Self {
phantom_key: PhantomData,
phantom_val: PhantomData,
phantom2: PhantomData,
tree,
prefix,
}
}
fn prefix<Q>(&self, key: &'a Q) -> Prefixed<'a, Q>
where
Key: Borrow<Q>,
Q: Serialize + ?Sized,
{
trace!("prefixing key with: {}", self.prefix);
Prefixed {
prefix: self.prefix,
key,
}
}
/// Inserts a key-value pair into the map.
///
/// If the map did not have this key present, [`None`] is returned.
///
/// If the map did have this key present, the value is updated, and the old
/// value is returned. The key is not updated, though.
///
/// The key and or value may be any borrowed form of the map’s key and or
/// value type, but the serialized form must match those for the key and
/// or value type.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// map: HashMap<u16, String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// assert_eq!(db.map().insert(&37, "a")?, None);
/// assert_eq!(db.map().is_empty()?, false);
///
/// db.map().insert(&37, "b")?;
/// assert_eq!(db.map().insert(&37, "c")?, Some("b".to_owned()));
/// assert_eq!(db.map().get(&37)?, Some("c".to_owned()));
/// # Ok(())
/// # }
/// ```
#[instrument(skip_all, level = "debug")]
pub fn insert<K, V>(&self, key: &'a K, value: &'a V) -> Result<Option<Value>, Error<E>>
where
Key: std::borrow::Borrow<K>,
K: Serialize + ?Sized,
Value: std::borrow::Borrow<V>,
V: Serialize + ?Sized,
{
let key = self.prefix(key);
let existing = self.tree.insert(&key, value)?;
Ok(existing)
}
/// Returns a copy of the value corresponding to the key.
///
/// The key may be any borrowed form of the map’s key type, but the
/// serialized form must match those for the key type.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// map: HashMap<u16, String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.map().insert(&1, &"a".to_owned())?;
/// assert_eq!(db.map().get(&1)?, Some("a".to_owned()));
/// assert_eq!(db.map().get(&2)?, None);
/// # Ok(())
/// # }
/// ```
#[instrument(skip_all, level = "debug")]
pub fn get<K>(&self, key: &'a K) -> Result<Option<Value>, Error<E>>
where
Key: std::borrow::Borrow<K>,
K: Serialize + ?Sized,
{
let key = self.prefix(key);
let value = self.tree.get(&key)?;
Ok(value)
}
/// Returns a key from the map, returning the value at the key if the key
/// was previously in the map.
///
/// The key may be any borrowed form of the map’s key type, but the
/// serialized form must match those for the key type.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
///
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// map: HashMap<u16, String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.map().insert(&1, &"a".to_owned())?;
/// assert_eq!(db.map().remove(&1)?, Some("a".to_owned()));
/// assert_eq!(db.map().remove(&2)?, None);
/// # Ok(())
/// # }
/// ```
#[instrument(skip_all, level = "debug")]
pub fn remove<K>(&self, key: &'a K) -> Result<Option<Value>, Error<E>>
where
Key: std::borrow::Borrow<K>,
K: Serialize + ?Sized,
{
let key = self.prefix(key);
let value = self.tree.remove(&key)?;
Ok(value)
}
}
impl<Key, Value, E, DS> Map<'_, Key, Value, DS>
where
E: fmt::Debug,
Key: Serialize + DeserializeOwned,
Value: Serialize + DeserializeOwned,
DS: DataStore<DbError = E> + byte_store::Ordered,
Error<E>: From<Error<<DS as crate::ByteStore>::DbError>>,
{
/// Clears the map, removing all key-value pairs.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
///
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// map: HashMap<u16, String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.map().insert(&1, &"a".to_owned())?;
/// db.map().clear()?;
/// assert!(db.map().is_empty()?);
/// # Ok(())
/// # }
/// ```
pub fn clear(&self) -> Result<(), Error<E>> {
for key in self.keys() {
let key = key?;
self.remove(&key)?;
}
Ok(())
}
/// Returns true if the map contains no elements.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
///
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// map: HashMap<u16, String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// assert!(db.map().is_empty()?);
/// db.map().insert(&1, &"a".to_owned())?;
/// assert!(!db.map().is_empty()?);
/// # Ok(())
/// # }
/// ```
pub fn is_empty(&self) -> Result<bool, Error<E>> {
Ok(self.iter().next().is_none())
}
}
impl<Key, Value, E, DS> fmt::Debug for Map<'_, Key, Value, DS>
where
E: fmt::Debug,
Key: Serialize + DeserializeOwned + fmt::Debug,
Value: Serialize + DeserializeOwned + fmt::Debug,
DS: DataStore<DbError = E> + byte_store::Ordered,
Error<E>: From<Error<<DS as crate::ByteStore>::DbError>>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[\n")?;
for element in self.iter() {
match element {
Ok((key, val)) => f.write_fmt(format_args!(" {key:?}: {val:?},\n"))?,
Err(err) => {
f.write_fmt(format_args!(
"ERROR while printing full list, could \
not read next element from db: {err}"
))?;
return Ok(());
}
}
}
f.write_str("]\n")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stores;
pub(crate) type TestMap<'a, K, V> = Map<'a, K, V, stores::BTreeMap>;
pub(crate) fn empty<'a, K, V>() -> TestMap<'a, K, V>
where
K: Clone + Serialize + DeserializeOwned,
V: Clone + Serialize + DeserializeOwned,
{
let ds = stores::BTreeMap::new();
let map = Map::new(ds, 1);
map
}
}