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
//! Traits allowing to [use types as key](crate::DbOptions::key_type) or
//! [value](crate::DbOptions::value_type)
//!
//! Any type that implements [`Storable`] can be used as a key or value in a
//! [`Db`](crate::Db). Implementation is `unsafe` and must be correct and not
//! change between (re-)opening environments.
//!
//! Types that have a fixed-length byte representation should additionally
//! implement [`StorableConstBytesLen`].
//!
//! When values are retrieved from a database, e.g. with
//! [`Txn::get`](crate::Txn::get), they are returned as a pointer of type
//! [`Storable::AlignedRef`], which may be an ordinary shared reference or a
//! smart-pointer (e.g. [`Owned`]) holding a copy for the purpose of memory
//! alignment. These references may be used directly (via
//! [dereferencing](std::ops::Deref)) or be converted into an owned value using
//! [`GenericCow::into_owned`] (alternatively, method
//! [`Txn::get_owned`](crate::Txn::get_owned) may be used to retrieve an owned
//! value, which isn't provided for the cursor methods though).
//!
//! When storing values, e.g. with [`Txn::put`](crate::TxnRw::put), a reference
//! to the `Storable` value must be provided. Alternatively, a reference-like
//! value can be provided if it implements [`StorableRef`]. For example,
//! `(&'a i32, &'a str)` implements `StorableRef<'a, (i32, String)>` and may be
//! passed instead of `&'a (i32, String)` to avoid unnecessary cloning to
//! construct the tuple.

use crate::cow::{GenericCow, Owned};

// TODO: When stable, use `std::ffi` instead of `core::ffi`
// see: https://github.com/rust-lang/rust/commit/07ea143f96929ac7f0b7af0f025be48a472273e5
use core::ffi::{c_size_t, c_uint};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::mem::{size_of, size_of_val};
use std::ptr::{copy_nonoverlapping, read_unaligned};
use std::slice;
use std::str;

/// Types that can be stored
///
/// Any type that implements `Storable` can be used as a key or value in a
/// [`Db`](crate::Db).
/// Implementation is `unsafe` and must be correct and not change between
/// (re-)opening environments.
/// Types that have a fixed-length byte representation should additionally
/// implement [`StorableConstBytesLen`].
/// Several constants must be set correctly to enable various optimizations.
pub unsafe trait Storable: ToOwned {
    /// Does byte representation have fixed length?
    ///
    /// If this constant is `true`, then trait [`StorableConstBytesLen`] should
    /// also be implemented.
    const CONST_BYTES_LEN: bool;
    /// Does [`Storable::cmp_bytes_unchecked`] perform a trivial (byte wise)
    /// lexicographical comparison?
    const TRIVIAL_CMP: bool = false;
    /// Is type equivalent to [`c_uint`] or [`c_size_t`]?
    const OPTIMIZE_INT: bool = false;
    /// Byte representation as [`GenericCow`]
    ///
    /// This can be a simple reference ([`&'a Self`](prim@reference)) or a
    /// a smart-pointer (like [`Owned<[u8]>`](Owned)) which drops the byte
    /// representation when the smart-pointer is dropped.
    type BytesRef<'a>: GenericCow<Borrowed = [u8]>
    where
        Self: 'a;
    /// Converts to byte slice
    fn to_bytes(&self) -> Self::BytesRef<'_>;
    /// Length of byte representation
    fn bytes_len(&self) -> usize {
        self.to_bytes().len()
    }
    /// Aligned version of `Self` as [`GenericCow`]
    ///
    /// This can be a simple reference ([`&'a Self`](prim@reference)) if there
    /// are no requirements for memory alignment, or can be a smart-pointer
    /// (like [`Owned<Self>`](Owned)) which drops the re-aligned copy when the
    /// smart-pointer is dropped.
    type AlignedRef<'a>: GenericCow<Borrowed = Self>;
    /// Converts from byte slice
    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_>;
    /// Compares byte representation using [`Ord`]
    ///
    /// This function is provided for convenient implementation of
    /// [`Storable::cmp_bytes_unchecked`] where desired.
    unsafe fn cmp_bytes_by_ord_unchecked(a: &[u8], b: &[u8]) -> Ordering
    where
        Self: Ord,
    {
        if Self::TRIVIAL_CMP {
            a.cmp(b)
        } else {
            Self::from_bytes_unchecked(a).cmp(&Self::from_bytes_unchecked(b))
        }
    }
    /// Compares byte representation
    unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering;
}

