armdb 0.12.0

sharded bitcask key-value storage optimized for NVMe
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
use crate::error::DbResult;

/// How a codec's on-disk bytes relate to generic inspection decoding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InspectionEncoding {
    /// Returned value bytes are accepted by the generic DynValue decoder for
    /// the collection's [`Typ`](armour_core::Typ).
    ///
    /// This does **not** promise that `rapira::deserialize::<ConcreteType>`
    /// succeeds. Compatible Zero layouts may not implement `Rapira` at all,
    /// and DynValue decoding intentionally differs from typed Rapira for some
    /// values (for example non-finite floats).
    ///
    /// ```no_run
    /// # fn demo(
    /// #     typ: &armour_core::Typ,
    /// #     value_bytes: &[u8],
    /// # ) -> Result<(), armour_core::dyn_value::DecodeError> {
    /// let value = armour_core::dyn_value::decode(typ, value_bytes)?;
    /// let _ = value;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// For the full Inspector lookup + decode flow, see the [`armour`](crate::armour)
    /// module docs (requires the `armour` feature).
    Rapira,
    /// Contiguous raw memory image of the logical type.
    ///
    /// Used when the collection does not promise DynValue compatibility —
    /// including Zero layouts whose computed `Typ` width differs from the
    /// stored value width, unsupported / variable `Typ` shapes, or non
    /// little-endian targets.
    RawLayout,
    /// No generic decoder contract is declared.
    Opaque,
}

/// Codec for encoding/decoding typed values to/from bytes.
///
/// Implemented as zero-sized marker structs for zero runtime overhead.
/// Used by [`TypedTree`](crate::TypedTree) for disk serialization.
pub trait Codec<T>: Send + Sync {
    /// Declares how inspection should interpret encoded bytes for this codec.
    const INSPECTION_ENCODING: InspectionEncoding = InspectionEncoding::Opaque;

    /// Encode `value` into `buf`. Implementations must clear `buf` before writing —
    /// the caller may pass a reusable buffer.
    fn encode_to(&self, value: &T, buf: &mut Vec<u8>) -> DbResult<()>;
    fn decode_from(&self, bytes: &[u8]) -> DbResult<T>;
    /// Encoded byte size of `value`. Default: encode into a throwaway buffer
    /// and return the resulting length. Specialize for cheap-size codecs.
    ///
    /// **The default swallows an encode error**: on `Err` it returns the length
    /// of whatever was written before the failure (often `0`), because the
    /// signature is infallible. Callers use this only as a sizing hint — the
    /// authoritative encode is [`encode_to`](Self::encode_to), which does return
    /// the error. A codec whose `encode_to` can fail should override `size` with
    /// a computation that cannot.
    fn size(&self, value: &T) -> usize {
        let mut buf = Vec::new();
        let _ = self.encode_to(value, &mut buf);
        buf.len()
    }
    /// Encode `value` into a fresh `Vec`. Convenience over [`encode_to`](Self::encode_to)
    /// for call sites with no buffer to reuse.
    fn encode(&self, value: &T) -> DbResult<Vec<u8>> {
        let mut buf = Vec::new();
        self.encode_to(value, &mut buf)?;
        Ok(buf)
    }
}

#[cfg(feature = "rapira-codec")]
#[derive(Default, Clone, Debug)]
pub struct RapiraCodec;

#[cfg(feature = "rapira-codec")]
impl<T: rapira::Rapira> Codec<T> for RapiraCodec {
    const INSPECTION_ENCODING: InspectionEncoding = InspectionEncoding::Rapira;

