cesiumdb 0.1.0

Blazing fast, persistent key-value store for Rust
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
// Copyright (c) Sienna Satterwhite, CesiumDB Contributors
// SPDX-License-Identifier: GPL-3.0-only WITH Classpath-exception-2.0

use std::{
    cmp::{
        Ordering,
        Reverse,
    },
    collections::Bound,
    fmt::Debug,
};

use bytes::{
    BufMut,
    Bytes,
    BytesMut,
};
use crc32fast::Hasher;
use tracing::instrument;

use crate::utils::{
    Deserializer,
    Serializer,
};

pub const DEFAULT_NS: u64 = 0;

#[instrument]
pub fn map_key_bound(bound: Bound<KeyBytes>) -> Bound<Bytes> {
    match bound {
        | Bound::Included(x) => {
            let mem_key = x.serialize();
            Bound::Included(mem_key)
        },
        | Bound::Excluded(x) => {
            let mem_key = x.serialize();
            Bound::Excluded(mem_key)
        },
        | Bound::Unbounded => Bound::Unbounded,
    }
}

#[derive(Debug, Eq, Clone, Copy, PartialEq)]
pub struct Key<T: AsRef<[u8]>> {
    /// namespace
    ns: u64,
    /// the actual key
    key: T,
    /// timestamp
    ts: u128,
}

pub type KeyBytes = Key<Bytes>;

