vsdb 16.3.6

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
//!
//! A `HashMap`-like structure that stores data on disk.
//!
//! `Mapx` provides a key-value store where both keys and values are encoded
//! using `serde`-like methods before being persisted. This allows for storing
//! complex data types while maintaining a familiar `HashMap` interface.
//!
//! # Examples
//!
//! ```
//! use vsdb::{Mapx, 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: Mapx<i32, String> = Mapx::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::{Entry, MapxOrdValues, MapxOrdValuesMut},
        mapx_ord_rawkey::{
            self, MapxOrdRawKey, MapxOrdRawKeyBatchEntry, MapxOrdRawKeyIter,
            MapxOrdRawKeyIterMut, ValueMut,
        },
    },
    common::{
        ende::{KeyEnDe, ValueEnDe},
        error::Result,
        macros::define_map_wrapper,
    },
};
use std::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

define_map_wrapper! {
    #[doc = "A disk-based, `HashMap`-like data structure with typed keys and values."]
    #[doc = ""]
    #[doc = "`Mapx` stores key-value pairs on disk, encoding both keys and values"]
    #[doc = "for type safety and persistence."]
    #[doc = ""]
    #[doc = "# Key determinism"]
    #[doc = ""]
    #[doc = "`K` must encode deterministically. Do not use `HashMap`, `HashSet`,"]
    #[doc = "or wrappers containing them as keys; their randomized iteration order"]
    #[doc = "can produce different storage bytes for logically equal keys."]
    pub struct Mapx<K, V> {
        inner: MapxOrdRawKey<V>,
        _p: PhantomData<K>,
    }
    where K: KeyEnDe, V: ValueEnDe
}

impl<K, V> Mapx<K, V>
where
    K: KeyEnDe,
    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.encode())
    }

    /// 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.encode())
    }

    /// 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.encode())
    }

    /// 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.encode(), 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.encode(),
            hdr: &mut self.inner,
        }
    }

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

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

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

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

    /// 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.encode())
    }

    /// Start a batch operation.
    ///
    /// This method allows you to perform multiple insert/remove operations
    /// and commit them atomically.
    ///
    /// A failed [`commit`](vsdb_core::common::BatchTrait::commit) consumes
    /// the buffered operations (none are applied) and is not retryable —
    /// re-stage the operations on a fresh batch instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use vsdb::{Mapx, vsdb_set_base_dir};
    ///
    /// vsdb_set_base_dir("/tmp/vsdb_mapx_batch_entry").unwrap();
    /// let mut map = Mapx::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) -> MapxBatchEntry<'_, K, V> {
        MapxBatchEntry {
            inner: self.inner.batch_entry(),
            _marker: PhantomData,
        }
    }

    /// Returns an iterator over the map's keys.
    ///
    /// Decodes only `K` — unlike `iter().map(|(k, _)| k)`, the value
    /// bytes are never decoded and discarded (see
    /// `MapxOrdRawKey::keys`'s doc comment for why this matters for
    /// nested-VSDB-collection value types).
    #[inline(always)]
    pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
        self.inner.keys().map(|k| K::decode(&k).unwrap())
    }
}

impl<'a, K, V> IntoIterator for &'a Mapx<K, V>
where
    K: KeyEnDe,
    V: ValueEnDe,
{
    type Item = (K, V);
    type IntoIter = MapxIter<'a, K, V>;

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

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

// Hand-written rather than `#[derive(PartialEq, Eq)]`: a derive would
// compare the *encoded* bytes of both `K` and `V` (postcard encoding is
// not injective on decoded value in general — e.g. `0.0_f64` and
// `-0.0_f64` encode to different bytes despite comparing equal, while
// distinct NaN bit patterns can compare unequal despite identical
// bytes), silently diverging from `K`/`V`'s own logical `PartialEq`.
// Comparing through `self.inner` (raw key bytes + *decoded* `V`)
// side-steps needing `K: PartialEq` at all — `K`'s encoding is already
// required to be deterministic and injective for the map's basic
// correctness, so byte-identical keys are logically identical keys —
// while still fixing the decoded-value comparison for `V`.
impl<K, V> PartialEq for Mapx<K, V>
where
    K: KeyEnDe,
    V: ValueEnDe + PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner.iter().eq(other.inner.iter())
    }
}

impl<K, V> Eq for Mapx<K, V>
where
    K: KeyEnDe,
    V: ValueEnDe + Eq,
{
}

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

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

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

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

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

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

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

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

/// An iterator over the entries of a `Mapx`.
pub struct MapxIter<'a, K, V>
where
    K: KeyEnDe,
    V: ValueEnDe,
{
    iter: MapxOrdRawKeyIter<'a, V>,
    _p: PhantomData<K>,
}

impl<K, V> Iterator for MapxIter<'_, K, V>
where
    K: KeyEnDe,
    V: ValueEnDe,
{
    type Item = (K, V);
    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|(k, v)| (<K as KeyEnDe>::decode(&k).unwrap(), v))
    }
}

impl<K, V> DoubleEndedIterator for MapxIter<'_, K, V>
where
    K: KeyEnDe,
    V: ValueEnDe,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter
            .next_back()
            .map(|(k, v)| (<K as KeyEnDe>::decode(&k).unwrap(), v))
    }
}

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

/// A mutable iterator over the entries of a `Mapx`.
pub struct MapxIterMut<'a, K, V>
where
    K: KeyEnDe,
    V: ValueEnDe,
{
    inner: MapxOrdRawKeyIterMut<'a, V>,
    _p: PhantomData<K>,
}

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

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

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

type MapxValues<'a, V> = MapxOrdValues<'a, V>;
type MapxValuesMut<'a, V> = MapxOrdValuesMut<'a, V>;

/// A mutable reference to a value in a `Mapx` iterator.
#[derive(Debug)]
pub struct ValueIterMut<'a, V>
where
    V: ValueEnDe,
{
    /// The inner mutable reference to the value.
    pub(crate) inner: mapx_ord_rawkey::ValueIterMut<'a, V>,
}

impl<V> Deref for ValueIterMut<'_, V>
where
    V: ValueEnDe,
{
    type Target = V;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<V> DerefMut for ValueIterMut<'_, V>
where
    V: ValueEnDe,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}