/// Types that can be stored with a fixed-length byte representation
///
/// This trait should be implemented when [`Storable::CONST_BYTES_LEN`] is
/// true.
pub unsafe trait StorableConstBytesLen: Storable {
    /// Length of byte representation as constant
    const BYTES_LEN: usize;
}

trait Signedness {
    const SIGNED: bool;
}

impl Signedness for bool {
    const SIGNED: bool = false;
}
impl Signedness for u8 {
    const SIGNED: bool = false;
}
impl Signedness for u16 {
    const SIGNED: bool = false;
}
impl Signedness for u32 {
    const SIGNED: bool = false;
}
impl Signedness for u64 {
    const SIGNED: bool = false;
}
impl Signedness for u128 {
    const SIGNED: bool = false;
}
impl Signedness for usize {
    const SIGNED: bool = false;
}
impl Signedness for i8 {
    const SIGNED: bool = true;
}
impl Signedness for i16 {
    const SIGNED: bool = true;
}
impl Signedness for i32 {
    const SIGNED: bool = true;
}
impl Signedness for i64 {
    const SIGNED: bool = true;
}
impl Signedness for i128 {
    const SIGNED: bool = true;
}
impl Signedness for isize {
    const SIGNED: bool = true;
}

macro_rules! impl_kv_fixed_size_always_aligned {
    ($type:ty) => {
        unsafe impl Storable for $type {
            const CONST_BYTES_LEN: bool = true;
            #[cfg(target_endian = "big")]
            const TRIVIAL_CMP: bool = !<Self as Signedness>::SIGNED;
            #[cfg(target_endian = "little")]
            const TRIVIAL_CMP: bool = !<Self as Signedness>::SIGNED && size_of::<Self>() == 1;
            const OPTIMIZE_INT: bool = !<Self as Signedness>::SIGNED
                && (size_of::<Self>() == size_of::<c_uint>()
                    || size_of::<Self>() == size_of::<c_size_t>());
            type BytesRef<'a> = &'a [u8];
            fn to_bytes(&self) -> Self::BytesRef<'_> {
                unsafe {
                    slice::from_raw_parts(self as *const Self as *const u8, size_of::<Self>())
                }
            }
            fn bytes_len(&self) -> usize {
                Self::BYTES_LEN
            }
            type AlignedRef<'a> = &'a Self;
            unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
                &*(bytes as *const _ as *const Self)
            }
            unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
                Self::cmp_bytes_by_ord_unchecked(a, b)
            }
        }
        unsafe impl StorableConstBytesLen for $type {
            const BYTES_LEN: usize = size_of::<Self>();
        }
    };
}

macro_rules! impl_kv_fixed_size_force_align {
    ($type:ty) => {
        unsafe impl Storable for $type {
            const CONST_BYTES_LEN: bool = true;
            #[cfg(target_endian = "big")]
            const TRIVIAL_CMP: bool = !<Self as Signedness>::SIGNED;
            #[cfg(target_endian = "little")]
            const TRIVIAL_CMP: bool = !<Self as Signedness>::SIGNED && size_of::<Self>() == 1;
            const OPTIMIZE_INT: bool = !<Self as Signedness>::SIGNED
                && (size_of::<Self>() == size_of::<c_uint>()
                    || size_of::<Self>() == size_of::<c_size_t>());
            type BytesRef<'a> = &'a [u8];
            fn to_bytes(&self) -> Self::BytesRef<'_> {
                unsafe {
                    slice::from_raw_parts(self as *const Self as *const u8, size_of::<Self>())
                }
            }
            fn bytes_len(&self) -> usize {
                Self::BYTES_LEN
            }
            type AlignedRef<'a> = Owned<Self>;
            unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
                Owned(read_unaligned(bytes.as_ptr() as *const Self))
            }
            unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
                Self::cmp_bytes_by_ord_unchecked(a, b)
            }
        }
        unsafe impl StorableConstBytesLen for $type {
            const BYTES_LEN: usize = size_of::<Self>();
        }
    };
}

