vsdb 13.3.0

A std-collection-like database
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
//!
//! A `BTreeMap`-like structure that stores data on disk.
//!
//! `MapxOrd` provides an ordered map where keys and values are encoded before
//! being persisted. Keys are encoded using `KeyEnDeOrdered` to ensure that
// a lexicographical ordering of the encoded bytes maintains the original order of the keys.
//!
//! # Examples
//!
//! ```
//! use vsdb::basic::mapx_ord::MapxOrd;
//! use vsdb::{vsdb_set_base_dir, vsdb_get_base_dir};
//! use std::fs;
//!
//! // It's recommended to use a temporary directory for testing
//! let dir = format!("/tmp/vsdb_testing/{}", rand::random::<u128>());
//! vsdb_set_base_dir(&dir).unwrap();
//!
//! let mut m: MapxOrd<u32, String> = MapxOrd::new();
//!
//! // Insert key-value pairs
//! m.insert(&1, &"hello".to_string());
//! m.insert(&2, &"world".to_string());
//!
//! // Retrieve a value
//! assert_eq!(m.get(&1), Some("hello".to_string()));
//!
//! // Iterate over the map
//! for (k, v) in m.iter() {
//!     println!("key: {}, val: {}", k, v);
//! }
//!
//! // Remove a key-value pair
//! m.remove(&2);
//!
//! // Clear the entire map
//! m.clear();
//!
//! // Clean up the directory
//! fs::remove_dir_all(vsdb_get_base_dir()).unwrap();
//! ```
//!

#[cfg(test)]
mod test;

use crate::{
    basic::mapx_ord_rawkey::{
        MapxOrdRawKey, MapxOrdRawKeyBatchEntry, MapxOrdRawKeyIter, ValueIterMut,
        ValueMut,
    },
    common::{
        RawKey,
        ende::{KeyEnDeOrdered, ValueEnDe},
    },
    define_map_wrapper,
};
use ruc::*;
use std::{marker::PhantomData, ops::RangeBounds};
use vsdb_core::basic::mapx_raw;

define_map_wrapper! {
    #[doc = "A disk-based, `BTreeMap`-like data structure with typed, ordered keys and values."]
    #[doc = ""]
    #[doc = "`MapxOrd` stores key-value pairs on disk, ensuring that the keys are ordered."]
    pub struct MapxOrd<K, V> {
        inner: MapxOrdRawKey<V>,
        _p: PhantomData<K>,
    }
    where K: KeyEnDeOrdered, V: ValueEnDe
}

