vsdb_core 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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

mod mmdb;

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

pub(crate) use self::mmdb::MmDB as Engine;

type DbIter = self::mmdb::MmdbIter;

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

use crate::common::{PREFIX_SIZE, PreBytes, RawKey, RawValue, VSDB};
use ruc::*;
use serde::{Deserialize, Serialize, de};
use std::{
    borrow::Cow,
    fmt,
    marker::PhantomData,
    ops::{Bound, Deref, DerefMut, RangeBounds},
    result::Result as StdResult,
    sync::LazyLock,
};

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

/// Trait for batch write operations
pub trait BatchTrait {
    fn insert(&mut self, key: &[u8], value: &[u8]);
    fn remove(&mut self, key: &[u8]);
    fn commit(&mut self) -> Result<()>;
}

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

#[derive(Debug)]
pub(crate) struct Mapx {
    // the unique ID of each instance
    prefix: Prefix,
}

#[derive(Debug)]
enum Prefix {
    Recovered(PreBytes),
    Created(LazyLock<PreBytes>),
}

impl Prefix {
    #[inline(always)]
    fn as_bytes(&self) -> &PreBytes {
        match self {
            Self::Recovered(bytes) => bytes,
            Self::Created(lc) => LazyLock::force(lc),
        }
    }

    #[inline(always)]
    fn to_bytes(&self) -> PreBytes {
        *self.as_bytes()
    }

    /// Force the prefix to be materialized (if lazily created)
    /// and return the bytes. Converts `Created` → `Recovered`
    /// so subsequent calls avoid re-forcing the LazyLock.
    fn materialize(&mut self) -> PreBytes {
        match self {
            Self::Recovered(bytes) => *bytes,
            Self::Created(lc) => {
                let b = *LazyLock::force(lc);
                *self = Self::Recovered(b);
                b
            }
        }
    }

    #[inline(always)]
    fn from_bytes(b: PreBytes) -> Self {
        Self::Recovered(b)
    }

    #[inline(always)]
    fn create() -> Self {
        Self::Created(LazyLock::new(|| {
            let prefix = VSDB.db.alloc_prefix();
            let prefix_bytes = prefix.to_le_bytes();
            debug_assert!(VSDB.db.iter(prefix_bytes).next().is_none());
            prefix_bytes
        }))
    }
}

impl Mapx {
    // # Safety
    //
    // This API breaks Rust's semantic safety guarantees.
    // It creates a second handle to the same underlying prefix,
    // allowing two `&mut Mapx` references to coexist. This
    // bypasses the borrow checker's exclusivity guarantee.
    //
    // Callers MUST ensure:
    // - No concurrent reads and writes to the same key.
    // - No concurrent iteration and mutation.
    // - Essentially, the caller must uphold single-writer semantics
    //   externally.
    pub(crate) unsafe fn shadow(&self) -> Self {
        Self {
            prefix: Prefix::from_bytes(self.prefix.to_bytes()),
        }
    }

    #[inline(always)]
    pub(crate) fn new() -> Self {
        Self {
            prefix: Prefix::create(),
        }
    }

    #[inline(always)]
    pub(crate) fn get(&self, key: &[u8]) -> Option<RawValue> {
        VSDB.db.get(self.prefix.to_bytes(), key)
    }

    #[inline(always)]
    pub(crate) fn get_mut(&mut self, key: &[u8]) -> Option<ValueMut<'_>> {
        let v = VSDB.db.get(self.prefix.materialize(), key)?;

