menhirkv 0.4.5

MenhirKV is yet another local KV store based on RocksDB.
Documentation
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Copyright (C) 2024 Christian Mauduit <ufoot@ufoot.org>

use crate::error::{Error, Result};
use crate::serial::*;
use ofilter::SyncStream;
use rocksdb::DBIteratorWithThreadMode;
use rocksdb::DB;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fmt;
use std::marker::PhantomData;

/// Iterator over a KV store.
///
///
/// IMPORTANT: the iterator will only iterate on entries which would
/// be removed by the next compaction. This means you could have
/// an item which is retrievable by `get()` or `peek()`, yet will
/// never be yielded by the iterator.
///
/// The idea is that when you
/// iterate, you care about what is "recent" and "important".
/// Old items which are still in the database are still available
/// if you know their keys, but they are not discoverable through
/// iterators.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_temporary(100).unwrap();
/// store.put(&1, &2).unwrap();
/// store.put(&3, &4).unwrap();
/// store.put(&5, &6).unwrap();
/// for item in store.iter().unwrap() {
///     let item = item.unwrap();
///     println!("key: {}, value: {}", item.0, item.1);
/// }
/// ```
// #[derive(Debug)]
pub struct Iter<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub(crate) inner: DBIteratorWithThreadMode<'a, DB>,
    pub(crate) filter: SyncStream<Vec<u8>>,
    pub(crate) done: usize,
    pub(crate) phantom_data: PhantomData<(K, V)>,
}

impl<K, V> fmt::Display for Iter<'_, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/?", self.done)
    }
}

impl<'a, K, V> Iterator for Iter<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    type Item = Result<(K, V)>;

    fn next(&mut self) -> Option<Result<(K, V)>> {
        loop {
            if let Some(res) = self.inner.next() {
                match res {
                    Ok(item) => {
                        let (kbuf, vbuf) = item;
                        let kvec: &Vec<u8> = &kbuf.to_vec();
                        if !self.filter.check(kvec) {
                            continue;
                        }
                        return match deserialize_key(kbuf) {
                            Ok(k) => match deserialize_value(vbuf) {
                                Ok(v) => Some(Ok((k, v))),
                                Err(e) => Some(Err(e)),
                            },
                            Err(e) => Some(Err(e)),
                        };
                    }
                    Err(e) => return Some(Err(Error::from(e))),
                }
            } else {
                break;
            }
        }
        None
    }
}

/// Iterator over the keys of a KV store.
///
/// Only yield keys that would still be here after a compaction.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_temporary(100).unwrap();
/// store.put(&1, &2).unwrap();
/// store.put(&3, &4).unwrap();
/// store.put(&5, &6).unwrap();
/// for key in store.keys().unwrap() {
///     let key = key.unwrap();
///     println!("key: {}", key);
/// }
/// ```
// #[derive(Debug)]
pub struct Keys<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub(crate) inner: DBIteratorWithThreadMode<'a, DB>,
    pub(crate) filter: SyncStream<Vec<u8>>,
    pub(crate) done: usize,
    pub(crate) phantom_data: PhantomData<(K, V)>,
}

impl<K, V> fmt::Display for Keys<'_, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/?", self.done)
    }
}

impl<'a, K, V> Iterator for Keys<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    type Item = Result<K>;

    fn next(&mut self) -> Option<Result<K>> {
        loop {
            if let Some(res) = self.inner.next() {
                match res {
                    Ok(item) => {
                        let kvec: &Vec<u8> = &item.0.to_vec();
                        if !self.filter.check(kvec) {
                            continue;
                        }
                        return Some(deserialize_key(item.0));
                    }
                    Err(e) => return Some(Err(Error::from(e))),
                }
            } else {
                break;
            }
        }
        None
    }
}

/// Iterator over the values of a KV store.
///
/// Only yield values that would still be here after a compaction.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_temporary(100).unwrap();
/// store.put(&1, &2).unwrap();
/// store.put(&3, &4).unwrap();
/// store.put(&5, &6).unwrap();
/// for value in store.values().unwrap() {
///     let value = value.unwrap();
///     println!("value: {}", value);
/// }
/// ```
// #[derive(Debug)]
pub struct Values<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub(crate) inner: DBIteratorWithThreadMode<'a, DB>,
    pub(crate) filter: SyncStream<Vec<u8>>,
    pub(crate) done: usize,
    pub(crate) phantom_data: PhantomData<(K, V)>,
}