impl_kv_fixed_size_always_aligned!(bool);
impl_kv_fixed_size_always_aligned!(u8);
impl_kv_fixed_size_force_align!(u16);
impl_kv_fixed_size_force_align!(u32);
impl_kv_fixed_size_force_align!(u64);
impl_kv_fixed_size_force_align!(u128);
impl_kv_fixed_size_force_align!(usize);
impl_kv_fixed_size_always_aligned!(i8);
impl_kv_fixed_size_force_align!(i16);
impl_kv_fixed_size_force_align!(i32);
impl_kv_fixed_size_force_align!(i64);
impl_kv_fixed_size_force_align!(i128);
impl_kv_fixed_size_force_align!(isize);

unsafe impl Storable for str {
    const CONST_BYTES_LEN: bool = false;
    const TRIVIAL_CMP: bool = true;
    type BytesRef<'a> = &'a [u8];
    fn to_bytes(&self) -> Self::BytesRef<'_> {
        self.as_bytes()
    }
    type AlignedRef<'a> = &'a Self;
    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
        str::from_utf8_unchecked(bytes)
    }
    unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
        Self::cmp_bytes_by_ord_unchecked(a, b)
    }
}

macro_rules! impl_kv_slice_always_aligned {
    ($type:ty) => {
        unsafe impl Storable for [$type] {
            const CONST_BYTES_LEN: bool = false;
            #[cfg(target_endian = "big")]
            const TRIVIAL_CMP: bool = !<$type as Signedness>::SIGNED;
            #[cfg(target_endian = "little")]
            const TRIVIAL_CMP: bool = !<$type as Signedness>::SIGNED && size_of::<$type>() == 1;
            type BytesRef<'a> = &'a [u8];
            fn to_bytes(&self) -> Self::BytesRef<'_> {
                unsafe {
                    slice::from_raw_parts(self as *const Self as *const u8, size_of_val(self))
                }
            }
            type AlignedRef<'a> = &'a Self;
            unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
                slice::from_raw_parts(
                    bytes as *const [u8] as *const $type,
                    bytes.len() / size_of::<$type>(),
                )
            }
            unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
                Self::cmp_bytes_by_ord_unchecked(a, b)
            }
        }
    };
}

macro_rules! impl_kv_slice_force_align {
    ($type:ty) => {
        unsafe impl Storable for [$type] {
            const CONST_BYTES_LEN: bool = false;
            #[cfg(target_endian = "big")]
            const TRIVIAL_CMP: bool = !<$type as Signedness>::SIGNED;
            #[cfg(target_endian = "little")]
            const TRIVIAL_CMP: bool = !<$type as Signedness>::SIGNED && size_of::<$type>() == 1;
            type BytesRef<'a> = &'a [u8];
            fn to_bytes(&self) -> Self::BytesRef<'_> {
                unsafe {
                    slice::from_raw_parts(self as *const Self as *const u8, size_of_val(self))
                }
            }
            type AlignedRef<'a> = Owned<[$type]>;
            unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
                let len = bytes.len() / size_of::<$type>();
                let mut vec: Vec<$type> = Vec::with_capacity(len);
                copy_nonoverlapping(bytes.as_ptr(), vec.as_mut_ptr() as *mut u8, bytes.len());
                vec.set_len(len);
                Owned(vec)
            }
            unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
                Self::cmp_bytes_by_ord_unchecked(a, b)
            }
        }
    };
}

impl_kv_slice_always_aligned!(bool);
impl_kv_slice_always_aligned!(u8);
impl_kv_slice_force_align!(u16);
impl_kv_slice_force_align!(u32);
impl_kv_slice_force_align!(u64);
impl_kv_slice_force_align!(u128);
impl_kv_slice_force_align!(usize);
impl_kv_slice_always_aligned!(i8);
impl_kv_slice_force_align!(i16);
impl_kv_slice_force_align!(i32);
impl_kv_slice_force_align!(i64);
impl_kv_slice_force_align!(i128);
impl_kv_slice_force_align!(isize);

/// Types that can be borrowed as a type that is [`Storable`]
///
/// Automatically implemented for:
///
/// * `Storable` types whose [owning type](ToOwned::Owned) is the same
///   `Storable` type (e.g. `i32` implements `BorrowStorable<Stored=i32>`)
/// * [`Vec<T>`](Vec), where `T` is `Storable` and the
///   [owning type](ToOwned::Owned) is `Vec<T>`, (e.g. `Vec<u8>` implements
///   `BorrowStorable<Stored=[u8]>`)
/// * `String` (with [`BorrowStorable::Stored`] being [`str`](prim@str))
pub trait BorrowStorable: Sized + Borrow<Self::Stored> {
    /// Borrowed [`Storable`] type
    type Stored: ?Sized + Storable + ToOwned<Owned = Self>;
}