        Some(ValueMut {
            key: key.to_vec(),
            value: v,
            dirty: false,
            hdr: self,
        })
    }

    #[inline(always)]
    pub(crate) fn mock_value_mut(
        &mut self,
        key: RawValue,
        value: RawValue,
    ) -> ValueMut<'_> {
        ValueMut {
            key,
            value,
            dirty: true,
            hdr: self,
        }
    }

    #[inline(always)]
    pub(crate) fn iter(&self) -> MapxIter<'_> {
        MapxIter {
            db_iter: VSDB.db.iter(self.prefix.to_bytes()),
            _marker: PhantomData,
        }
    }

    #[inline(always)]
    pub(crate) fn iter_mut(&mut self) -> MapxIterMut<'_> {
        MapxIterMut {
            db_iter: VSDB.db.iter(self.prefix.materialize()),
            hdr: self,
        }
    }

    #[inline(always)]
    pub(crate) fn range<'a, R: RangeBounds<Cow<'a, [u8]>>>(
        &'a self,
        bounds: R,
    ) -> MapxIter<'a> {
        MapxIter {
            db_iter: VSDB.db.range(self.prefix.to_bytes(), bounds),
            _marker: PhantomData,
        }
    }

    #[inline(always)]
    pub(crate) fn range_detached<'a, R: RangeBounds<Cow<'a, [u8]>>>(
        &self,
        bounds: R,
    ) -> MapxIter<'a> {
        MapxIter {
            db_iter: VSDB.db.range(self.prefix.to_bytes(), bounds),
            _marker: PhantomData,
        }
    }

    #[inline(always)]
    pub(crate) fn range_mut<'a, R: RangeBounds<Cow<'a, [u8]>>>(
        &'a mut self,
        bounds: R,
    ) -> MapxIterMut<'a> {
        MapxIterMut {
            db_iter: VSDB.db.range(self.prefix.materialize(), bounds),
            hdr: self,
        }
    }

    #[inline(always)]
    pub(crate) fn insert(&mut self, key: &[u8], value: &[u8]) {
        let prefix = self.prefix.materialize();
        VSDB.db.insert(prefix, key, value);
    }

    #[inline(always)]
    pub(crate) fn remove(&mut self, key: &[u8]) {
        let prefix = self.prefix.materialize();
        VSDB.db.remove(prefix, key);
    }

    /// Marks a key for deferred removal via compaction filter.
    #[inline(always)]
    pub(crate) fn lazy_delete(&self, key: &[u8]) {
        VSDB.db.lazy_delete(self.prefix.to_bytes(), key);
    }

    /// Batch version of [`lazy_delete`](Self::lazy_delete).
    #[inline(always)]
    pub(crate) fn lazy_delete_batch(
        &self,
        keys: impl IntoIterator<Item = impl AsRef<[u8]>>,
    ) {
        VSDB.db.lazy_delete_batch(self.prefix.to_bytes(), keys);
    }

    #[inline(always)]
    pub(crate) fn batch_begin(&mut self) -> Box<dyn BatchTrait + '_> {
        let prefix = self.prefix.materialize();
        VSDB.db.batch_begin(prefix)
    }

    #[inline(always)]
    pub(crate) fn clear(&mut self) {
        // Avoid collecting all keys into memory at once.
        // Instead, delete in chunks using repeated range scans.
        //
        // Important: we do not delete while holding an iterator alive.
        // Each loop creates a fresh iterator starting strictly after `last_key`.
        //
        // NOTE: This operation is NOT atomic. Concurrent readers (e.g.
        // via `shadow()`) may observe a partially-cleared state.
        const CLEAR_CHUNK: usize = 4096;

        let prefix = self.prefix.materialize();
        let mut last_key: Option<RawKey> = None;

        loop {
            let mut it = match &last_key {
                None => VSDB.db.iter(prefix),
                Some(k) => VSDB.db.range(
                    prefix,
                    (Bound::Excluded(Cow::Owned(k.clone())), Bound::Unbounded),
                ),
            };

            let mut keys = Vec::with_capacity(CLEAR_CHUNK);
            for _ in 0..CLEAR_CHUNK {
                let Some((k, _)) = it.next() else {
                    break;
                };
                last_key = Some(k.clone());
                keys.push(k);
            }

            // Drop the iterator before mutating the DB to avoid
            // holding a read snapshot across the batch delete.
            drop(it);

            if keys.is_empty() {
                break;
            }

            let mut batch = VSDB.db.batch_begin(prefix);
            for k in keys.iter() {
                batch.remove(k);
            }
            batch
                .commit()
                .expect("vsdb: batch delete failed during clear");
        }
    }

    #[inline(always)]
    pub(crate) unsafe fn from_prefix_slice(s: impl AsRef<[u8]>) -> Self {
        debug_assert_eq!(s.as_ref().len(), PREFIX_SIZE);
        let mut prefix = PreBytes::default();
        prefix.copy_from_slice(s.as_ref());
        Self {
            prefix: Prefix::Recovered(prefix),
        }
    }

    #[inline(always)]
    pub(crate) fn as_prefix_slice(&self) -> &PreBytes {
        self.prefix.as_bytes()
    }

    #[inline(always)]
    pub fn is_the_same_instance(&self, other_hdr: &Self) -> bool {
        self.prefix.to_bytes() == other_hdr.prefix.to_bytes()
    }
}

impl Clone for Mapx {
    fn clone(&self) -> Self {
        let mut new_instance = Self::new();
        {
            let mut batch = new_instance.batch_begin();
            for (k, v) in self.iter() {
                batch.insert(&k, &v);
            }
            batch.commit().expect("vsdb: clone failed — I/O error");
        }
        new_instance
    }
}