impl Key<Bytes> {
    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn new(ns: u64, key: Bytes, ts: u128) -> Self {
        Key { ns, key, ts }
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn set_key(&mut self, val: Bytes) {
        self.key = val;
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn key(&self) -> &Bytes {
        &self.key
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn key_len(&self) -> usize {
        self.key.as_ref().len()
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn raw_len(&self) -> usize {
        self.key.as_ref().len() + size_of::<u64>() + size_of::<u128>()
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn is_empty(&self) -> bool {
        self.key.as_ref().is_empty()
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn set_ts(&mut self, ts: u128) {
        self.ts = ts;
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn ts(&self) -> u128 {
        self.ts
    }

    /// Returns true if this is a "latest" pointer key (timestamp inverts to 0)
    pub fn is_pointer_key(&self) -> bool {
        self.ts == 0
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn set_ns(&mut self, ns: u64) {
        self.ns = ns;
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn ns(&self) -> u64 {
        self.ns
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn as_bytes(&self) -> Bytes {
        self.key.clone()
    }

    #[instrument(level = "trace")]
    #[inline]
    pub fn serialize_for_latest(&self) -> Bytes {
        // Directly serialize with u128::MAX as timestamp instead of wastefully
        // serializing, copying the entire buffer, and modifying 16 bytes
        let mut bytes =
            BytesMut::with_capacity(size_of::<u64>() + self.key.as_ref().len() + size_of::<u128>());

        bytes.put_u64_le(self.ns);
        bytes.put_slice(self.key.as_ref());
        // IMPORTANT: Use big-endian so lexicographic byte comparison gives correct
        // ordering
        bytes.put_u128(u128::MAX); // "latest" marker

        bytes.freeze()
    }
}

impl Serializer for Key<Bytes> {
    #[instrument(level = "trace")]
    #[inline]
    fn serialize(&self) -> Bytes {
        let mut bytes =
            BytesMut::with_capacity(size_of::<u64>() + self.key.as_ref().len() + size_of::<u128>());

        // this is the serialized key
        bytes.put_u64_le(self.ns);
        bytes.put_slice(self.key.as_ref());
        // IMPORTANT: Use big-endian so lexicographic byte comparison gives correct
        // ordering
        bytes.put_u128(u128::MAX - self.ts);

        bytes.freeze()
    }
}

impl Deserializer for Key<Bytes> {
    #[instrument(level = "trace")]
    #[inline]
    fn deserialize(slice: Bytes) -> Self {
        let mut ns_arr = [0u8; 8];
        ns_arr.copy_from_slice(&slice[0..8]);

        let mut ts_arr = [0u8; 16];
        ts_arr.copy_from_slice(&slice[slice.len() - 16..]);

        KeyBytes {
            ns: u64::from_le_bytes(ns_arr),
            key: Bytes::copy_from_slice(&slice[8..slice.len() - 16]),
            // IMPORTANT: Use big-endian to match serialization
            ts: u128::MAX - u128::from_be_bytes(ts_arr),
        }
    }
}

impl<T: AsRef<[u8]>> AsRef<[u8]> for Key<T> {
    fn as_ref(&self) -> &[u8] {
        self.key.as_ref()
    }
}

impl Default for Key<Bytes> {
    fn default() -> Self {
        KeyBytes {
            ns: 0,
            key: Bytes::default(),
            ts: 0,
        }
    }
}

impl<T: AsRef<[u8]> + PartialOrd> PartialOrd for Key<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (self.ns, self.key.as_ref(), Reverse(self.ts)).partial_cmp(&(
            other.ns,
            other.key.as_ref(),
            Reverse(other.ts),
        ))
    }
}

impl<T: AsRef<[u8]> + Ord> Ord for Key<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.ns, self.key.as_ref(), Reverse(self.ts)).cmp(&(
            other.ns,
            other.key.as_ref(),
            Reverse(other.ts),
        ))
    }
}

impl Key<Bytes> {
    /// SIMD-optimized comparison for merge operations
    ///
    /// Uses SIMD instructions to accelerate key comparison when available.
    /// Falls back to standard comparison for small keys.
    #[inline]
    pub fn simd_cmp(&self, other: &Self) -> Ordering {
        // Must match the standard Ord implementation exactly
        // Standard: (self.ns, self.key.as_ref(), Reverse(self.ts))
        self.ns
            .cmp(&other.ns)
            .then_with(|| {
                // Use SIMD for key bytes comparison
                crate::simd::simd_compare_keys(self.key.as_ref(), other.key.as_ref())
            })
            .then_with(|| {
                // Reverse comparison for timestamp (like Reverse(self.ts))
                other.ts.cmp(&self.ts)
            })
    }
}

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

    #[test]
    fn test_simd_cmp_matches_ord() {
        use rand::Rng;
        let mut rng = rand::rng();

        for _ in 0..100 {
            let ns1 = rng.random();
            let ns2 = rng.random();
            let ts1 = rng.random();
            let ts2 = rng.random();

            let len = rng.random_range(1..64);
            let mut key1_bytes = vec![0u8; len];
            let mut key2_bytes = vec![0u8; len];
            rng.fill(&mut key1_bytes[..]);
            rng.fill(&mut key2_bytes[..]);

            let key1 = KeyBytes::new(ns1, Bytes::from(key1_bytes), ts1);
            let key2 = KeyBytes::new(ns2, Bytes::from(key2_bytes), ts2);

            let simd_result = key1.simd_cmp(&key2);
            let ord_result = key1.cmp(&key2);

            assert_eq!(
                simd_result, ord_result,
                "SIMD and Ord mismatch for ns1={}, ns2={}, ts1={}, ts2={}",
                ns1, ns2, ts1, ts2
            );
        }
    }
}

impl From<Bytes> for Key<Bytes> {
    fn from(val: Bytes) -> Self {
        let mut ns_arr = [0u8; 8];
        ns_arr.copy_from_slice(&val[0..8]);

        let mut ts_arr = [0u8; 16];
        ts_arr.copy_from_slice(&val[val.len() - 16..]);

        Key {
            ns: u64::from_le_bytes(ns_arr),
            key: Bytes::copy_from_slice(&val[16..val.len() - 8]),
            // IMPORTANT: Use big-endian to match serialization
            ts: u128::MAX - u128::from_be_bytes(ts_arr),
        }
    }
}

#[derive(Debug, Eq, Clone, Copy, PartialEq)]
pub struct Value<T: AsRef<[u8]>> {
    pub ns: u64,
    pub value: T,
    pub tombstone: bool,
}

pub type ValueBytes = Value<Bytes>;

impl ValueBytes {
    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn new(ns: u64, val: Bytes) -> Self {
        ValueBytes {
            ns,
            value: val,
            tombstone: false,
        }
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn new_tombstone(ns: u64) -> Self {
        ValueBytes {
            ns,
            value: Bytes::new(),
            tombstone: true,
        }
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn is_tombstone(&self) -> bool {
        self.tombstone
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn set_ns(&mut self, ns: u64) {
        self.ns = ns
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn ns(&self) -> u64 {
        self.ns
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn from_slice(ns: u64, slice: &[u8]) -> Self {
        ValueBytes {
            ns,
            value: Bytes::copy_from_slice(slice),
            tombstone: false,
        }
    }

    #[instrument(level = "trace")]
    pub fn deserialize(bytes: Bytes) -> Self {
        let mut ns_arr = [0u8; 8];
        ns_arr.copy_from_slice(&bytes[0..8]);

        let tombstone = bytes[8] != 0;

        ValueBytes {
            ns: u64::from_le_bytes(ns_arr),
            tombstone,
            value: Bytes::copy_from_slice(&bytes[9..]),
        }
    }

    #[instrument(level = "trace")]
    #[inline]
    pub fn serialize(&self) -> Bytes {
        // namespace + tombstone flag + payload
        let len = size_of::<u64>() + size_of::<u8>() + self.value.as_ref().len();

        let mut buf = BytesMut::with_capacity(len);
        buf.put_u64_le(self.ns);
        buf.put_u8(if self.tombstone { 1 } else { 0 });
        buf.put_slice(self.value.as_ref());

        buf.freeze()
    }

    #[cfg_attr(feature = "telemetry", tracing::instrument(skip_all, level = "debug"))]
    pub fn as_bytes(&self) -> Bytes {
        self.value.clone()
    }
}

impl AsRef<[u8]> for ValueBytes {
    fn as_ref(&self) -> &[u8] {
        self.value.as_ref()
    }
}

impl Default for ValueBytes {
    fn default() -> Self {
        ValueBytes {
            ns: 0,
            value: Bytes::default(),
            tombstone: false,
        }
    }
}

impl<T: AsRef<[u8]> + PartialOrd> PartialOrd for Value<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (self.ns, self.value.as_ref()).partial_cmp(&(other.ns, other.value.as_ref()))
    }
}

impl<T: AsRef<[u8]> + Ord> Ord for Value<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.ns, self.value.as_ref()).cmp(&(other.ns, other.value.as_ref()))
    }
}

impl From<Bytes> for Value<Bytes> {
    fn from(val: Bytes) -> Self {
        let mut ns_arr = [0u8; 8];
        ns_arr.copy_from_slice(&val[0..8]);

        let tombstone = val[8] != 0;

        Value {
            ns: u64::from_le_bytes(ns_arr),
            tombstone,
            value: Bytes::copy_from_slice(&val[9..]),
        }
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;

    use crate::{
        keypair::{
            KeyBytes,
            ValueBytes,
        },
        utils::{
            Deserializer,
            Serializer,
        },
    };

    #[test]
    fn test_key_serialization() {
        let key = KeyBytes {
            ns: 0,
            key: Bytes::from("test"),
            ts: 0,
        };
        let memory_serialized = key.serialize();

        // 8 + 4 + 16
        // ns + payload + ts
        assert_eq!(memory_serialized.clone().len(), 28);

        let de_key = KeyBytes::deserialize(memory_serialized.clone());
        assert_eq!(key, de_key);

        let mut latest_key = de_key.clone();
        latest_key.set_ts(1234456773567);
        let latest_serialized = latest_key.serialize_for_latest();

        assert_eq!(
            memory_serialized.clone(),
            latest_serialized.clone(),
            "latest & original key must be the same"
        );
    }

    #[test]
    fn test_value_serialization() {
        let val = ValueBytes::new(0, Bytes::from("test-value"));
        let serialized = val.serialize();
        // namespace (8) + tombstone flag (1) + value (10) = 19
        assert_eq!(serialized.len(), 19);

        let de_val = ValueBytes::deserialize(serialized);
        assert_eq!(val, de_val);
    }

    #[test]
    fn test_key_ordering_by_namespace() {
        let key1 = KeyBytes::new(0, Bytes::from("key"), 100);
        let key2 = KeyBytes::new(1, Bytes::from("key"), 100);

        assert!(key1 < key2, "keys should be ordered by namespace first");
    }

    #[test]
    fn test_key_ordering_by_key_bytes() {
        let key1 = KeyBytes::new(0, Bytes::from("aaa"), 100);
        let key2 = KeyBytes::new(0, Bytes::from("bbb"), 100);

        assert!(
            key1 < key2,
            "keys in same namespace should be ordered by key bytes"
        );
    }

    #[test]
    fn test_key_ordering_by_timestamp() {
        let key1 = KeyBytes::new(0, Bytes::from("key"), 200);
        let key2 = KeyBytes::new(0, Bytes::from("key"), 100);

        // with same ns and key, newer timestamp (200) should come first (Reverse
        // ordering)
        assert!(
            key1 < key2,
            "keys with same ns and key should be ordered by timestamp in reverse"
        );
    }

    #[test]
    fn test_key_ordering_complex() {
        // test full ordering: ns, then key, then reverse timestamp
        let mut keys = vec![
            KeyBytes::new(1, Bytes::from("zzz"), 100),
            KeyBytes::new(0, Bytes::from("bbb"), 100),
            KeyBytes::new(0, Bytes::from("aaa"), 200),
            KeyBytes::new(0, Bytes::from("aaa"), 100),
            KeyBytes::new(1, Bytes::from("aaa"), 100),
        ];

        keys.sort();

        // expected order:
        // (0, aaa, 200) - ns=0, key=aaa, newest timestamp
        // (0, aaa, 100) - ns=0, key=aaa, older timestamp
        // (0, bbb, 100) - ns=0, key=bbb
        // (1, aaa, 100) - ns=1, key=aaa
        // (1, zzz, 100) - ns=1, key=zzz

        assert_eq!(keys[0].ns(), 0);
        assert_eq!(keys[0].as_bytes(), Bytes::from("aaa"));
        assert_eq!(keys[0].ts(), 200);

        assert_eq!(keys[1].ns(), 0);
        assert_eq!(keys[1].as_bytes(), Bytes::from("aaa"));
        assert_eq!(keys[1].ts(), 100);

        assert_eq!(keys[2].ns(), 0);
        assert_eq!(keys[2].as_bytes(), Bytes::from("bbb"));

        assert_eq!(keys[3].ns(), 1);
        assert_eq!(keys[3].as_bytes(), Bytes::from("aaa"));

        assert_eq!(keys[4].ns(), 1);
        assert_eq!(keys[4].as_bytes(), Bytes::from("zzz"));
    }

    #[test]
    fn test_key_empty() {
        let key = KeyBytes::new(0, Bytes::new(), 0);
        assert!(key.is_empty());
        assert_eq!(key.key_len(), 0);

        let serialized = key.serialize();
        let deserialized = KeyBytes::deserialize(serialized);
        assert!(deserialized.is_empty());
    }

    #[test]
    fn test_key_large() {
        let large_key = vec![b'k'; 10000];
        let key = KeyBytes::new(0, Bytes::from(large_key.clone()), 999999);

        assert_eq!(key.key_len(), 10000);
        assert_eq!(key.raw_len(), 10000 + size_of::<u64>() + size_of::<u128>());

        let serialized = key.serialize();
        let deserialized = KeyBytes::deserialize(serialized);

        assert_eq!(deserialized.key_len(), 10000);
        assert_eq!(deserialized.as_bytes().len(), 10000);
    }

    #[test]
    fn test_value_empty() {
        let val = ValueBytes::new(0, Bytes::new());
        assert_eq!(val.as_bytes().len(), 0);

        let serialized = val.serialize();
        let deserialized = ValueBytes::deserialize(serialized);
        assert_eq!(deserialized.as_bytes().len(), 0);
    }

    #[test]
    fn test_value_large() {
        let large_value = vec![b'v'; 100000];
        let val = ValueBytes::new(42, Bytes::from(large_value.clone()));

        assert_eq!(val.as_bytes().len(), 100000);

        let serialized = val.serialize();
        let deserialized = ValueBytes::deserialize(serialized);

        assert_eq!(deserialized.ns(), 42);
        assert_eq!(deserialized.as_bytes().len(), 100000);
    }

    #[test]
    fn test_key_default() {
        let key = KeyBytes::default();
        assert_eq!(key.ns(), 0);
        assert_eq!(key.ts(), 0);
        assert!(key.is_empty());
    }

    #[test]
    fn test_value_default() {
        let val = ValueBytes::default();
        assert_eq!(val.ns(), 0);
        assert_eq!(val.as_bytes().len(), 0);
    }

    #[test]
    fn test_key_setters() {
        let mut key = KeyBytes::new(0, Bytes::from("original"), 100);

        key.set_ns(5);
        assert_eq!(key.ns(), 5);

        key.set_ts(200);
        assert_eq!(key.ts(), 200);

        key.set_key(Bytes::from("modified"));
        assert_eq!(key.as_bytes(), Bytes::from("modified"));
    }

    #[test]
    fn test_value_setters() {
        let mut val = ValueBytes::new(0, Bytes::from("original"));

        val.set_ns(10);
        assert_eq!(val.ns(), 10);
    }

    #[test]
    fn test_value_from_slice() {
        let data = b"test data";
        let val = ValueBytes::from_slice(3, data);

        assert_eq!(val.ns(), 3);
        assert_eq!(val.as_bytes(), Bytes::from(&data[..]));
    }

    #[test]
    fn test_value_ordering() {
        let val1 = ValueBytes::new(0, Bytes::from("aaa"));
        let val2 = ValueBytes::new(0, Bytes::from("bbb"));
        let val3 = ValueBytes::new(1, Bytes::from("aaa"));

        assert!(
            val1 < val2,
            "values should be ordered by value bytes in same namespace"
        );
        assert!(val1 < val3, "values should be ordered by namespace first");
        assert!(val2 < val3, "namespace ordering should take precedence");
    }

    #[test]
    fn test_map_key_bound() {
        use std::collections::Bound;

        use crate::keypair::map_key_bound;

        let key = KeyBytes::new(0, Bytes::from("test"), 100);
        let bound = Bound::Included(key.clone());
        let mapped = map_key_bound(bound);

        match mapped {
            | Bound::Included(bytes) => {
                let deserialized = KeyBytes::deserialize(bytes);
                assert_eq!(deserialized, key);
            },
            | _ => panic!("expected Included bound"),
        }

        let bound = Bound::Excluded(key.clone());
        let mapped = map_key_bound(bound);
        match mapped {
            | Bound::Excluded(_) => {},
            | _ => panic!("expected Excluded bound"),
        }

        let bound: Bound<KeyBytes> = Bound::Unbounded;
        let mapped = map_key_bound(bound);
        match mapped {
            | Bound::Unbounded => {},
            | _ => panic!("expected Unbounded bound"),
        }
    }

    #[test]
    fn test_timestamp_boundary_values() {
        // test with u128::MAX timestamp
        let key_max = KeyBytes::new(0, Bytes::from("key"), u128::MAX);
        let serialized = key_max.serialize();
        let deserialized = KeyBytes::deserialize(serialized);
        assert_eq!(deserialized.ts(), u128::MAX);

        // test with 0 timestamp
        let key_zero = KeyBytes::new(0, Bytes::from("key"), 0);
        let serialized = key_zero.serialize();
        let deserialized = KeyBytes::deserialize(serialized);
        assert_eq!(deserialized.ts(), 0);
    }

    #[test]
    fn test_namespace_boundary_values() {
        // test with u64::MAX namespace
        let key = KeyBytes::new(u64::MAX, Bytes::from("key"), 100);
        let serialized = key.serialize();
        let deserialized = KeyBytes::deserialize(serialized);
        assert_eq!(deserialized.ns(), u64::MAX);

        let val = ValueBytes::new(u64::MAX, Bytes::from("value"));
        let serialized = val.serialize();
        let deserialized = ValueBytes::deserialize(serialized);
        assert_eq!(deserialized.ns(), u64::MAX);
    }

    #[test]
    fn test_tombstone_creation() {
        let tombstone = ValueBytes::new_tombstone(42);
        assert!(tombstone.is_tombstone());
        assert_eq!(tombstone.ns(), 42);
        assert_eq!(tombstone.as_bytes().len(), 0);
    }

    #[test]
    fn test_tombstone_serialization() {
        let tombstone = ValueBytes::new_tombstone(5);

        // Test memory serialization
        let serialized = tombstone.serialize();
        let deserialized = ValueBytes::deserialize(serialized);
        assert!(deserialized.is_tombstone());
        assert_eq!(deserialized.ns(), 5);

        // Test storage serialization
        let serialized = tombstone.serialize();
        let deserialized = ValueBytes::deserialize(serialized);
        assert!(deserialized.is_tombstone());
        assert_eq!(deserialized.ns(), 5);
    }

    #[test]
    fn test_non_tombstone_values() {
        let value = ValueBytes::new(0, Bytes::from("data"));
        assert!(!value.is_tombstone());

        let value = ValueBytes::from_slice(1, b"more data");
        assert!(!value.is_tombstone());

        let value = ValueBytes::default();
        assert!(!value.is_tombstone());
    }
}