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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
use core::fmt;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::u64;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::traits::DataStore;
use crate::Error;
use super::PhantomUnsync;
mod extend;
mod iterator;
/// mimics the API of [`VecDeque`](std::collections::VecDeque)
pub struct VecDeque<T, DS>
where
DS: DataStore,
{
phantom: PhantomData<T>,
phantom2: PhantomUnsync,
ds: DS,
prefix: u8,
// Points to the current free slot
head: Arc<AtomicU64>,
// Points to the current free slot
tail: Arc<AtomicU64>,
}
#[derive(Serialize, Deserialize, Hash, Eq, PartialEq, Clone, Debug)]
pub struct Prefixed {
prefix: u8,
/// Rather large so we can *just* start in the middle and be sure
/// you can never reach an edge
index: u64,
}
impl Prefixed {
pub fn index(&self) -> u64 {
self.index
}
pub fn min(prefix: u8) -> Self {
Self { prefix, index: 0 }
}
pub fn max(prefix: u8) -> Self {
Self {
prefix,
index: u64::MAX,
}
}
}
impl<T, E, DS> VecDeque<T, DS>
where
E: fmt::Debug,
T: Serialize + DeserializeOwned,
DS: DataStore<DbError = E>,
{
#[doc(hidden)]
pub fn new(ds: DS, prefix: u8, head: Arc<AtomicU64>, tail: Arc<AtomicU64>) -> Self {
assert_ne!(
head.load(Ordering::Relaxed),
tail.load(Ordering::Relaxed),
"VecDeque::new failed"
);
Self {
phantom: PhantomData,
phantom2: PhantomData,
ds,
prefix,
head,
tail,
}
}
/// Returns the element at `index` if there is one.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// assert_eq!(db.list().get(0)?, None);
/// db.list().push_back("a")?;
/// db.list().push_back("b")?;
/// assert_eq!(db.list().get(0)?, Some("a".to_owned()));
/// # Ok(())
/// # }
/// ```
pub fn get(&self, index: usize) -> Result<Option<T>, Error<E>> {
if index >= self.len() as usize {
return Ok(None);
}
let head = self.head.load(Ordering::Relaxed);
let db_index = index as u64 + head + 1;
let key = Prefixed {
prefix: self.prefix,
index: db_index,
};
self.ds.get(&key)
}
/// Appends an element to the back of the collection.
///
/// The item may be any borrowed form of the lists item type, but the
/// serialized form must match the not borrowed serialized form.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list().push_back("a")?;
/// db.list().push_back("b")?;
/// # Ok(())
/// # }
/// ```
pub fn push_back<Q>(&self, value: &Q) -> Result<(), Error<E>>
where
T: std::borrow::Borrow<Q>,
Q: Serialize + ?Sized,
{
let free_tail = self.tail.fetch_add(1, Ordering::SeqCst);
let key = Prefixed {
prefix: self.prefix,
index: free_tail,
};
self.ds.insert::<Prefixed, Q, T>(&key, value)?;
Ok(())
}
/// Appends an element to the front of the collection.
///
/// The item may be any borrowed form of the lists item type, but the
/// serialized form must match the not borrowed serialized form.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list().push_front("b")?;
/// db.list().push_front("a")?;
/// # Ok(())
/// # }
/// ```
pub fn push_front<Q>(&self, value: &Q) -> Result<(), Error<E>>
where
T: std::borrow::Borrow<Q>,
Q: Serialize + ?Sized,
{
let free_head = self.head.fetch_sub(1, Ordering::SeqCst);
let key = Prefixed {
prefix: self.prefix,
index: free_head,
};
self.ds.insert::<Prefixed, Q, T>(&key, value)?;
Ok(())
}
/// Removes the last element from this database deque and returns it,
/// or `None` if it is empty
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list().extend(["a", "b", "c"])?;
/// assert_eq!(db.list().pop_back()?, Some("c".to_owned()));
/// # Ok(())
/// # }
/// ```
pub fn pop_back(&self) -> Result<Option<T>, Error<E>> {
let tail = self.tail.load(Ordering::Relaxed);
let head = self.head.load(Ordering::Relaxed);
let next_tail = tail - 1;
if next_tail != head {
self.tail.store(tail - 1, Ordering::Relaxed);
}
// TODO TAIL AND HEAD COLLIDE, TEST THIS AND FIX POP_FRONT SIMILARLY
let key = Prefixed {
prefix: self.prefix,
index: tail - 1,
};
self.ds.remove(&key)
}
/// Removes the first element from this database deque and returns it,
/// or `None` if it is empty
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list().extend(["a", "b", "c"])?;
/// assert_eq!(db.list().pop_front()?, Some("a".to_owned()));
/// # Ok(())
/// # }
/// ```
pub fn pop_front(&self) -> Result<Option<T>, Error<E>> {
let free_head = self.head.fetch_add(1, Ordering::Relaxed);
let key = Prefixed {
prefix: self.prefix,
index: free_head + 1,
};
self.ds.remove(&key)
}
/// Clears the list, removing all values.
///
/// # Errors
/// This can fail if the underlying database ran into a problem
/// or if serialization failed.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list().extend(["a", "b", "c"])?;
/// assert!(!db.list().is_empty());
/// db.list().clear();
/// dbg!("post_clear");
/// assert!(db.list().is_empty());
/// dbg!("post fn");
/// # Ok(())
/// # }
/// ```
pub fn clear(&self) -> Result<(), Error<E>> {
// Keep going back until nothing left, as long as pop_back works
// concurrently this is safe too
while self.pop_back()?.is_some() {}
Ok(())
}
/// Returns the number of elements in the list, also referred to as its 'length'.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list().extend(["a", "b", "c"])?;
/// assert_eq!(db.list().len(), 3);
/// # Ok(())
/// # }
/// ```
pub fn len(&self) -> usize {
let head = self.head.load(Ordering::Acquire);
let tail = self.tail.load(Ordering::Acquire);
return ((tail - head) - 1) as usize;
}
/// Returns `true` if the list has a length of 0.
///
/// # Examples
/// ```
/// #[dbstruct::dbstruct(db=btreemap)]
/// struct Test {
/// list_a: VecDeque<String>,
/// list_b: VecDeque<String>,
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Test::new()?;
/// db.list_a().extend(["a", "b", "c"])?;
/// assert!(!db.list_a().is_empty());
/// assert!(db.list_b().is_empty());
/// # Ok(())
/// # }
/// ```
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<T, E, DS> fmt::Debug for VecDeque<T, DS>
where
E: fmt::Debug,
T: Serialize + DeserializeOwned + fmt::Debug,
DS: DataStore<DbError = E>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("[\n")?;
for element in self.iter() {
match element {
Ok(val) => f.write_fmt(format_args!(" {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")
}
}