impl<K, V> MapxOrd<K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    /// Retrieves a value from the map for a given key.
    #[inline(always)]
    pub fn get(&self, key: &K) -> Option<V> {
        self.inner.get(key.to_bytes())
    }

    /// Retrieves a mutable reference to a value in the map.
    #[inline(always)]
    pub fn get_mut(&mut self, key: &K) -> Option<ValueMut<'_, V>> {
        self.inner.get_mut(key.to_bytes())
    }

    /// Checks if the map contains a value for the specified key.
    #[inline(always)]
    pub fn contains_key(&self, key: &K) -> bool {
        self.inner.contains_key(key.to_bytes())
    }

    /// Retrieves the last entry with a key less than or equal to the given key.
    #[inline(always)]
    pub fn get_le(&self, key: &K) -> Option<(K, V)> {
        self.inner
            .get_le(key.to_bytes())
            .map(|(k, v)| (pnk!(K::from_bytes(k)), v))
    }

    /// Retrieves the first entry with a key greater than or equal to the given key.
    #[inline(always)]
    pub fn get_ge(&self, key: &K) -> Option<(K, V)> {
        self.inner
            .get_ge(key.to_bytes())
            .map(|(k, v)| (pnk!(K::from_bytes(k)), v))
    }

    /// Inserts a key-value pair into the map.
    ///
    /// Does not return the old value for performance reasons.
    #[inline(always)]
    pub fn insert(&mut self, key: &K, value: &V) {
        self.inner.insert(key.to_bytes(), value)
    }

    /// Inserts a key with an already encoded value.
    ///
    /// # Safety
    ///
    /// This is a low-level API for performance-critical scenarios, such as versioned
    /// implementations. Do not use for common purposes.
    #[inline(always)]
    pub unsafe fn insert_encoded_value(&mut self, key: &K, value: impl AsRef<[u8]>) {
        unsafe { self.inner.insert_encoded_value(key.to_bytes(), value) }
    }

    /// Gets an entry for a given key, allowing for in-place modification.
    #[inline(always)]
    pub fn entry(&mut self, key: &K) -> Entry<'_, V> {
        Entry {
            key: key.to_bytes(),
            hdr: &mut self.inner,
        }
    }

    /// Returns an iterator over the map's entries.
    #[inline(always)]
    pub fn iter(&self) -> MapxOrdIter<'_, K, V> {
        MapxOrdIter {
            inner: self.inner.iter(),
            _p: PhantomData,
        }
    }

    /// Returns a mutable iterator over the map's entries.
    #[inline(always)]
    pub fn iter_mut(&mut self) -> MapxOrdIterMut<'_, K, V> {
        MapxOrdIterMut {
            inner: self.inner.inner.iter_mut(),
            _p: PhantomData,
        }
    }

    /// Returns an iterator over the map's values.
    #[inline(always)]
    pub fn values(&self) -> MapxOrdValues<'_, V> {
        MapxOrdValues {
            inner: self.inner.iter(),
        }
    }

    /// Returns a mutable iterator over the map's values.
    #[inline(always)]
    pub fn values_mut(&mut self) -> MapxOrdValuesMut<'_, V> {
        MapxOrdValuesMut {
            inner: self.inner.inner.iter_mut(),
            _p: PhantomData,
        }
    }

    /// Returns an iterator over a range of entries in the map.
    #[inline(always)]
    pub fn range<R: RangeBounds<K>>(&self, bounds: R) -> MapxOrdIter<'_, K, V> {
        let (l, h) = crate::cow_bytes_bounds!(bounds);

        MapxOrdIter {
            inner: self.inner.range((l, h)),
            _p: PhantomData,
        }
    }

    /// Returns a mutable iterator over a range of entries in the map.
    #[inline(always)]
    pub fn range_mut<R: RangeBounds<K>>(
        &mut self,
        bounds: R,
    ) -> MapxOrdIterMut<'_, K, V> {
        let (l, h) = crate::cow_bytes_bounds!(bounds);

        MapxOrdIterMut {
            inner: self.inner.inner.range_mut((l, h)),
            _p: PhantomData,
        }
    }

    /// Retrieves the first entry in the map.
    #[inline(always)]
    pub fn first(&self) -> Option<(K, V)> {
        self.iter().next()
    }

    /// Retrieves the last entry in the map.
    #[inline(always)]
    pub fn last(&self) -> Option<(K, V)> {
        self.iter().next_back()
    }

    /// Removes a key from the map.
    ///
    /// Does not return the old value for performance reasons.
    #[inline(always)]
    pub fn remove(&mut self, key: &K) {
        self.inner.remove(key.to_bytes())
    }

    /// Start a batch operation.
    ///
    /// This method allows you to perform multiple insert/remove operations
    /// and commit them atomically.
    ///
    /// # Examples
    ///
    /// ```
    /// use vsdb::basic::mapx_ord::MapxOrd;
    /// use vsdb::vsdb_set_base_dir;
    ///
    /// vsdb_set_base_dir("/tmp/vsdb_mapx_ord_batch_entry").unwrap();
    /// let mut map: MapxOrd<u32, String> = MapxOrd::new();
    ///
    /// let mut batch = map.batch_entry();
    /// batch.insert(&1, &"one".to_string());
    /// batch.insert(&2, &"two".to_string());
    /// batch.commit().unwrap();
    ///
    /// assert_eq!(map.get(&1), Some("one".to_string()));
    /// assert_eq!(map.get(&2), Some("two".to_string()));
    /// ```
    #[inline(always)]
    pub fn batch_entry(&mut self) -> MapxOrdBatchEntry<'_, K, V> {
        MapxOrdBatchEntry {
            inner: self.inner.batch_entry(),
            _marker: PhantomData,
        }
    }

    /// Returns an iterator over the map's keys in ascending order.
    #[inline(always)]
    pub fn keys(&self) -> impl Iterator<Item = K> + '_ {
        self.iter().map(|(k, _)| k)
    }
}

impl<'a, K, V> IntoIterator for &'a MapxOrd<K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    type Item = (K, V);
    type IntoIter = MapxOrdIter<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, K, V> IntoIterator for &'a mut MapxOrd<K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    type Item = (K, ValueIterMut<'a, V>);
    type IntoIter = MapxOrdIterMut<'a, K, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// A batch entry for `MapxOrd`.
pub struct MapxOrdBatchEntry<'a, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    inner: MapxOrdRawKeyBatchEntry<'a, V>,
    _marker: PhantomData<K>,
}