impl<T> BorrowStorable for T
where
    T: Storable + ToOwned<Owned = Self>,
{
    type Stored = Self;
}

impl<T> BorrowStorable for Vec<T>
where
    [T]: Storable + ToOwned<Owned = Self>,
    T: Storable,
{
    type Stored = [T];
}

impl BorrowStorable for String {
    type Stored = str;
}

/// Reference-like types which can be used to store a [`Storable`] type
///
/// Type parameter `T` is the `Storable` type and `'a` is the lifetime used for
/// the reference-like type.
///
/// For example, `(&'a i32, &'a str)` implements
/// `StorableRef<'a, (i32, String)>` and may thus be passed to
/// [`TxnRw::put`](crate::TxnRw::put) instead of `&'a (i32, String)`.
/// This avoids unnecessary cloning when constructing the tuple.
pub unsafe trait StorableRef<'a, T>
where
    Self: Sized + Copy,
    T: ?Sized + Storable + 'a,
{
    /// Converts reference to byte slice
    fn ref_to_bytes(self) -> T::BytesRef<'a>;
    /// Length of byte representation
    fn ref_bytes_len(self) -> usize {
        self.ref_to_bytes().len()
    }
}

unsafe impl<'a, T, U> StorableRef<'a, T> for &'a U
where
    T: ?Sized + Storable + 'a,
    U: ?Sized + Borrow<T>,
{
    fn ref_to_bytes(self) -> T::BytesRef<'a> {
        self.borrow().to_bytes()
    }
    fn ref_bytes_len(self) -> usize {
        self.borrow().bytes_len()
    }
}

unsafe impl<'a, T1, T2, U1, U2> StorableRef<'a, (T1, T2)> for (U1, U2)
where
    T1: Clone + BorrowStorable + 'a,
    T2: Clone + BorrowStorable + 'a,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    U1: StorableRef<'a, <T1 as BorrowStorable>::Stored>,
    U2: StorableRef<'a, <T2 as BorrowStorable>::Stored>,
{
    fn ref_to_bytes(self) -> <(T1, T2) as Storable>::BytesRef<'a> {
        let mut bytes = Vec::with_capacity(self.0.ref_bytes_len() + self.1.ref_bytes_len());
        bytes.extend_from_slice(&self.0.ref_to_bytes());
        bytes.extend_from_slice(&self.1.ref_to_bytes());
        Owned(bytes)
    }
}

unsafe impl<T1, T2> Storable for (T1, T2)
where
    T1: Clone + BorrowStorable,
    T2: Clone + BorrowStorable,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
{
    const CONST_BYTES_LEN: bool = <T2 as BorrowStorable>::Stored::CONST_BYTES_LEN;
    const TRIVIAL_CMP: bool =
        <T1 as BorrowStorable>::Stored::TRIVIAL_CMP && <T2 as BorrowStorable>::Stored::TRIVIAL_CMP;
    type AlignedRef<'a> = Owned<Self>;
    type BytesRef<'a> = Owned<[u8]>
    where
        T1: 'a,
        T2: 'a;
    fn to_bytes(&self) -> Self::BytesRef<'_> {
        StorableRef::<(T1, T2)>::ref_to_bytes((&self.0, &self.1))
    }
    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
        let idx1 = <T1 as BorrowStorable>::Stored::BYTES_LEN;
        let v1: T1 =
            <T1 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[0..idx1]).into_owned();
        let v2: T2 =
            <T2 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[idx1..]).into_owned();
        Owned((v1, v2))
    }
    unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
        let idx1 = <T1 as BorrowStorable>::Stored::BYTES_LEN;
        <T1 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[0..idx1], &b[0..idx1]).then_with(
            || <T2 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[idx1..], &b[idx1..]),
        )
    }
}

unsafe impl<T1, T2> StorableConstBytesLen for (T1, T2)
where
    T1: Clone + BorrowStorable,
    T2: Clone + BorrowStorable,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
{
    const BYTES_LEN: usize =
        <T1 as BorrowStorable>::Stored::BYTES_LEN + <T2 as BorrowStorable>::Stored::BYTES_LEN;
}