impl<K, V> fmt::Display for Values<'_, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/?", self.done)
    }
}

impl<'a, K, V> Iterator for Values<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    type Item = Result<V>;

    fn next(&mut self) -> Option<Result<V>> {
        loop {
            if let Some(res) = self.inner.next() {
                match res {
                    Ok(item) => {
                        let (kbuf, vbuf) = item;
                        let kvec: &Vec<u8> = &kbuf.to_vec();
                        if !self.filter.check(kvec) {
                            continue;
                        }
                        return Some(deserialize_value(vbuf));
                    }
                    Err(e) => return Some(Err(Error::from(e))),
                }
            } else {
                break;
            }
        }
        None
    }
}

/// Export a KV store.
///
/// The difference between this and a standard iterator is that
/// this one returns `(K, V)` instead of `Result<(K, V)>`.
/// A consequence of this is that it may `panic()` at any iteration,
/// as there can always be an error, and it will not catch it.
///
/// If you want something failsafe, use the standard iterator.
/// This one is easier to use, but can crash your program.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_temporary(100).unwrap();
/// store.put(&1, &2).unwrap();
/// store.put(&3, &4).unwrap();
/// store.put(&5, &6).unwrap();
/// let export = store.export().unwrap().collect::<Vec<(usize, usize)>>(); // may panic()
/// assert_eq!(3, export.len());
/// ```
// #[derive(Debug)]
pub struct Export<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub(crate) inner: DBIteratorWithThreadMode<'a, DB>,
    pub(crate) filter: SyncStream<Vec<u8>>,
    pub(crate) done: usize,
    pub(crate) phantom_data: PhantomData<(K, V)>,
}

impl<K, V> fmt::Display for Export<'_, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/?", self.done)
    }
}

impl<'a, K, V> Export<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub fn try_next(&mut self) -> Result<Option<(K, V)>> {
        loop {
            if let Some(res) = self.inner.next() {
                match res {
                    Ok(item) => {
                        let (kbuf, vbuf) = item;
                        let kvec: &Vec<u8> = &kbuf.to_vec();
                        if !self.filter.check(kvec) {
                            continue;
                        }
                        return match deserialize_key(kbuf) {
                            Ok(k) => match deserialize_value(vbuf) {
                                Ok(v) => Ok(Some((k, v))),
                                Err(e) => Err(e),
                            },
                            Err(e) => Err(e),
                        };
                    }
                    Err(e) => return Err(Error::from(e)),
                }
            } else {
                break;
            }
        }
        Ok(None)
    }
}

impl<'a, K, V> Iterator for Export<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    type Item = (K, V);

    fn next(&mut self) -> Option<(K, V)> {
        match self.try_next() {
            Ok(item) => item,
            Err(e) => panic!("export error: {}", e),
        }
    }
}

/// Export the keys of a KV store.
///
/// The difference between this and a standard iterator is that
/// this one returns `K` instead of `Result<K>`.
/// A consequence of this is that it may `panic()` at any iteration,
/// as there can always be an error, and it will not catch it.
///
/// If you want something failsafe, use the standard iterator.
/// This one is easier to use, but can crash your program.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_temporary(100).unwrap();
/// store.put(&1, &2).unwrap();
/// store.put(&3, &4).unwrap();
/// store.put(&5, &6).unwrap();
/// let mut keys = store.export_keys().unwrap().collect::<Vec<usize>>(); // may panic()
/// keys.sort();
/// assert_eq!(vec![1, 3, 5], keys);
/// ```
// #[derive(Debug)]
pub struct ExportKeys<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub(crate) inner: DBIteratorWithThreadMode<'a, DB>,
    pub(crate) filter: SyncStream<Vec<u8>>,
    pub(crate) done: usize,
    pub(crate) phantom_data: PhantomData<(K, V)>,
}

impl<K, V> fmt::Display for ExportKeys<'_, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/?", self.done)
    }
}