impl PartialEq for Mapx {
    fn eq(&self, other: &Mapx) -> bool {
        // Short-circuit: if both point to the same prefix, they are identical
        if self.prefix.to_bytes() == other.prefix.to_bytes() {
            return true;
        }

        // Compare all key-value pairs
        let mut self_iter = self.iter();
        let mut other_iter = other.iter();

        loop {
            match (self_iter.next(), other_iter.next()) {
                (Some((k1, v1)), Some((k2, v2))) => {
                    if k1 != k2 || v1 != v2 {
                        return false;
                    }
                }
                (None, None) => return true,
                _ => return false,
            }
        }
    }
}

impl Eq for Mapx {}

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

pub(crate) struct SimpleVisitor;

impl<'de> de::Visitor<'de> for SimpleVisitor {
    type Value = Vec<u8>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("bytes")
    }

    fn visit_str<E>(self, v: &str) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(v.as_bytes().to_vec())
    }

    fn visit_string<E>(self, v: String) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(v.into_bytes())
    }

    fn visit_bytes<E>(self, v: &[u8]) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(v.to_vec())
    }

    fn visit_byte_buf<E>(self, v: Vec<u8>) -> StdResult<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(v)
    }

    fn visit_seq<A>(self, mut seq: A) -> StdResult<Self::Value, A::Error>
    where
        A: de::SeqAccess<'de>,
    {
        let mut ret = vec![];
        loop {
            match seq.next_element() {
                Ok(i) => {
                    if let Some(i) = i {
                        ret.push(i);
                    } else {
                        break;
                    }
                }
                Err(e) => {
                    return Err(de::Error::custom(e));
                }
            }
        }
        Ok(ret)
    }
}

impl Serialize for Mapx {
    fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_bytes(&self.prefix.to_bytes())
    }
}

impl<'de> Deserialize<'de> for Mapx {
    fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer
            .deserialize_byte_buf(SimpleVisitor)
            .and_then(|meta| {
                if meta.len() != PREFIX_SIZE {
                    return Err(serde::de::Error::invalid_length(
                        meta.len(),
                        &"exactly 8 bytes for Mapx prefix",
                    ));
                }
                Ok(unsafe { Self::from_prefix_slice(meta) })
            })
    }
}

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

pub struct MapxIter<'a> {
    db_iter: DbIter,
    _marker: PhantomData<&'a ()>,
}

impl fmt::Debug for MapxIter<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("MapxIter").finish()
    }
}

impl Iterator for MapxIter<'_> {
    type Item = (RawKey, RawValue);
    fn next(&mut self) -> Option<Self::Item> {
        self.db_iter.next()
    }
}

impl DoubleEndedIterator for MapxIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.db_iter.next_back()
    }
}

pub struct MapxIterMut<'a> {
    db_iter: DbIter,
    hdr: &'a mut Mapx,
}

impl fmt::Debug for MapxIterMut<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("MapxIterMut").field(&self.hdr).finish()
    }
}

impl<'a> Iterator for MapxIterMut<'a> {
    type Item = (RawKey, ValueIterMut<'a>);

    fn next(&mut self) -> Option<Self::Item> {
        let (k, v) = self.db_iter.next()?;

        let vmut = ValueIterMut {
            prefix: self.hdr.prefix.to_bytes(),
            key: k.clone(),
            value: v,
            dirty: false,
            _marker: PhantomData,
        };

        Some((k, vmut))
    }
}

impl<'a> DoubleEndedIterator for MapxIterMut<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let (k, v) = self.db_iter.next_back()?;

        let vmut = ValueIterMut {
            prefix: self.hdr.prefix.to_bytes(),
            key: k.clone(),
            value: v,
            dirty: false,
            _marker: PhantomData,
        };

        Some((k, vmut))
    }
}

#[derive(Debug)]
pub struct ValueIterMut<'a> {
    prefix: PreBytes,
    key: RawKey,
    value: RawValue,
    dirty: bool,
    _marker: PhantomData<&'a mut ()>,
}

impl Drop for ValueIterMut<'_> {
    fn drop(&mut self) {
        if self.dirty {
            VSDB.db.insert(self.prefix, &self.key, &self.value);
        }
    }
}

impl Deref for ValueIterMut<'_> {
    type Target = RawValue;
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl DerefMut for ValueIterMut<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.dirty = true;
        &mut self.value
    }
}

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

#[derive(Debug)]
pub struct ValueMut<'a> {
    key: RawKey,
    value: RawValue,
    dirty: bool,
    hdr: &'a mut Mapx,
}

impl Drop for ValueMut<'_> {
    fn drop(&mut self) {
        if self.dirty {
            self.hdr.insert(&self.key[..], &self.value[..]);
        }
    }
}

impl Deref for ValueMut<'_> {
    type Target = RawValue;
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl DerefMut for ValueMut<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.dirty = true;
        &mut self.value
    }
}

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