unsafe impl<'a, T1, T2, T3, U1, U2, U3> StorableRef<'a, (T1, T2, T3)> for (U1, U2, U3)
where
    T1: Clone + BorrowStorable + 'a,
    T2: Clone + BorrowStorable + 'a,
    T3: Clone + BorrowStorable + 'a,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
    U1: StorableRef<'a, <T1 as BorrowStorable>::Stored>,
    U2: StorableRef<'a, <T2 as BorrowStorable>::Stored>,
    U3: StorableRef<'a, <T3 as BorrowStorable>::Stored>,
{
    fn ref_to_bytes(self) -> <(T1, T2, T3) as Storable>::BytesRef<'a> {
        let mut bytes = Vec::with_capacity(
            self.0.ref_bytes_len() + self.1.ref_bytes_len() + self.2.ref_bytes_len(),
        );
        bytes.extend_from_slice(&self.0.ref_to_bytes());
        bytes.extend_from_slice(&self.1.ref_to_bytes());
        bytes.extend_from_slice(&self.2.ref_to_bytes());
        Owned(bytes)
    }
}

unsafe impl<T1, T2, T3> Storable for (T1, T2, T3)
where
    T1: Clone + BorrowStorable,
    T2: Clone + BorrowStorable,
    T3: Clone + BorrowStorable,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
{
    const CONST_BYTES_LEN: bool = <T3 as BorrowStorable>::Stored::CONST_BYTES_LEN;
    const TRIVIAL_CMP: bool = <T1 as BorrowStorable>::Stored::TRIVIAL_CMP
        && <T2 as BorrowStorable>::Stored::TRIVIAL_CMP
        && <T3 as BorrowStorable>::Stored::TRIVIAL_CMP;
    type AlignedRef<'a> = Owned<Self>;
    type BytesRef<'a> = Owned<[u8]>
    where
        T1: 'a,
        T2: 'a,
        T3: 'a;
    fn to_bytes(&self) -> Self::BytesRef<'_> {
        StorableRef::<(T1, T2, T3)>::ref_to_bytes((&self.0, &self.1, &self.2))
    }
    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
        let idx1 = <T1 as BorrowStorable>::Stored::BYTES_LEN;
        let idx2 = idx1 + <T2 as BorrowStorable>::Stored::BYTES_LEN;
        let v1: T1 =
            <T1 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[0..idx1]).into_owned();
        let v2: T2 =
            <T2 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[idx1..idx2]).into_owned();
        let v3: T3 =
            <T3 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[idx2..]).into_owned();
        Owned((v1, v2, v3))
    }
    unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
        let idx1 = <T1 as BorrowStorable>::Stored::BYTES_LEN;
        let idx2 = idx1 + <T2 as BorrowStorable>::Stored::BYTES_LEN;
        <T1 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[0..idx1], &b[0..idx1])
            .then_with(|| {
                <T2 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[idx1..idx2], &b[idx1..idx2])
            })
            .then_with(|| {
                <T3 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[idx2..], &b[idx2..])
            })
    }
}

unsafe impl<T1, T2, T3> StorableConstBytesLen for (T1, T2, T3)
where
    T1: Clone + BorrowStorable,
    T2: Clone + BorrowStorable,
    T3: Clone + BorrowStorable,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T3 as BorrowStorable>::Stored: StorableConstBytesLen,
{
    const BYTES_LEN: usize = <T1 as BorrowStorable>::Stored::BYTES_LEN
        + <T2 as BorrowStorable>::Stored::BYTES_LEN
        + <T3 as BorrowStorable>::Stored::BYTES_LEN;
}

unsafe impl<'a, T1, T2, T3, T4, U1, U2, U3, U4> StorableRef<'a, (T1, T2, T3, T4)>
    for (U1, U2, U3, U4)