impl<'a, K, V> ExportKeys<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub fn try_next(&mut self) -> Result<Option<K>> {
        loop {
            if let Some(res) = self.inner.next() {
                match res {
                    Ok(item) => {
                        let kvec: &Vec<u8> = &item.0.to_vec();
                        if !self.filter.check(kvec) {
                            continue;
                        }
                        return match deserialize_key(item.0) {
                            Ok(k) => Ok(Some(k)),
                            Err(e) => Err(e),
                        };
                    }
                    Err(e) => return Err(Error::from(e)),
                }
            } else {
                break;
            }
        }
        Ok(None)
    }
}

impl<'a, K, V> Iterator for ExportKeys<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    type Item = K;

    fn next(&mut self) -> Option<K> {
        match self.try_next() {
            Ok(item) => item,
            Err(e) => panic!("export error: {}", e),
        }
    }
}

/// Export the values of a KV store.
///
/// The difference between this and a standard iterator is that
/// this one returns `V` instead of `Result<V>`.
/// A consequence of this is that it may `panic()` at any iteration,
/// as there can always be an error, and it will not catch it.
///
/// If you want something failsafe, use the standard iterator.
/// This one is easier to use, but can crash your program.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_temporary(100).unwrap();
/// store.put(&1, &2).unwrap();
/// store.put(&3, &4).unwrap();
/// store.put(&5, &6).unwrap();
/// let mut values = store.export_values().unwrap().collect::<Vec<usize>>(); // may panic()
/// values.sort();
/// assert_eq!(vec![2, 4, 6], values);
/// ```
// #[derive(Debug)]
pub struct ExportValues<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub(crate) inner: DBIteratorWithThreadMode<'a, DB>,
    pub(crate) filter: SyncStream<Vec<u8>>,
    pub(crate) done: usize,
    pub(crate) phantom_data: PhantomData<(K, V)>,
}

impl<K, V> fmt::Display for ExportValues<'_, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/?", self.done)
    }
}

impl<'a, K, V> ExportValues<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    pub fn try_next(&mut self) -> Result<Option<V>> {
        loop {
            if let Some(res) = self.inner.next() {
                match res {
                    Ok(item) => {
                        let (kbuf, vbuf) = item;
                        let kvec: &Vec<u8> = &kbuf.to_vec();
                        if !self.filter.check(kvec) {
                            continue;
                        };
                        return match deserialize_value(vbuf) {
                            Ok(v) => Ok(Some(v)),
                            Err(e) => Err(e),
                        };
                    }
                    Err(e) => return Err(Error::from(e)),
                }
            } else {
                break;
            }
        }
        Ok(None)
    }
}

impl<'a, K, V> Iterator for ExportValues<'a, K, V>
where
    K: Serialize + DeserializeOwned,
    V: Serialize + DeserializeOwned,
{
    type Item = V;

    fn next(&mut self) -> Option<V> {
        match self.try_next() {
            Ok(item) => item,
            Err(e) => panic!("export error: {}", e),
        }
    }
}

/// Iterator over the column family names of a KV store.
///
/// Use this to list the name of all column family names.
/// It will also yield the empty string, corresponding to
/// the main/root column family you open by default.
///
/// These are not necessarily exactly the names used by RocksDB
/// internally, there can be some marshalling. Typically,
/// a prefix is added. Unless you inspect the content of the
/// inner database yourself, do not worry about this.
///
/// ```
/// use menhirkv::Store;
///
/// let store = Store::<usize, usize>::open_cf_temporary(&["a", "b"], 100).unwrap();
/// let cf_names = store.iter_cf_names().collect::<Vec<&str>>();
/// assert_eq!(vec!["", "a", "b"], cf_names);
/// ```
pub struct IterCfNames<'a> {
    pub(crate) idx: isize,
    pub(crate) other_cfs: &'a Vec<String>,
}

impl fmt::Display for IterCfNames<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}", self.idx + 1, self.other_cfs.len() + 1)
    }
}

impl<'a> Iterator for IterCfNames<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.idx < 0 {
            self.idx = 0;
            return Some("");
        }
        if self.idx as usize >= self.other_cfs.len() {
            return None;
        }
        let cf_name = self.other_cfs[self.idx as usize].as_str();
        self.idx += 1;
        Some(cf_name)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.other_cfs.len() + 1 - ((self.idx + 1) as usize);
        (remaining, Some(remaining))
    }
}

impl<'a> ExactSizeIterator for IterCfNames<'a> {}