impl<'a, K, V> MapxOrdBatchEntry<'a, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    /// Insert a key-value pair into the batch.
    pub fn insert(&mut self, key: &K, value: &V) {
        self.inner.insert(key.to_bytes(), value);
    }

    /// Remove a key in the batch.
    pub fn remove(&mut self, key: &K) {
        self.inner.remove(key.to_bytes());
    }

    /// Commit the batch.
    pub fn commit(self) -> Result<()> {
        self.inner.commit()
    }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/// An iterator over the entries of a `MapxOrd`.
pub struct MapxOrdIter<'a, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    inner: MapxOrdRawKeyIter<'a, V>,
    _p: PhantomData<K>,
}

impl<K, V> Iterator for MapxOrdIter<'_, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    type Item = (K, V);
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, v)| (pnk!(K::from_bytes(k)), v))
    }
}

impl<K, V> DoubleEndedIterator for MapxOrdIter<'_, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner
            .next_back()
            .map(|(k, v)| (pnk!(K::from_bytes(k)), v))
    }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/// An iterator over the values of a `MapxOrd`.
pub struct MapxOrdValues<'a, V>
where
    V: ValueEnDe,
{
    /// The inner iterator over raw key-value pairs.
    pub(crate) inner: MapxOrdRawKeyIter<'a, V>,
}

impl<V> Iterator for MapxOrdValues<'_, V>
where
    V: ValueEnDe,
{
    type Item = V;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(_, v)| v)
    }
}

impl<V> DoubleEndedIterator for MapxOrdValues<'_, V>
where
    V: ValueEnDe,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(_, v)| v)
    }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/// A mutable iterator over the values of a `MapxOrd`.
pub struct MapxOrdValuesMut<'a, V>
where
    V: ValueEnDe,
{
    /// The inner mutable iterator over raw key-value pairs.
    pub(crate) inner: mapx_raw::MapxRawIterMut<'a>,
    /// A phantom data field to hold the value type.
    pub(crate) _p: PhantomData<V>,
}

impl<'a, V> Iterator for MapxOrdValuesMut<'a, V>
where
    V: ValueEnDe,
{
    type Item = ValueIterMut<'a, V>;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(_, v)| ValueIterMut {
            value: pnk!(<V as ValueEnDe>::decode(&v)),
            inner: v,
        })
    }
}

impl<V> DoubleEndedIterator for MapxOrdValuesMut<'_, V>
where
    V: ValueEnDe,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(_, v)| ValueIterMut {
            value: pnk!(<V as ValueEnDe>::decode(&v)),
            inner: v,
        })
    }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/// A mutable iterator over the entries of a `MapxOrd`.
pub struct MapxOrdIterMut<'a, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    inner: mapx_raw::MapxRawIterMut<'a>,
    _p: PhantomData<(K, V)>,
}

impl<'a, K, V> Iterator for MapxOrdIterMut<'a, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    type Item = (K, ValueIterMut<'a, V>);
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, v)| {
            (
                pnk!(<K as KeyEnDeOrdered>::from_bytes(k)),
                ValueIterMut {
                    value: <V as ValueEnDe>::decode(&v).unwrap(),
                    inner: v,
                },
            )
        })
    }
}

impl<K, V> DoubleEndedIterator for MapxOrdIterMut<'_, K, V>
where
    K: KeyEnDeOrdered,
    V: ValueEnDe,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(k, v)| {
            (
                pnk!(<K as KeyEnDeOrdered>::from_bytes(k)),
                ValueIterMut {
                    value: <V as ValueEnDe>::decode(&v).unwrap(),
                    inner: v,
                },
            )
        })
    }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

/// A view into a single entry in a map, which may either be vacant or occupied.
pub struct Entry<'a, V>
where
    V: ValueEnDe,
{
    /// The raw key of the entry.
    pub(crate) key: RawKey,
    /// A mutable reference to the map's header.
    pub(crate) hdr: &'a mut MapxOrdRawKey<V>,
}

impl<'a, V> Entry<'a, V>
where
    V: ValueEnDe,
{
    /// Ensures a value is in the entry by inserting the default if empty,
    /// and returns a mutable reference to the value.
    pub fn or_insert(self, default: V) -> ValueMut<'a, V> {
        crate::entry_or_insert_via_mock!(
            self,
            MapxOrdRawKey<V>,
            get_mut(&self.key),
            mock_value_mut(self.key, default)
        )
    }
}

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////