where
    T1: Clone + BorrowStorable + 'a,
    T2: Clone + BorrowStorable + 'a,
    T3: Clone + BorrowStorable + 'a,
    T4: Clone + BorrowStorable + 'a,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T3 as BorrowStorable>::Stored: StorableConstBytesLen,
    U1: StorableRef<'a, <T1 as BorrowStorable>::Stored>,
    U2: StorableRef<'a, <T2 as BorrowStorable>::Stored>,
    U3: StorableRef<'a, <T3 as BorrowStorable>::Stored>,
    U4: StorableRef<'a, <T4 as BorrowStorable>::Stored>,
{
    fn ref_to_bytes(self) -> <(T1, T2, T3, T4) as Storable>::BytesRef<'a> {
        let mut bytes = Vec::with_capacity(
            self.0.ref_bytes_len()
                + self.1.ref_bytes_len()
                + self.2.ref_bytes_len()
                + self.3.ref_bytes_len(),
        );
        bytes.extend_from_slice(&self.0.ref_to_bytes());
        bytes.extend_from_slice(&self.1.ref_to_bytes());
        bytes.extend_from_slice(&self.2.ref_to_bytes());
        bytes.extend_from_slice(&self.3.ref_to_bytes());
        Owned(bytes)
    }
}

unsafe impl<T1, T2, T3, T4> Storable for (T1, T2, T3, T4)
where
    T1: Clone + BorrowStorable,
    T2: Clone + BorrowStorable,
    T3: Clone + BorrowStorable,
    T4: Clone + BorrowStorable,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T3 as BorrowStorable>::Stored: StorableConstBytesLen,
{
    const CONST_BYTES_LEN: bool = <T4 as BorrowStorable>::Stored::CONST_BYTES_LEN;
    const TRIVIAL_CMP: bool = <T1 as BorrowStorable>::Stored::TRIVIAL_CMP
        && <T2 as BorrowStorable>::Stored::TRIVIAL_CMP
        && <T3 as BorrowStorable>::Stored::TRIVIAL_CMP
        && <T4 as BorrowStorable>::Stored::TRIVIAL_CMP;
    type AlignedRef<'a> = Owned<Self>;
    type BytesRef<'a> = Owned<[u8]>
    where
        T1: 'a,
        T2: 'a,
        T3: 'a,
        T4: 'a;
    fn to_bytes(&self) -> Self::BytesRef<'_> {
        StorableRef::<(T1, T2, T3, T4)>::ref_to_bytes((&self.0, &self.1, &self.2, &self.3))
    }
    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self::AlignedRef<'_> {
        let idx1 = <T1 as BorrowStorable>::Stored::BYTES_LEN;
        let idx2 = idx1 + <T2 as BorrowStorable>::Stored::BYTES_LEN;
        let idx3 = idx2 + <T3 as BorrowStorable>::Stored::BYTES_LEN;
        let v1: T1 =
            <T1 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[0..idx1]).into_owned();
        let v2: T2 =
            <T2 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[idx1..idx2]).into_owned();
        let v3: T3 =
            <T3 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[idx2..idx3]).into_owned();
        let v4: T4 =
            <T4 as BorrowStorable>::Stored::from_bytes_unchecked(&bytes[idx3..]).into_owned();
        Owned((v1, v2, v3, v4))
    }
    unsafe fn cmp_bytes_unchecked(a: &[u8], b: &[u8]) -> Ordering {
        let idx1 = <T1 as BorrowStorable>::Stored::BYTES_LEN;
        let idx2 = idx1 + <T2 as BorrowStorable>::Stored::BYTES_LEN;
        let idx3 = idx2 + <T3 as BorrowStorable>::Stored::BYTES_LEN;
        <T1 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[0..idx1], &b[0..idx1])
            .then_with(|| {
                <T2 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[idx1..idx2], &b[idx1..idx2])
            })
            .then_with(|| {
                <T3 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[idx2..idx3], &b[idx2..idx3])
            })
            .then_with(|| {
                <T4 as BorrowStorable>::Stored::cmp_bytes_unchecked(&a[idx3..], &b[idx3..])
            })
    }
}

unsafe impl<T1, T2, T3, T4> StorableConstBytesLen for (T1, T2, T3, T4)
where
    T1: Clone + BorrowStorable,
    T2: Clone + BorrowStorable,
    T3: Clone + BorrowStorable,
    T4: Clone + BorrowStorable,
    <T1 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T2 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T3 as BorrowStorable>::Stored: StorableConstBytesLen,
    <T4 as BorrowStorable>::Stored: StorableConstBytesLen,
{
    const BYTES_LEN: usize = <T1 as BorrowStorable>::Stored::BYTES_LEN
        + <T2 as BorrowStorable>::Stored::BYTES_LEN
        + <T3 as BorrowStorable>::Stored::BYTES_LEN
        + <T4 as BorrowStorable>::Stored::BYTES_LEN;
}