    fn encode_to(&self, value: &T, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        rapira::extend_vec(value, buf);
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<T> {
        rapira::deserialize(bytes).map_err(|_| crate::error::DbError::CorruptedEntry { offset: 0 })
    }

    fn size(&self, value: &T) -> usize {
        rapira::Rapira::size(value)
    }
}

#[cfg(feature = "bitcode-codec")]
#[derive(Default, Clone, Debug)]
pub struct BitcodeCodec;

#[cfg(feature = "bitcode-codec")]
impl<T: bitcode::Encode + for<'a> bitcode::Decode<'a>> Codec<T> for BitcodeCodec {
    fn encode_to(&self, value: &T, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        buf.extend_from_slice(&bitcode::encode(value));
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<T> {
        bitcode::decode(bytes).map_err(|_| crate::error::DbError::CorruptedEntry { offset: 0 })
    }
}

/// Codec using [postcard](https://docs.rs/postcard) — compact binary serde format
/// with varint encoding. Good JS/TS interop via `postcard-js` npm package.
#[cfg(feature = "postcard-codec")]
#[derive(Default, Clone, Debug)]
pub struct PostcardCodec;

#[cfg(feature = "postcard-codec")]
impl<T: serde::Serialize + for<'a> serde::Deserialize<'a>> Codec<T> for PostcardCodec {
    fn encode_to(&self, value: &T, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        let encoded = postcard::to_allocvec(value)
            .map_err(|_| crate::error::DbError::Client("postcard serialization failed"))?;
        buf.extend_from_slice(&encoded);
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<T> {
        postcard::from_bytes(bytes).map_err(|_| crate::error::DbError::CorruptedEntry { offset: 0 })
    }
}

/// Codec for `T: IntoBytes + FromBytes` — fixed-size values via zerocopy.
///
/// Zero-cost conversion via `zerocopy::IntoBytes::as_bytes` / `FromBytes::read_from_bytes`.
/// Unlike [`BytemuckCodec`], does not require `bytemuck` — uses the always-available
/// `zerocopy` crate.
#[derive(Default, Clone, Debug)]
pub struct ZerocopyCodec;

impl<T> Codec<T> for ZerocopyCodec
where
    T: zerocopy::IntoBytes + zerocopy::FromBytes + zerocopy::Immutable,
{
    const INSPECTION_ENCODING: InspectionEncoding = InspectionEncoding::RawLayout;

    fn encode_to(&self, value: &T, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        buf.extend_from_slice(zerocopy::IntoBytes::as_bytes(value));
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<T> {
        zerocopy::FromBytes::read_from_bytes(bytes)
            .map_err(|_| crate::error::DbError::CorruptedEntry { offset: 0 })
    }

    fn size(&self, _value: &T) -> usize {
        size_of::<T>()
    }
}

/// Codec for `T: bytemuck::Pod` — fixed-size values cast as raw bytes.
///
/// Zero-cost conversion via `bytemuck::bytes_of` / `try_from_bytes`.
/// For variable-length vectors use [`BytemuckSliceCodec`] instead.
#[cfg(feature = "bytemuck-codec")]
#[derive(Default, Clone, Debug)]
pub struct BytemuckCodec;

#[cfg(feature = "bytemuck-codec")]
impl<T: bytemuck::Pod> Codec<T> for BytemuckCodec {
    const INSPECTION_ENCODING: InspectionEncoding = InspectionEncoding::RawLayout;

    fn encode_to(&self, value: &T, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        buf.extend_from_slice(bytemuck::bytes_of(value));
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<T> {
        if bytes.len() != size_of::<T>() {
            return Err(crate::error::DbError::CorruptedEntry { offset: 0 });
        }
        Ok(bytemuck::pod_read_unaligned(bytes))
    }

    fn size(&self, _value: &T) -> usize {
        size_of::<T>()
    }
}

/// Codec for `Vec<T>` where `T: bytemuck::Pod` — variable-length vector
/// serialized as contiguous raw bytes via `bytemuck::cast_slice`.
///
/// Matches the pattern from `bytemuck_slice_record!` in the `armour` crate.
///
/// ```ignore
/// let tree = TypedTree::<16, Vec<u64>, BytemuckSliceCodec>::open(config, BytemuckSliceCodec)?;
/// tree.put(&key, vec![1u64, 2, 3])?;
/// ```
#[cfg(feature = "bytemuck-codec")]
#[derive(Default, Clone, Debug)]
pub struct BytemuckSliceCodec;

#[cfg(feature = "bytemuck-codec")]
impl<W: BytemuckVec> Codec<W> for BytemuckSliceCodec {
    const INSPECTION_ENCODING: InspectionEncoding = InspectionEncoding::RawLayout;

    fn encode_to(&self, value: &W, buf: &mut Vec<u8>) -> DbResult<()> {
        buf.clear();
        buf.extend_from_slice(bytemuck::cast_slice(value.as_slice()));
        Ok(())
    }

    fn decode_from(&self, bytes: &[u8]) -> DbResult<W> {
        let item_size = size_of::<W::Item>();
        if item_size == 0 {
            return Ok(W::from_vec(Vec::new()));
        }
        if !bytes.is_empty() && !bytes.len().is_multiple_of(item_size) {
            return Err(crate::error::DbError::CorruptedEntry { offset: 0 });
        }
        let vec: Vec<W::Item> = bytes
            .chunks_exact(item_size)
            .map(bytemuck::pod_read_unaligned)
            .collect();
        Ok(W::from_vec(vec))
    }

    fn size(&self, value: &W) -> usize {
        std::mem::size_of_val(value.as_slice())
    }
}

/// Trait for types that can be encoded/decoded as a contiguous slice of `Pod` elements.
///
/// Implemented automatically for `Vec<T: Pod>`. For newtype wrappers over `Vec<T>`,
/// implement this trait to use [`BytemuckSliceCodec`] directly:
///
/// ```ignore
/// #[derive(From, AsRef)]
/// #[repr(transparent)]
/// pub struct PostLikes(pub Vec<UserID>);
///
/// impl BytemuckVec for PostLikes {
///     type Item = UserID;
///     fn from_vec(v: Vec<UserID>) -> Self { Self(v) }
///     fn as_slice(&self) -> &[UserID] { &self.0 }
/// }
///
/// let map = db.open_typed_map::<PostLikes, BytemuckSliceCodec>(...)?;
/// ```
#[cfg(feature = "bytemuck-codec")]
pub trait BytemuckVec: Send + Sync + Sized {
    type Item: bytemuck::Pod;
    fn from_vec(v: Vec<Self::Item>) -> Self;
    fn as_slice(&self) -> &[Self::Item];
}

#[cfg(feature = "bytemuck-codec")]
impl<T: bytemuck::Pod + Send + Sync> BytemuckVec for Vec<T> {
    type Item = T;
    fn from_vec(v: Vec<T>) -> Self {
        v
    }
    fn as_slice(&self) -> &[T] {
        self
    }
}

#[cfg(test)]
mod inspection_encoding_tests {
    use super::*;
    use crate::error::DbError;

    #[derive(Clone)]
    struct UndeclaredCodec;

    impl Codec<u8> for UndeclaredCodec {
        fn encode_to(&self, value: &u8, buf: &mut Vec<u8>) -> DbResult<()> {
            buf.clear();
            buf.push(*value);
            Ok(())
        }

        fn decode_from(&self, bytes: &[u8]) -> DbResult<u8> {
            bytes
                .first()
                .copied()
                .ok_or(DbError::CorruptedEntry { offset: 0 })
        }
    }

    #[test]
    fn inspection_encoding_defaults_to_opaque() {
        assert_eq!(
            <UndeclaredCodec as Codec<u8>>::INSPECTION_ENCODING,
            InspectionEncoding::Opaque,
        );
    }

    #[cfg(feature = "rapira-codec")]
    #[test]
    fn rapira_codec_declares_rapira() {
        assert_eq!(
            <RapiraCodec as Codec<u64>>::INSPECTION_ENCODING,
            InspectionEncoding::Rapira,
        );
    }

    #[test]
    fn zerocopy_codec_declares_raw_layout() {
        assert_eq!(
            <ZerocopyCodec as Codec<u64>>::INSPECTION_ENCODING,
            InspectionEncoding::RawLayout,
        );
    }

    #[cfg(feature = "bytemuck-codec")]
    #[test]
    fn bytemuck_codec_declares_raw_layout() {
        assert_eq!(
            <BytemuckCodec as Codec<u64>>::INSPECTION_ENCODING,
            InspectionEncoding::RawLayout,
        );
    }

    #[cfg(feature = "bytemuck-codec")]
    #[test]
    fn bytemuck_slice_codec_declares_raw_layout() {
        assert_eq!(
            <BytemuckSliceCodec as Codec<Vec<u64>>>::INSPECTION_ENCODING,
            InspectionEncoding::RawLayout,
        );
    }

    #[cfg(feature = "bitcode-codec")]
    #[test]
    fn bitcode_codec_declares_opaque() {
        assert_eq!(
            <BitcodeCodec as Codec<u64>>::INSPECTION_ENCODING,
            InspectionEncoding::Opaque,
        );
    }

    #[cfg(feature = "postcard-codec")]
    #[test]
    fn postcard_codec_declares_opaque() {
        assert_eq!(
            <PostcardCodec as Codec<u64>>::INSPECTION_ENCODING,
            InspectionEncoding::Opaque,
        );
    }
}

#[cfg(test)]
mod size_tests {
    use super::*;

    #[test]
    fn zerocopy_size_is_constant() {
        let c = ZerocopyCodec;
        let v: u64 = 42;
        assert_eq!(<ZerocopyCodec as Codec<u64>>::size(&c, &v), 8);
    }

    #[cfg(feature = "rapira-codec")]
    #[test]
    fn rapira_size_matches_encode_len() {
        let c = RapiraCodec;
        let v: Vec<u8> = vec![1, 2, 3, 4, 5];
        let mut buf = Vec::new();
        c.encode_to(&v, &mut buf).unwrap();
        assert_eq!(<RapiraCodec as Codec<Vec<u8>>>::size(&c, &v), buf.len());
    }

    #[cfg(feature = "rapira-codec")]
    #[test]
    fn encode_matches_encode_to() {
        let c = RapiraCodec;
        let v: Vec<u8> = vec![1, 2, 3, 4, 5];
        let mut buf = Vec::new();
        c.encode_to(&v, &mut buf).unwrap();
        assert_eq!(Codec::<Vec<u8>>::encode(&c, &v).unwrap(), buf);
    }

    #[cfg(feature = "bytemuck-codec")]
    #[test]
    fn bytemuck_size_is_constant() {
        let c = BytemuckCodec;
        let v: [u8; 16] = [0; 16];
        assert_eq!(<BytemuckCodec as Codec<[u8; 16]>>::size(&c, &v), 16);
    }

    #[cfg(feature = "bytemuck-codec")]
    #[test]
    fn bytemuck_slice_size_matches() {
        let c = BytemuckSliceCodec;
        let v: Vec<u32> = vec![1, 2, 3, 4];
        let mut buf = Vec::new();
        c.encode_to(&v, &mut buf).unwrap();
        assert_eq!(
            <BytemuckSliceCodec as Codec<Vec<u32>>>::size(&c, &v),
            buf.len()
        );
    }

    // WP-I: checked decode must reject schema-drifted / hostile bytes with
    // Err(CorruptedEntry) instead of UB or OOM.
    #[cfg(feature = "rapira-codec")]
    #[test]
    fn rapira_decode_rejects_invalid_utf8() {
        let c = RapiraCodec;
        // u32 LE length = 2, followed by two bytes that are not valid UTF-8.
        let bad_utf8: &[u8] = &[2, 0, 0, 0, 0xFF, 0xFE];
        let res: DbResult<String> = c.decode_from(bad_utf8);
        assert!(
            matches!(res, Err(crate::error::DbError::CorruptedEntry { .. })),
            "invalid UTF-8 must surface as CorruptedEntry, got {res:?}"
        );
    }

    #[cfg(feature = "rapira-codec")]
    #[test]
    fn rapira_decode_rejects_zero_nonzero() {
        let c = RapiraCodec;
        // NonZeroU32 of value 0 — impossible under a checked decode (UB otherwise).
        let zero: &[u8] = &[0, 0, 0, 0];
        let res: DbResult<std::num::NonZeroU32> = c.decode_from(zero);
        assert!(
            matches!(res, Err(crate::error::DbError::CorruptedEntry { .. })),
            "zero NonZeroU32 must surface as CorruptedEntry, got {res:?}"
        );
    }

    #[cfg(feature = "rapira-codec")]
    #[test]
    fn rapira_decode_rejects_oversized_capacity() {
        let c = RapiraCodec;
        // u32 LE length = u32::MAX — far above VEC_MAX_CAP (512 * 1024). `Vec<u32>`
        // uses the generic Vec<T> rapira impl, which rejects with MaxCapacity BEFORE
        // any Vec::with_capacity. DO NOT run under the old unchecked codec — its
        // generic unchecked path would Vec::<u32>::with_capacity(u32::MAX) and abort.
        // (`Vec<u8>` would NOT exercise this — it has a specialized bytes impl that
        // only bounds-checks, no with_capacity — so the type here must be a non-byte Vec.)
        let huge_len: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
        let res: DbResult<Vec<u32>> = c.decode_from(huge_len);
        assert!(
            matches!(res, Err(crate::error::DbError::CorruptedEntry { .. })),
            "oversized collection length must surface as CorruptedEntry, got {res:?}"
        );
    }
}