bonsaidb_core/
key.rs

1/// [`Key`] implementations for time types.
2pub mod time;
3mod varint;
4
5mod deprecated;
6
7use std::borrow::{Borrow, Cow};
8use std::collections::HashMap;
9use std::convert::Infallible;
10use std::io::{self, ErrorKind};
11use std::num::{
12    NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
13    NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, TryFromIntError,
14};
15use std::ops::Deref;
16use std::string::FromUtf8Error;
17
18use arc_bytes::serde::{Bytes, CowBytes};
19use arc_bytes::ArcBytes;
20pub use bonsaidb_macros::Key;
21pub use deprecated::*;
22use num_traits::{FromPrimitive, ToPrimitive};
23use ordered_varint::{Signed, Unsigned, Variable};
24use serde::{Deserialize, Serialize};
25use transmog::BorrowedDeserializer;
26pub use varint::{VarInt, VariableInteger};
27
28use crate::connection::{Bound, BoundRef, MaybeOwned, RangeRef};
29use crate::AnyError;
30
31/// A trait that enables a type to convert itself into a `memcmp`-compatible
32/// sequence of bytes.
33pub trait KeyEncoding<K = Self>: Send + Sync {
34    /// The error type that can be produced by either serialization or
35    /// deserialization.
36    type Error: AnyError;
37
38    /// The size of the key, if constant. If this type doesn't produce the same
39    /// number of bytes for each value, this should be `None`.
40    const LENGTH: Option<usize>;
41
42    /// Describes this type by invoking functions on `visitor` describing the
43    /// key being encoded.
44    ///
45    /// See the [`KeyVisitor`] trait for more information.
46    ///
47    /// [`KeyDescription::for_key()`]/[`KeyDescription::for_encoding()`] are
48    /// built-in functions
49    fn describe<Visitor>(visitor: &mut Visitor)
50    where
51        Visitor: KeyVisitor;
52
53    /// Convert `self` into a `Cow<'_, [u8]>` containing bytes that are able to be
54    /// compared via `memcmp` in a way that is comptaible with its own Ord
55    /// implementation.
56    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error>;
57}
58
59/// A trait that enables a type to convert itself into a `memcmp`-compatible
60/// sequence of bytes.
61///
62/// # Deriving this trait
63///
64/// This trait can be derived on structs and enums whose members all implement
65/// `Key`. It is important to note that the order of individual fields and enum
66/// variants is important, so special care must be taken when updating enums and
67/// structs when trying to preserve backwards compatibility with existing data.
68///
69/// ```rust
70/// use bonsaidb_core::key::Key;
71///
72/// #[derive(Key, Clone, Debug)]
73/// # #[key(core = bonsaidb_core)]
74/// struct CompositeKey {
75///     user_id: u64,
76///     task_id: u32,
77/// }
78/// ```
79///
80/// Each field or enum variant is encoded and decoded in the order in which it
81/// appears in the source code. The implementation uses [`CompositeKeyEncoder`]
82/// and [`CompositeKeyDecoder`] to encode each field.
83///
84/// ## Changing the `enum` representation type
85///
86/// By default, the derived `Key` implementation will use an `isize` for its
87/// representation, which is encoded using [`ordered_varint`]. If you wish to
88/// use a fixed-size encoding or use `usize`, `enum_repr` can be used to control
89/// the type being encoded.
90///
91/// The default behavior produces compact output for simple enums, but can also
92/// support growing to the limits of `isize`:
93///
94/// ```rust
95/// use bonsaidb_core::key::{Key, KeyEncoding};
96///
97/// #[derive(Key, Clone, Debug)]
98/// # #[key(core = bonsaidb_core)]
99/// enum Color {
100///     Red,
101///     Green,
102///     Blue,
103/// }
104///
105/// let encoded = Color::Red.as_ord_bytes().unwrap();
106/// assert_eq!(encoded.len(), 1);
107/// ```
108///
109/// If a `#[repr(...)]` attribute exists and its parameter is a built-in integer
110/// type, the `Key` derive will use that type for its representation instead:
111///
112/// ```rust
113/// use bonsaidb_core::key::{Key, KeyEncoding};
114///
115/// #[derive(Key, Clone, Debug)]
116/// # #[key(core = bonsaidb_core)]
117/// #[repr(u32)]
118/// enum Color {
119///     Red = 0xFF0000FF,
120///     Green = 0x00FF00FF,
121///     Blue = 0x0000FFFF,
122/// }
123///
124/// let encoded = Color::Red.as_ord_bytes().unwrap();
125/// assert_eq!(encoded.len(), 4);
126/// ```
127///
128/// If the type would rather use a different type for the key encoding than it
129/// uses for in-memory representation, the `enum_repr` parameter can be used:
130///
131/// ```rust
132/// use bonsaidb_core::key::{Key, KeyEncoding};
133///
134/// #[derive(Key, Clone, Debug)]
135/// # #[key(core = bonsaidb_core)]
136/// #[key(enum_repr = u32)]
137/// #[repr(usize)]
138/// enum Color {
139///     Red = 0xFF0000FF,
140///     Green = 0x00FF00FF,
141///     Blue = 0x0000FFFF,
142/// }
143///
144/// let encoded = Color::Red.as_ord_bytes().unwrap();
145/// assert_eq!(encoded.len(), 4);
146/// ```
147///
148/// ## `null_handling`
149///
150/// The derive macro offers an argument `null_handling`, which defaults to
151/// `escape`. Escaping null bytes in variable length fields ensures all data
152/// encoded will sort correctly. In situations where speed is more important
153/// than sorting behavior, `allow` or `deny` can be specified. `allow` will
154/// permit null bytes to pass through encoding and decoding without being
155/// checked. `deny` will check for null bytes when encoding and return an error
156/// if any are present.
157///
158/// Null bytes can cause problematic sort behavior when multiple variable-length
159/// encoded fields are encoded as a composite key. Consider this example:
160///
161/// ```rust
162/// use bonsaidb_core::key::Key;
163///
164/// #[derive(Key, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
165/// #[key(null_handling = allow)]
166/// # #[key(core = bonsaidb_core)]
167/// struct CompositeKey {
168///     a: String,
169///     b: String,
170/// }
171/// ```
172///
173/// With this structure, we can cause sorting misbehaviors using this data set:
174///
175/// | `a`      | `b`   | Encoded Bytes         |
176/// |----------|-------|-----------------------|
177/// | `"a"`    | `"c"` | `6100 6300 0101`      |
178/// | `"a\0b"` | `"a"` | `6100 6200 610003 01` |
179/// | `"b"`    | `"a"` | `6200 6100 0101`      |
180///
181/// In this table, `a` and `b` are ordered as `CompositeKey` would be ordered
182/// when compared using `Ord`. However, the order of the encoded bytes does not
183/// match.
184///
185/// This null-byte edge case only applies to variable length [`Key`]s
186/// ([`KeyEncoding::LENGTH`] is `None`).
187pub trait Key<'k>: KeyEncoding<Self> + Clone + Send + Sync {
188    /// If true, this type can benefit from an owned `Vec<u8>`. This flag is
189    /// used as a hint of whether to attempt to do memcpy operations in some
190    /// decoding operations to avoid extra allocations.
191    const CAN_OWN_BYTES: bool;
192
193    /// Deserialize a sequence of bytes previously encoded with
194    /// [`KeyEncoding::as_ord_bytes`].
195    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error>;
196
197    /// Return the first value in sequence for this type. Not all types
198    /// implement this.
199    fn first_value() -> Result<Self, NextValueError> {
200        Err(NextValueError::Unsupported)
201    }
202
203    /// Return the next value in sequence for this type. Not all types implement
204    /// this. Instead of wrapping/overflowing, None should be returned.
205    fn next_value(&self) -> Result<Self, NextValueError> {
206        Err(NextValueError::Unsupported)
207    }
208}
209
210impl<'a, 'k, K, KE> KeyEncoding<K> for &'a KE
211where
212    KE: KeyEncoding<K> + ?Sized + PartialEq,
213    K: Key<'k> + PartialEq<KE>,
214{
215    type Error = KE::Error;
216
217    const LENGTH: Option<usize> = K::LENGTH;
218
219    fn describe<Visitor>(visitor: &mut Visitor)
220    where
221        Visitor: KeyVisitor,
222    {
223        KE::describe(visitor);
224    }
225
226    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
227        (*self).as_ord_bytes()
228    }
229}
230
231/// A Visitor for information about a [`KeyEncoding`].
232///
233/// This trait is used in [`KeyEncoding::describe`] to report information about
234/// the type of data contained within the key. Using this information,
235/// generically interpreting the bytes of a key type can be possible as long as
236/// the key type uses [`CompositeKeyEncoder`].
237///
238/// This trait is not something that most users will ever need to implement.
239/// Instead,
240/// [`KeyDescription::for_key()`]/[`KeyDescription::for_encoding()`] are
241/// built-in functions to retrieve the information reported by this trait in an
242/// easier-to-use interface.
243pub trait KeyVisitor {
244    /// Report that a basic key type is encoded next in this key.
245    fn visit_type(&mut self, kind: KeyKind);
246
247    /// Report that a composite type made up of `count` fields is encoded next in
248    /// this key.
249    ///
250    /// `KeyVisitor` implementations may panic if there are less than or more
251    /// than `count` fields reported by either `visit_type()` or
252    /// `visit_composite()`.
253    fn visit_composite(&mut self, kind: CompositeKind, count: usize);
254
255    /// Report that the current composite type has extra metadata.
256    ///
257    /// This can be used to encode const generic parameters that are helpful in
258    /// interpretting the contents of a type. For example,
259    /// [`LimitedResolutionTimestamp`](time::limited::LimitedResolutionTimestamp)
260    /// uses this function to report the `TimeEpoch`'s nanoseconds since the
261    /// Unix epoch.
262    fn visit_composite_attribute(
263        &mut self,
264        key: impl Into<Cow<'static, str>>,
265        value: impl Into<KeyAttibuteValue>,
266    );
267}
268
269/// The type of a single field contained in a key.
270#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
271pub enum KeyKind {
272    /// An `unit` type, encoded with no length.
273    Unit,
274    /// An `u8` encoded in big-endian encoding.
275    U8,
276    /// An `u16` encoded in big-endian encoding.
277    U16,
278    /// An `u32` encoded in big-endian encoding.
279    U32,
280    /// An `u64` encoded in big-endian encoding.
281    U64,
282    /// An `u128` encoded in big-endian encoding.
283    U128,
284    /// An `usize` encoded in big-endian encoding.
285    Usize,
286    /// An `i8` encoded in big-endian encoding.
287    I8,
288    /// An `i16` encoded in big-endian encoding.
289    I16,
290    /// An `i32` encoded in big-endian encoding.
291    I32,
292    /// An `i64` encoded in big-endian encoding.
293    I64,
294    /// An `i128` encoded in big-endian encoding.
295    I128,
296    /// An `isize` encoded in big-endian encoding.
297    Isize,
298    /// A [`Signed`] number encoded using [`ordered_varint`].
299    Signed,
300    /// An [`Unsigned`] number encoded using [`ordered_varint`].
301    Unsigned,
302    /// A `bool` encoded as a single byte.
303    Bool,
304    /// A String encoded using BonsaiDb's built-in `KeyEncoding`.
305    String,
306    /// A byte array encoded using BonsaiDb's built-in `KeyEncoding`.
307    Bytes,
308}
309
310/// A value used as part of [`KeyVisitor::visit_composite_attribute`].
311#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
312pub enum KeyAttibuteValue {
313    /// An `u8` value.
314    U8(u8),
315    /// An `i8` value.
316    I8(i8),
317    /// An `u16` value.
318    U16(u16),
319    /// An `i16` value.
320    I16(i16),
321    /// An `u32` value.
322    U32(u32),
323    /// An `i32` value.
324    I32(i32),
325    /// An `u64` value.
326    U64(u64),
327    /// An `i64` value.
328    I64(i64),
329    /// An `u128` value.
330    U128(u128),
331    /// An `i128` value.
332    I128(i128),
333    /// An `usize` value.
334    Usize(usize),
335    /// An `isize` value.
336    Isize(isize),
337    /// A `bool` value.
338    Bool(bool),
339    /// A string value.
340    Str(Cow<'static, str>),
341    /// A byte array value.
342    Bytes(Cow<'static, [u8]>),
343}
344
345macro_rules! impl_const_key_from {
346    ($from:ty, $constkey:expr) => {
347        impl From<$from> for KeyAttibuteValue {
348            fn from(value: $from) -> Self {
349                #[allow(clippy::redundant_closure_call)]
350                $constkey(value)
351            }
352        }
353    };
354}
355
356impl_const_key_from!(u8, KeyAttibuteValue::U8);
357impl_const_key_from!(i8, KeyAttibuteValue::I8);
358impl_const_key_from!(u16, KeyAttibuteValue::U16);
359impl_const_key_from!(i16, KeyAttibuteValue::I16);
360impl_const_key_from!(u32, KeyAttibuteValue::U32);
361impl_const_key_from!(i32, KeyAttibuteValue::I32);
362impl_const_key_from!(u64, KeyAttibuteValue::U64);
363impl_const_key_from!(i64, KeyAttibuteValue::I64);
364impl_const_key_from!(u128, KeyAttibuteValue::U128);
365impl_const_key_from!(i128, KeyAttibuteValue::I128);
366impl_const_key_from!(usize, KeyAttibuteValue::Usize);
367impl_const_key_from!(isize, KeyAttibuteValue::Isize);
368impl_const_key_from!(bool, KeyAttibuteValue::Bool);
369impl_const_key_from!(&'static str, |s: &'static str| KeyAttibuteValue::Str(
370    Cow::Borrowed(s)
371));
372impl_const_key_from!(String, |s: String| KeyAttibuteValue::Str(Cow::Owned(s)));
373impl_const_key_from!(&'static [u8], |b: &'static [u8]| KeyAttibuteValue::Bytes(
374    Cow::Borrowed(b)
375));
376impl_const_key_from!(Vec<u8>, |b: Vec<u8>| KeyAttibuteValue::Bytes(Cow::Owned(b)));
377
378/// A description of the kind of a composite key.
379#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
380pub enum CompositeKind {
381    /// An [`Option`], which always contains a single field.
382    Option,
383    /// An [`Result`], which reports two fields -- the first for the `Ok` type,
384    /// and the second for the `Err` type.
385    Result,
386    /// A sequence of fields.
387    Tuple,
388    /// A sequence of fields, identified by the fully qualified name. E.g.,
389    /// `"std::time::SystemTime"` is the value that the
390    /// [`SystemTime`](std::time::SystemTime)'s `KeyEncoding` implementation
391    /// reports.
392    Struct(Cow<'static, str>),
393}
394
395/// A description of an encoded [`Key`].
396#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
397pub enum KeyDescription {
398    /// A basic key type.
399    Basic(KeyKind),
400    /// A composite key made up of more than one field.
401    Composite(CompositeKeyDescription),
402    /// Another type with a custom encoding format.
403    Other(Cow<'static, str>),
404}
405
406impl KeyDescription {
407    /// Returns a description of the given [`KeyEncoding`] implementor.
408    ///
409    /// # Panics
410    ///
411    /// This function will panic if `KE` emits an imbalanced sequence of visit
412    /// calls.
413    #[must_use]
414    pub fn for_encoding<KE: KeyEncoding<K>, K: for<'k> Key<'k>>() -> Self {
415        let mut describer = KeyDescriber::default();
416        KE::describe(&mut describer);
417        describer
418            .result
419            .expect("invalid KeyEncoding::describe implementation -- imbalanced visit calls")
420    }
421
422    /// Returns the description of a given [`Key`] implementor.
423    ///
424    /// # Panics
425    ///
426    /// This function will panic if `KE` emits an imbalanced sequence of visit
427    /// calls.
428    #[must_use]
429    pub fn for_key<K: for<'k> Key<'k>>() -> Self {
430        Self::for_encoding::<K, K>()
431    }
432}
433
434/// A description of a multi-field key encoded using [`CompositeKeyEncoder`].
435#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
436pub struct CompositeKeyDescription {
437    /// The kind of composite key.
438    pub kind: CompositeKind,
439    /// The fields contained within this key.
440    pub fields: Vec<KeyDescription>,
441    /// The attributes of this key.
442    pub attributes: HashMap<Cow<'static, str>, KeyAttibuteValue>,
443}
444
445#[derive(Default)]
446struct KeyDescriber {
447    stack: Vec<CompositeKeyDescription>,
448    result: Option<KeyDescription>,
449}
450
451impl KeyDescriber {
452    fn record(&mut self, description: KeyDescription) {
453        match self.stack.last_mut() {
454            Some(composite) => {
455                composite.fields.push(description);
456                if composite.fields.len() == composite.fields.capacity() {
457                    // The composite key is finished, pop the state.
458                    let completed = self.stack.pop().expect("just matched");
459                    self.record(KeyDescription::Composite(completed));
460                }
461            }
462            None => {
463                // Stack has been completed.
464                assert!(self.result.replace(description).is_none());
465            }
466        }
467    }
468}
469
470impl KeyVisitor for KeyDescriber {
471    fn visit_type(&mut self, kind: KeyKind) {
472        let description = KeyDescription::Basic(kind);
473        self.record(description);
474    }
475
476    fn visit_composite(&mut self, kind: CompositeKind, count: usize) {
477        self.stack.push(CompositeKeyDescription {
478            kind,
479            fields: Vec::with_capacity(count),
480            attributes: HashMap::new(),
481        });
482    }
483
484    fn visit_composite_attribute(
485        &mut self,
486        key: impl Into<Cow<'static, str>>,
487        value: impl Into<KeyAttibuteValue>,
488    ) {
489        let current = self
490            .stack
491            .last_mut()
492            .expect("visit_composite_attribute must be called only after visit_composite");
493        current.attributes.insert(key.into(), value.into());
494    }
495}
496
497/// The error types for [`Key::next_value()`].
498#[derive(Clone, thiserror::Error, Debug, Serialize, Deserialize)]
499pub enum NextValueError {
500    /// The key type does not support this operation.
501    #[error("the key type does not support automatic ids")]
502    Unsupported,
503    /// Generating a new value would wrap the underlying value.
504    #[error("the key type has run out of unique values")]
505    WouldWrap,
506}
507
508/// A source of bytes from a `&'borrowed [u8]`, `&'ephemeral [u8]` or `Vec<u8>`.
509///
510/// This is used by the [`Key`] trait to allow `'ephemeral` borrows of an owned
511/// `Vec<u8>` while also allowing for code paths that support borrowing from a
512/// `'borrowed` byte slice.
513pub enum ByteSource<'borrowed, 'ephemeral> {
514    /// Borrowed bytes valid for `'borrowed`.
515    Borrowed(&'borrowed [u8]),
516
517    /// Borrowed bytes valid for `'ephemeral`.
518    Ephemeral(&'ephemeral [u8]),
519
520    /// Owned bytes.
521    Owned(Vec<u8>),
522}
523
524impl<'borrowed, 'ephemeral> ByteSource<'borrowed, 'ephemeral>
525where
526    'borrowed: 'ephemeral,
527{
528    /// Coerce a `ByteSource` into `Cow<'borrowed, [u8]>`
529    ///
530    /// This will allocate if this is an `'ephemeral` reference.
531    #[must_use]
532    pub fn into_borrowed(self) -> Cow<'borrowed, [u8]> {
533        match self {
534            Self::Borrowed(bytes) => Cow::Borrowed(bytes),
535            Self::Ephemeral(bytes) => Cow::Owned(Vec::from(bytes)),
536            Self::Owned(bytes) => Cow::Owned(bytes),
537        }
538    }
539
540    /// Coerce a `ByteSource` into a `Vec<u8>`
541    ///
542    /// This will allocate if the source is `'borrowed` or `'ephemeral`.
543    #[must_use]
544    #[allow(clippy::match_same_arms)] // Lifetimes are different.
545    pub fn into_owned(self) -> Vec<u8> {
546        match self {
547            Self::Borrowed(bytes) => Vec::from(bytes),
548            Self::Ephemeral(bytes) => Vec::from(bytes),
549            Self::Owned(bytes) => bytes,
550        }
551    }
552}
553
554impl<'borrowed, 'ephemeral> AsRef<[u8]> for ByteSource<'borrowed, 'ephemeral> {
555    #[allow(clippy::match_same_arms)] // Lifetimes are different.
556    fn as_ref(&self) -> &[u8] {
557        match self {
558            Self::Borrowed(bytes) => bytes,
559            Self::Ephemeral(bytes) => bytes,
560            Self::Owned(ref bytes) => bytes.as_slice(),
561        }
562    }
563}
564
565impl<'borrowed, 'ephemeral> Deref for ByteSource<'borrowed, 'ephemeral> {
566    type Target = [u8];
567
568    fn deref(&self) -> &Self::Target {
569        self.as_ref()
570    }
571}
572
573impl<'borrowed, 'ephemeral> Default for ByteSource<'borrowed, 'ephemeral> {
574    fn default() -> Self {
575        Self::Owned(Vec::default())
576    }
577}
578
579impl<'borrowed, 'ephemeral> From<Cow<'borrowed, [u8]>> for ByteSource<'borrowed, 'ephemeral> {
580    fn from(cow: Cow<'borrowed, [u8]>) -> Self {
581        match cow {
582            Cow::Borrowed(bytes) => ByteSource::Borrowed(bytes),
583            Cow::Owned(bytes) => ByteSource::Owned(bytes),
584        }
585    }
586}
587
588/// A type that can be used as a prefix range in range-based queries.
589pub trait IntoPrefixRange<'a, TOwned>: PartialEq
590where
591    TOwned: Borrow<Self> + PartialEq<Self>,
592{
593    /// Returns the value as a prefix-range, which will match all values that
594    /// start with `self`.
595    fn to_prefix_range(&'a self) -> RangeRef<'a, TOwned, Self>;
596}
597
598fn next_byte_sequence(start: &[u8]) -> Option<Vec<u8>> {
599    let mut end = start.to_vec();
600    // Modify the last byte by adding one. If it would wrap, we proceed to the
601    // next byte.
602    while let Some(last_byte) = end.pop() {
603        if let Some(next) = last_byte.checked_add(1) {
604            end.push(next);
605            return Some(end);
606        }
607    }
608
609    None
610}
611
612impl<'k> Key<'k> for Cow<'k, [u8]> {
613    const CAN_OWN_BYTES: bool = true;
614
615    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
616        Ok(bytes.into_borrowed())
617    }
618}
619
620impl<'k, 'ke> KeyEncoding<Cow<'ke, [u8]>> for Cow<'k, [u8]> {
621    type Error = Infallible;
622
623    const LENGTH: Option<usize> = None;
624
625    fn describe<Visitor>(visitor: &mut Visitor)
626    where
627        Visitor: KeyVisitor,
628    {
629        visitor.visit_type(KeyKind::Bytes);
630    }
631
632    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
633        Ok(self.clone())
634    }
635}
636
637macro_rules! impl_u8_slice_key_encoding {
638    ($type:ty) => {
639        impl<'k> KeyEncoding<$type> for &'k [u8] {
640            type Error = Infallible;
641
642            const LENGTH: Option<usize> = None;
643
644            fn describe<Visitor>(visitor: &mut Visitor)
645            where
646                Visitor: KeyVisitor,
647            {
648                visitor.visit_type(KeyKind::Bytes)
649            }
650
651            fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
652                Ok(Cow::Borrowed(self))
653            }
654        }
655    };
656}
657
658impl_u8_slice_key_encoding!(Cow<'k, [u8]>);
659
660impl<'a, 'k> IntoPrefixRange<'a, Self> for Cow<'k, [u8]> {
661    fn to_prefix_range(&'a self) -> RangeRef<'a, Self> {
662        if let Some(next) = next_byte_sequence(self) {
663            RangeRef {
664                start: BoundRef::borrowed(Bound::Included(self)),
665                end: BoundRef::owned(Bound::Excluded(Cow::Owned(next))),
666            }
667        } else {
668            RangeRef {
669                start: BoundRef::borrowed(Bound::Included(self)),
670                end: BoundRef::Unbounded,
671            }
672        }
673    }
674}
675
676impl<'a, 'k, TOwned, TBorrowed> Key<'k> for MaybeOwned<'a, TOwned, TBorrowed>
677where
678    TBorrowed: KeyEncoding<TOwned, Error = TOwned::Error> + PartialEq + ?Sized,
679    TOwned: Key<'k> + PartialEq<TBorrowed>,
680{
681    const CAN_OWN_BYTES: bool = TOwned::CAN_OWN_BYTES;
682
683    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
684        TOwned::from_ord_bytes(bytes).map(Self::Owned)
685    }
686}
687
688impl<'a, 'k, TOwned, TBorrowed> KeyEncoding<Self> for MaybeOwned<'a, TOwned, TBorrowed>
689where
690    TBorrowed: KeyEncoding<TOwned, Error = TOwned::Error> + PartialEq + ?Sized,
691    TOwned: Key<'k> + PartialEq<TBorrowed>,
692{
693    type Error = TOwned::Error;
694
695    const LENGTH: Option<usize> = TBorrowed::LENGTH;
696
697    fn describe<Visitor>(visitor: &mut Visitor)
698    where
699        Visitor: KeyVisitor,
700    {
701        TBorrowed::describe(visitor);
702    }
703
704    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
705        match self {
706            MaybeOwned::Owned(value) => value.as_ord_bytes(),
707            MaybeOwned::Borrowed(value) => value.as_ord_bytes(),
708        }
709    }
710}
711
712#[test]
713fn cow_prefix_range_tests() {
714    use std::ops::RangeBounds;
715    assert!(Cow::<'_, [u8]>::Borrowed(b"a")
716        .to_prefix_range()
717        .contains(&Cow::Borrowed(&b"aa"[..])));
718    assert!(!Cow::<'_, [u8]>::Borrowed(b"a")
719        .to_prefix_range()
720        .contains(&Cow::Borrowed(&b"b"[..])));
721    assert!(Cow::<'_, [u8]>::Borrowed(b"\xff")
722        .to_prefix_range()
723        .contains(&Cow::Borrowed(&b"\xff\xff"[..])));
724    assert!(!Cow::<'_, [u8]>::Borrowed(b"\xff")
725        .to_prefix_range()
726        .contains(&Cow::Borrowed(&b"\xfe"[..])));
727}
728
729impl<'k> Key<'k> for Vec<u8> {
730    const CAN_OWN_BYTES: bool = true;
731
732    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
733        Ok(bytes.into_owned())
734    }
735}
736
737impl KeyEncoding<Self> for Vec<u8> {
738    type Error = Infallible;
739
740    const LENGTH: Option<usize> = None;
741
742    fn describe<Visitor>(visitor: &mut Visitor)
743    where
744        Visitor: KeyVisitor,
745    {
746        visitor.visit_type(KeyKind::Bytes);
747    }
748
749    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
750        Ok(Cow::Borrowed(self))
751    }
752}
753
754impl_u8_slice_key_encoding!(Vec<u8>);
755
756impl<'k> IntoPrefixRange<'k, Self> for Vec<u8> {
757    fn to_prefix_range(&'k self) -> RangeRef<'k, Self> {
758        if let Some(next) = next_byte_sequence(self) {
759            RangeRef {
760                start: BoundRef::borrowed(Bound::Included(self)),
761                end: BoundRef::owned(Bound::Excluded(next)),
762            }
763        } else {
764            RangeRef {
765                start: BoundRef::borrowed(Bound::Included(self)),
766                end: BoundRef::Unbounded,
767            }
768        }
769    }
770}
771
772impl<'k, const N: usize> Key<'k> for [u8; N] {
773    const CAN_OWN_BYTES: bool = false;
774
775    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
776        if bytes.as_ref().len() == N {
777            let mut array = [0; N];
778            array.copy_from_slice(bytes.as_ref());
779            Ok(array)
780        } else {
781            Err(IncorrectByteLength)
782        }
783    }
784}
785
786impl<const N: usize> KeyEncoding<Self> for [u8; N] {
787    type Error = IncorrectByteLength;
788
789    const LENGTH: Option<usize> = Some(N);
790
791    fn describe<Visitor>(visitor: &mut Visitor)
792    where
793        Visitor: KeyVisitor,
794    {
795        visitor.visit_type(KeyKind::Bytes);
796    }
797
798    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
799        Ok(Cow::Borrowed(self))
800    }
801}
802
803#[test]
804fn vec_prefix_range_tests() {
805    use std::ops::RangeBounds;
806    assert!(b"a".to_vec().to_prefix_range().contains(&b"aa".to_vec()));
807    assert!(!b"a".to_vec().to_prefix_range().contains(&b"b".to_vec()));
808    assert!(b"\xff"
809        .to_vec()
810        .to_prefix_range()
811        .contains(&b"\xff\xff".to_vec()));
812    assert!(!b"\xff"
813        .to_vec()
814        .to_prefix_range()
815        .contains(&b"\xfe".to_vec()));
816}
817
818impl<'k> Key<'k> for ArcBytes<'k> {
819    const CAN_OWN_BYTES: bool = true;
820
821    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
822        Ok(Self::from(bytes.into_borrowed()))
823    }
824}
825
826impl<'k> KeyEncoding<Self> for ArcBytes<'k> {
827    type Error = Infallible;
828
829    const LENGTH: Option<usize> = None;
830
831    fn describe<Visitor>(visitor: &mut Visitor)
832    where
833        Visitor: KeyVisitor,
834    {
835        visitor.visit_type(KeyKind::Bytes);
836    }
837
838    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
839        Ok(Cow::Borrowed(self))
840    }
841}
842
843impl_u8_slice_key_encoding!(ArcBytes<'k>);
844
845impl<'a, 'k> IntoPrefixRange<'a, Self> for ArcBytes<'k> {
846    fn to_prefix_range(&'a self) -> RangeRef<'a, Self> {
847        if let Some(next) = next_byte_sequence(self) {
848            RangeRef {
849                start: BoundRef::borrowed(Bound::Included(self)),
850                end: BoundRef::owned(Bound::Excluded(Self::owned(next))),
851            }
852        } else {
853            RangeRef {
854                start: BoundRef::borrowed(Bound::Included(self)),
855                end: BoundRef::Unbounded,
856            }
857        }
858    }
859}
860
861#[test]
862fn arcbytes_prefix_range_tests() {
863    use std::ops::RangeBounds;
864    assert!(ArcBytes::from(b"a")
865        .to_prefix_range()
866        .contains(&ArcBytes::from(b"aa")));
867    assert!(!ArcBytes::from(b"a")
868        .to_prefix_range()
869        .contains(&ArcBytes::from(b"b")));
870    assert!(ArcBytes::from(b"\xff")
871        .to_prefix_range()
872        .contains(&ArcBytes::from(b"\xff\xff")));
873    assert!(!ArcBytes::from(b"\xff")
874        .to_prefix_range()
875        .contains(&ArcBytes::from(b"\xfe")));
876}
877
878impl<'k> Key<'k> for CowBytes<'k> {
879    const CAN_OWN_BYTES: bool = true;
880
881    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
882        Ok(Self(bytes.into_borrowed()))
883    }
884}
885
886impl<'k> KeyEncoding<Self> for CowBytes<'k> {
887    type Error = Infallible;
888
889    const LENGTH: Option<usize> = None;
890
891    fn describe<Visitor>(visitor: &mut Visitor)
892    where
893        Visitor: KeyVisitor,
894    {
895        visitor.visit_type(KeyKind::Bytes);
896    }
897
898    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
899        Ok(self.0.clone())
900    }
901}
902
903impl_u8_slice_key_encoding!(CowBytes<'k>);
904
905impl<'a, 'k> IntoPrefixRange<'a, Self> for CowBytes<'k> {
906    fn to_prefix_range(&'a self) -> RangeRef<'_, Self> {
907        if let Some(next) = next_byte_sequence(self) {
908            RangeRef {
909                start: BoundRef::borrowed(Bound::Included(self)),
910                end: BoundRef::owned(Bound::Excluded(Self::from(next))),
911            }
912        } else {
913            RangeRef {
914                start: BoundRef::borrowed(Bound::Included(self)),
915                end: BoundRef::Unbounded,
916            }
917        }
918    }
919}
920
921#[test]
922fn cowbytes_prefix_range_tests() {
923    use std::ops::RangeBounds;
924    assert!(CowBytes::from(&b"a"[..])
925        .to_prefix_range()
926        .contains(&CowBytes::from(&b"aa"[..])));
927    assert!(!CowBytes::from(&b"a"[..])
928        .to_prefix_range()
929        .contains(&CowBytes::from(&b"b"[..])));
930    assert!(CowBytes::from(&b"\xff"[..])
931        .to_prefix_range()
932        .contains(&CowBytes::from(&b"\xff\xff"[..])));
933    assert!(!CowBytes::from(&b"\xff"[..])
934        .to_prefix_range()
935        .contains(&CowBytes::from(&b"\xfe"[..])));
936}
937
938impl<'k> Key<'k> for Bytes {
939    const CAN_OWN_BYTES: bool = true;
940
941    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
942        Ok(Self(bytes.into_owned()))
943    }
944}
945
946impl KeyEncoding<Self> for Bytes {
947    type Error = Infallible;
948
949    const LENGTH: Option<usize> = None;
950
951    fn describe<Visitor>(visitor: &mut Visitor)
952    where
953        Visitor: KeyVisitor,
954    {
955        visitor.visit_type(KeyKind::Bytes);
956    }
957
958    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
959        Ok(Cow::Borrowed(self))
960    }
961}
962
963impl_u8_slice_key_encoding!(Bytes);
964
965impl<'a> IntoPrefixRange<'a, Self> for Bytes {
966    fn to_prefix_range(&'a self) -> RangeRef<'a, Self> {
967        if let Some(next) = next_byte_sequence(self) {
968            RangeRef {
969                start: BoundRef::borrowed(Bound::Included(self)),
970                end: BoundRef::owned(Bound::Excluded(Self::from(next))),
971            }
972        } else {
973            RangeRef {
974                start: BoundRef::borrowed(Bound::Included(self)),
975                end: BoundRef::Unbounded,
976            }
977        }
978    }
979}
980
981#[test]
982fn bytes_prefix_range_tests() {
983    use std::ops::RangeBounds;
984    assert!(Bytes::from(b"a".to_vec())
985        .to_prefix_range()
986        .contains(&Bytes::from(b"aa".to_vec())));
987    assert!(!Bytes::from(b"a".to_vec())
988        .to_prefix_range()
989        .contains(&Bytes::from(b"b".to_vec())));
990    assert!(Bytes::from(b"\xff".to_vec())
991        .to_prefix_range()
992        .contains(&Bytes::from(b"\xff\xff".to_vec())));
993    assert!(!Bytes::from(b"\xff".to_vec())
994        .to_prefix_range()
995        .contains(&Bytes::from(b"\xfe".to_vec())));
996}
997
998impl<'k> Key<'k> for String {
999    const CAN_OWN_BYTES: bool = true;
1000
1001    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
1002        Self::from_utf8(bytes.into_owned())
1003    }
1004}
1005
1006impl KeyEncoding<Self> for String {
1007    type Error = FromUtf8Error;
1008
1009    const LENGTH: Option<usize> = None;
1010
1011    fn describe<Visitor>(visitor: &mut Visitor)
1012    where
1013        Visitor: KeyVisitor,
1014    {
1015        visitor.visit_type(KeyKind::String);
1016    }
1017
1018    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1019        Ok(Cow::Borrowed(self.as_bytes()))
1020    }
1021}
1022
1023impl KeyEncoding<String> for str {
1024    type Error = FromUtf8Error;
1025
1026    const LENGTH: Option<usize> = None;
1027
1028    fn describe<Visitor>(visitor: &mut Visitor)
1029    where
1030        Visitor: KeyVisitor,
1031    {
1032        visitor.visit_type(KeyKind::String);
1033    }
1034
1035    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1036        Ok(Cow::Borrowed(self.as_bytes()))
1037    }
1038}
1039
1040impl<'a> IntoPrefixRange<'a, Self> for String {
1041    fn to_prefix_range(&'a self) -> RangeRef<'a, Self> {
1042        let mut bytes = self.as_bytes().to_vec();
1043        for (index, char) in self.char_indices().rev() {
1044            let mut next_char = u32::from(char) + 1;
1045            if next_char == 0xd800 {
1046                next_char = 0xE000;
1047            } else if next_char > u32::from(char::MAX) {
1048                continue;
1049            }
1050
1051            let mut char_bytes = [0; 6];
1052            bytes.splice(
1053                index..,
1054                char::try_from(next_char)
1055                    .unwrap()
1056                    .encode_utf8(&mut char_bytes)
1057                    .bytes(),
1058            );
1059            return RangeRef {
1060                start: BoundRef::borrowed(Bound::Included(self)),
1061                end: BoundRef::owned(Bound::Excluded(Self::from_utf8(bytes).unwrap())),
1062            };
1063        }
1064
1065        RangeRef {
1066            start: BoundRef::borrowed(Bound::Included(self)),
1067            end: BoundRef::Unbounded,
1068        }
1069    }
1070}
1071
1072impl<'a> IntoPrefixRange<'a, String> for str {
1073    fn to_prefix_range(&'a self) -> RangeRef<'a, String, Self> {
1074        let mut bytes = self.as_bytes().to_vec();
1075        for (index, char) in self.char_indices().rev() {
1076            let mut next_char = u32::from(char) + 1;
1077            if next_char == 0xd800 {
1078                next_char = 0xE000;
1079            } else if next_char > u32::from(char::MAX) {
1080                continue;
1081            }
1082
1083            let mut char_bytes = [0; 6];
1084            bytes.splice(
1085                index..,
1086                char::try_from(next_char)
1087                    .unwrap()
1088                    .encode_utf8(&mut char_bytes)
1089                    .bytes(),
1090            );
1091            return RangeRef {
1092                start: BoundRef::borrowed(Bound::Included(self)),
1093                end: BoundRef::owned(Bound::Excluded(String::from_utf8(bytes).unwrap())),
1094            };
1095        }
1096
1097        RangeRef {
1098            start: BoundRef::borrowed(Bound::Included(self)),
1099            end: BoundRef::Unbounded,
1100        }
1101    }
1102}
1103
1104impl<'k> Key<'k> for Cow<'k, str> {
1105    const CAN_OWN_BYTES: bool = true;
1106
1107    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
1108        match bytes.into_borrowed() {
1109            Cow::Borrowed(bytes) => std::str::from_utf8(bytes).map(Cow::Borrowed),
1110            Cow::Owned(bytes) => String::from_utf8(bytes)
1111                .map(Cow::Owned)
1112                .map_err(|e| e.utf8_error()),
1113        }
1114    }
1115}
1116
1117impl<'k> KeyEncoding<Self> for Cow<'k, str> {
1118    type Error = std::str::Utf8Error;
1119
1120    const LENGTH: Option<usize> = None;
1121
1122    fn describe<Visitor>(visitor: &mut Visitor)
1123    where
1124        Visitor: KeyVisitor,
1125    {
1126        visitor.visit_type(KeyKind::String);
1127    }
1128
1129    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1130        Ok(Cow::Borrowed(self.as_bytes()))
1131    }
1132}
1133
1134#[test]
1135fn string_prefix_range_tests() {
1136    use std::ops::RangeBounds;
1137    assert!(String::from("a")
1138        .to_prefix_range()
1139        .contains(&String::from("aa")));
1140    assert!(!String::from("a")
1141        .to_prefix_range()
1142        .contains(&String::from("b")));
1143    assert!(String::from("\u{d799}")
1144        .to_prefix_range()
1145        .contains(&String::from("\u{d799}a")));
1146    assert!(!String::from("\u{d799}")
1147        .to_prefix_range()
1148        .contains(&String::from("\u{e000}")));
1149    assert!(String::from("\u{10ffff}")
1150        .to_prefix_range()
1151        .contains(&String::from("\u{10ffff}a")));
1152    assert!(!String::from("\u{10ffff}")
1153        .to_prefix_range()
1154        .contains(&String::from("\u{10fffe}")));
1155}
1156
1157impl<'k> Key<'k> for () {
1158    const CAN_OWN_BYTES: bool = false;
1159
1160    fn from_ord_bytes<'b>(_: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
1161        Ok(())
1162    }
1163}
1164
1165impl KeyEncoding<Self> for () {
1166    type Error = Infallible;
1167
1168    const LENGTH: Option<usize> = Some(0);
1169
1170    fn describe<Visitor>(visitor: &mut Visitor)
1171    where
1172        Visitor: KeyVisitor,
1173    {
1174        visitor.visit_type(KeyKind::Unit);
1175    }
1176
1177    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1178        Ok(Cow::default())
1179    }
1180}
1181
1182impl<'k> Key<'k> for bool {
1183    const CAN_OWN_BYTES: bool = false;
1184
1185    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
1186        let bytes = bytes.as_ref();
1187        if bytes.is_empty() || bytes[0] == 0 {
1188            Ok(false)
1189        } else {
1190            Ok(true)
1191        }
1192    }
1193}
1194
1195impl KeyEncoding<Self> for bool {
1196    type Error = Infallible;
1197
1198    const LENGTH: Option<usize> = Some(1);
1199
1200    fn describe<Visitor>(visitor: &mut Visitor)
1201    where
1202        Visitor: KeyVisitor,
1203    {
1204        visitor.visit_type(KeyKind::Bool);
1205    }
1206
1207    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1208        if *self {
1209            Ok(Cow::Borrowed(&[1_u8]))
1210        } else {
1211            Ok(Cow::Borrowed(&[0_u8]))
1212        }
1213    }
1214}
1215
1216macro_rules! count_args {
1217    () => (0usize);
1218    ( $arg:tt $($remaining:tt)* ) => (1usize + count_args!($($remaining)*));
1219}
1220
1221macro_rules! impl_key_for_tuple {
1222    ($(($index:tt, $varname:ident, $generic:ident)),+) => {
1223        impl<'k, $($generic),+> Key<'k> for ($($generic),+,)
1224        where
1225            $($generic: for<'ke> Key<'ke>),+
1226        {
1227            const CAN_OWN_BYTES: bool = false;
1228            fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
1229                let mut decoder = CompositeKeyDecoder::default_for(bytes);
1230                $(let $varname = decoder.decode::<$generic>()?;)+
1231                decoder.finish()?;
1232
1233                Ok(($($varname),+,))
1234            }
1235        }
1236
1237        impl<$($generic),+> KeyEncoding<Self> for ($($generic),+,)
1238        where
1239            $($generic: for<'k> Key<'k>),+
1240        {
1241            type Error = CompositeKeyError;
1242
1243            const LENGTH: Option<usize> = match ($($generic::LENGTH),+,) {
1244                ($(Some($varname)),+,) => Some($($varname +)+ 0),
1245                _ => None,
1246            };
1247
1248            fn describe<Visitor>(visitor: &mut Visitor)
1249            where
1250                Visitor: KeyVisitor,
1251            {
1252                visitor.visit_composite(CompositeKind::Tuple, count_args!($($generic) +));
1253                $($generic::describe(visitor);)+
1254            }
1255
1256            fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1257                let mut encoder = CompositeKeyEncoder::default();
1258
1259                $(encoder.encode(&self.$index)?;)+
1260
1261                Ok(Cow::Owned(encoder.finish()))
1262            }
1263        }
1264    };
1265}
1266
1267impl_key_for_tuple!((0, t1, T1));
1268impl_key_for_tuple!((0, t1, T1), (1, t2, T2));
1269impl_key_for_tuple!((0, t1, T1), (1, t2, T2), (2, t3, T3));
1270impl_key_for_tuple!((0, t1, T1), (1, t2, T2), (2, t3, T3), (3, t4, T4));
1271impl_key_for_tuple!(
1272    (0, t1, T1),
1273    (1, t2, T2),
1274    (2, t3, T3),
1275    (3, t4, T4),
1276    (4, t5, T5)
1277);
1278impl_key_for_tuple!(
1279    (0, t1, T1),
1280    (1, t2, T2),
1281    (2, t3, T3),
1282    (3, t4, T4),
1283    (4, t5, T5),
1284    (5, t6, T6)
1285);
1286impl_key_for_tuple!(
1287    (0, t1, T1),
1288    (1, t2, T2),
1289    (2, t3, T3),
1290    (3, t4, T4),
1291    (4, t5, T5),
1292    (5, t6, T6),
1293    (6, t7, T7)
1294);
1295impl_key_for_tuple!(
1296    (0, t1, T1),
1297    (1, t2, T2),
1298    (2, t3, T3),
1299    (3, t4, T4),
1300    (4, t5, T5),
1301    (5, t6, T6),
1302    (6, t7, T7),
1303    (7, t8, T8)
1304);
1305
1306/// Encodes multiple [`KeyEncoding`] implementors into a single byte buffer,
1307/// preserving the ordering guarantees necessary for [`Key`].
1308///
1309/// The produced bytes can be decoded using [`CompositeKeyDecoder`].
1310pub struct CompositeKeyEncoder<NullHandling = EscapeNullBytes> {
1311    bytes: Vec<u8>,
1312    encoded_lengths: Vec<u16>,
1313    null_handling: NullHandling,
1314}
1315
1316impl<NullHandling> CompositeKeyEncoder<NullHandling>
1317where
1318    NullHandling: CompositeKeyNullHandler,
1319{
1320    /// Encodes a single [`KeyEncoding`] implementing value.
1321    ///
1322    /// ```rust
1323    /// # use bonsaidb_core::key::{ByteSource, CompositeKeyEncoder, CompositeKeyDecoder};
1324    ///
1325    /// let value1 = String::from("hello");
1326    /// let value2 = 42_u32;
1327    /// let mut encoder = CompositeKeyEncoder::default();
1328    /// encoder.encode(&value1).unwrap();
1329    /// encoder.encode(&value2).unwrap();
1330    /// let encoded = encoder.finish();
1331    ///
1332    /// let mut decoder = CompositeKeyDecoder::default_for(ByteSource::Borrowed(&encoded));
1333    /// let decoded_string = decoder.decode::<String>().unwrap();
1334    /// assert_eq!(decoded_string, value1);
1335    /// let decoded_u32 = decoder.decode::<u32>().unwrap();
1336    /// assert_eq!(decoded_u32, value2);
1337    /// decoder.finish().expect("trailing bytes");
1338    /// ```
1339    pub fn encode<'k, K: Key<'k>, T: KeyEncoding<K> + ?Sized>(
1340        &mut self,
1341        value: &'k T,
1342    ) -> Result<(), CompositeKeyError> {
1343        let mut encoded = T::as_ord_bytes(value).map_err(CompositeKeyError::new)?;
1344        if T::LENGTH.is_none() {
1345            self.null_handling.handle_nulls(&mut encoded)?;
1346            let encoded_length = u16::try_from(encoded.len())?;
1347            self.encoded_lengths.push(encoded_length);
1348        }
1349        self.bytes.extend_from_slice(&encoded);
1350        if T::LENGTH.is_none() {
1351            // With variable length data, we need the key to have a delimiter to
1352            // ensure that "a" sorts before "aa".
1353            self.bytes.push(0);
1354        }
1355        Ok(())
1356    }
1357
1358    /// Finishes encoding the field and returns the encoded bytes.
1359    #[must_use]
1360    #[allow(clippy::missing_panics_doc)] // All unreachable
1361    pub fn finish(mut self) -> Vec<u8> {
1362        self.bytes.reserve_exact(self.encoded_lengths.len() * 2);
1363        for length in self.encoded_lengths.into_iter().rev() {
1364            match length {
1365                0..=0x7F => {
1366                    self.bytes.push(u8::try_from(length).unwrap());
1367                }
1368                0x80..=0x3FFF => {
1369                    self.bytes.push(u8::try_from(length >> 7).unwrap());
1370                    self.bytes
1371                        .push(u8::try_from((length & 0x7F) | 0x80).unwrap());
1372                }
1373                0x4000.. => {
1374                    self.bytes.push(u8::try_from(length >> 14).unwrap());
1375                    self.bytes
1376                        .push(u8::try_from(((length >> 7) & 0x7F) | 0x80).unwrap());
1377                    self.bytes
1378                        .push(u8::try_from((length & 0x7F) | 0x80).unwrap());
1379                }
1380            }
1381        }
1382        self.bytes
1383    }
1384}
1385
1386impl Default for CompositeKeyEncoder<EscapeNullBytes> {
1387    fn default() -> Self {
1388        Self {
1389            bytes: Vec::new(),
1390            encoded_lengths: Vec::new(),
1391            null_handling: EscapeNullBytes,
1392        }
1393    }
1394}
1395
1396impl CompositeKeyEncoder<AllowNullBytes> {
1397    /// Returns an encoder that allows null bytes in variable length fields.
1398    ///
1399    /// See [`CompositeKeyFieldContainsNullByte`] for information about the edge
1400    /// cases this may introduce.
1401    #[must_use]
1402    pub const fn allowing_null_bytes() -> Self {
1403        Self {
1404            bytes: Vec::new(),
1405            encoded_lengths: Vec::new(),
1406            null_handling: AllowNullBytes,
1407        }
1408    }
1409}
1410
1411impl CompositeKeyEncoder<DenyNullBytes> {
1412    /// Returns an encoder that denies null bytes in variable length fields by
1413    /// returning an error when any null bytes are detected.
1414    #[must_use]
1415    pub const fn denying_null_bytes() -> Self {
1416        Self {
1417            bytes: Vec::new(),
1418            encoded_lengths: Vec::new(),
1419            null_handling: DenyNullBytes,
1420        }
1421    }
1422}
1423
1424/// Escapes null bytes in variable length fields in composite keys. This option
1425/// ensures proper sort order is maintained even when null bytes are used within
1426/// vairable fields.
1427///
1428/// To see more information about the edge case encoding prevents, see
1429/// [`CompositeKeyFieldContainsNullByte`].
1430#[derive(Default, Debug, Clone, Copy)]
1431pub struct EscapeNullBytes;
1432/// Prevents checking for null bytes in variable length fields in composite
1433/// keys. [`Key`] types that have a fixed width have no edge cases with null
1434/// bytes. See [`CompositeKeyFieldContainsNullByte`] for an explanation and
1435/// example of the edge case introduced when allowing null bytes to be used
1436/// without escaping.
1437#[derive(Default, Debug, Clone, Copy)]
1438pub struct AllowNullBytes;
1439#[derive(Default, Debug, Clone, Copy)]
1440/// Checks for null bytes when encoding variable length fields in composite keys
1441/// and returns an error if any are encountered. This prevents extra processing
1442/// when encoding fields, but may introduce incorrect sort ordering (see
1443/// [`CompositeKeyFieldContainsNullByte`] for more).
1444pub struct DenyNullBytes;
1445
1446/// A null-byte handling approach for [`CompositeKeyEncoder`] and
1447/// [`CompositeKeyDecoder`]. This type is only used when the fields being
1448/// encoded are variable length.
1449///
1450/// Ensuring proper sort order with composite keys requires special handling of
1451/// null bytes. The safest option is to use [`EscapeNullBytes`], but this option
1452/// will cause extra allocations when keys contain null bytes.
1453/// [`AllowNullBytes`] allows null-bytes through without any extra checks, but
1454/// their usage can cause incorrect sorting behavior. See
1455/// [`CompositeKeyFieldContainsNullByte`] for more information on this edge
1456/// case. The last implementation is [`DenyNullBytes`] which checks for null
1457/// bytes when encoding and returns an error if any are encountered. When
1458/// decoding with this option, there is no extra processing performed before
1459/// decoding individual fields.
1460pub trait CompositeKeyNullHandler {
1461    /// Process the null bytes in `field_bytes`, if needed.
1462    fn handle_nulls(&self, field_bytes: &mut Cow<'_, [u8]>) -> Result<(), CompositeKeyError>;
1463    /// Decode the null bytes in `encoded`, if needed.
1464    fn decode_nulls_if_needed<'b, 'e>(
1465        &self,
1466        encoded: ByteSource<'b, 'e>,
1467    ) -> Result<ByteSource<'b, 'e>, CompositeKeyError>;
1468}
1469
1470impl CompositeKeyNullHandler for DenyNullBytes {
1471    #[inline]
1472    fn handle_nulls(&self, encoded: &mut Cow<'_, [u8]>) -> Result<(), CompositeKeyError> {
1473        if encoded.iter().any(|b| *b == 0) {
1474            Err(CompositeKeyError::new(io::Error::new(
1475                ErrorKind::InvalidData,
1476                CompositeKeyFieldContainsNullByte,
1477            )))
1478        } else {
1479            Ok(())
1480        }
1481    }
1482
1483    #[inline]
1484    fn decode_nulls_if_needed<'b, 'e>(
1485        &self,
1486        encoded: ByteSource<'b, 'e>,
1487    ) -> Result<ByteSource<'b, 'e>, CompositeKeyError> {
1488        Ok(encoded)
1489    }
1490}
1491
1492impl CompositeKeyNullHandler for AllowNullBytes {
1493    #[inline]
1494    fn handle_nulls(&self, _encoded: &mut Cow<'_, [u8]>) -> Result<(), CompositeKeyError> {
1495        Ok(())
1496    }
1497
1498    #[inline]
1499    fn decode_nulls_if_needed<'b, 'e>(
1500        &self,
1501        encoded: ByteSource<'b, 'e>,
1502    ) -> Result<ByteSource<'b, 'e>, CompositeKeyError> {
1503        Ok(encoded)
1504    }
1505}
1506
1507impl CompositeKeyNullHandler for EscapeNullBytes {
1508    #[inline]
1509    fn handle_nulls(&self, unescaped: &mut Cow<'_, [u8]>) -> Result<(), CompositeKeyError> {
1510        let null_bytes = bytecount::count(unescaped, 0);
1511        if null_bytes > 0 {
1512            let mut null_encoded = Vec::with_capacity(unescaped.len() + null_bytes);
1513            for unescaped in unescaped.as_ref() {
1514                if *unescaped == 0 {
1515                    null_encoded.extend_from_slice(&[0, 0]);
1516                } else {
1517                    null_encoded.push(*unescaped);
1518                }
1519            }
1520            *unescaped = Cow::Owned(null_encoded);
1521        }
1522        Ok(())
1523    }
1524
1525    #[inline]
1526    fn decode_nulls_if_needed<'b, 'e>(
1527        &self,
1528        mut encoded: ByteSource<'b, 'e>,
1529    ) -> Result<ByteSource<'b, 'e>, CompositeKeyError> {
1530        // Find the first null byte
1531        if let Some(mut index) = encoded
1532            .iter()
1533            .enumerate()
1534            .find_map(|(index, b)| (*b == 0).then_some(index))
1535        {
1536            // The field has at least one null byte, we need to mutate the
1537            // bytes.
1538            let mut bytes = encoded.into_owned();
1539            loop {
1540                // Check that the next byte is a null. If so, we remove the
1541                // current byte and look for the next null.
1542                let next_index = index + 1;
1543                if Some(0) == bytes.get(next_index).copied() {
1544                    bytes.remove(index);
1545                    index = next_index;
1546                } else {
1547                    todo!("error: unescaped null byte")
1548                    // return Err(CompositeKeyError::new("unescaped null byte encountered"));
1549                }
1550
1551                // Find the next null byte, if one exists.
1552                let Some(next_index) = bytes[index..]
1553                    .iter()
1554                    .enumerate()
1555                    .find_map(|(index, b)| (*b == 0).then_some(index))
1556                else {
1557                    break;
1558                };
1559                index += next_index;
1560            }
1561            encoded = ByteSource::Owned(bytes);
1562        }
1563        Ok(encoded)
1564    }
1565}
1566
1567/// Null bytes in variable fields encoded with [`CompositeKeyEncoder`] can cause
1568/// sort order to misbehave.
1569///
1570/// Consider these tuples:
1571///
1572/// | Tuple          | Encoded          |
1573/// |----------------|------------------|
1574/// | `("a", "b")`   | `9700 9800 0101` |
1575/// | `("a\0", "a")` | `9700 9700 0101` |
1576///
1577/// The encoded bytes, when compared, will produce a different sort result than
1578/// when comparing the tuples.
1579///
1580/// By default, [`CompositeKeyEncoder`] checks for null bytes and returns an
1581/// error when a null byte is found. See
1582/// [`CompositeKeyEncoder::allowing_null_bytes()`] if you wish
1583/// to allow null bytes despite this edge case.
1584#[derive(thiserror::Error, Debug)]
1585#[error("a variable length field contained a null byte.")]
1586pub struct CompositeKeyFieldContainsNullByte;
1587
1588/// Decodes multiple [`Key`] values from a byte slice previously encoded with
1589/// [`CompositeKeyEncoder`].
1590pub struct CompositeKeyDecoder<'key, 'ephemeral, NullHandling = EscapeNullBytes> {
1591    bytes: ByteSource<'key, 'ephemeral>,
1592    offset: usize,
1593    end: usize,
1594    null_handling: NullHandling,
1595}
1596
1597impl<'key, 'ephemeral> CompositeKeyDecoder<'key, 'ephemeral, EscapeNullBytes> {
1598    /// Returns a decoder for `bytes` that decodes escaped null bytes.
1599    ///
1600    /// This function is compatible with keys encoded with
1601    /// [`CompositeKeyEncoder::default()`].
1602    #[must_use]
1603    pub fn default_for(bytes: ByteSource<'key, 'ephemeral>) -> Self {
1604        Self {
1605            end: bytes.as_ref().len(),
1606            bytes,
1607            offset: 0,
1608            null_handling: EscapeNullBytes,
1609        }
1610    }
1611}
1612
1613impl<'key, 'ephemeral> CompositeKeyDecoder<'key, 'ephemeral, AllowNullBytes> {
1614    /// Returns a decoder for `bytes` that ignores null bytes.
1615    ///
1616    /// This function is compatible with keys encoded with
1617    /// [`CompositeKeyEncoder::allowing_null_bytes()`].
1618    #[must_use]
1619    pub fn allowing_null_bytes(bytes: ByteSource<'key, 'ephemeral>) -> Self {
1620        Self {
1621            end: bytes.as_ref().len(),
1622            bytes,
1623            offset: 0,
1624            null_handling: AllowNullBytes,
1625        }
1626    }
1627}
1628
1629impl<'key, 'ephemeral> CompositeKeyDecoder<'key, 'ephemeral, DenyNullBytes> {
1630    /// Returns a decoder for `bytes` that ignores null bytes.
1631    ///
1632    /// This function is compatible with keys encoded with
1633    /// [`CompositeKeyEncoder::denying_null_bytes()`].
1634    #[must_use]
1635    pub fn denying_null_bytes(bytes: ByteSource<'key, 'ephemeral>) -> Self {
1636        Self {
1637            end: bytes.as_ref().len(),
1638            bytes,
1639            offset: 0,
1640            null_handling: DenyNullBytes,
1641        }
1642    }
1643}
1644
1645impl<'key, 'ephemeral, NullHandling> CompositeKeyDecoder<'key, 'ephemeral, NullHandling>
1646where
1647    NullHandling: CompositeKeyNullHandler,
1648{
1649    /// Decodes a value previously encoded using [`CompositeKeyEncoder`]. Calls
1650    /// to decode must be made in the same order as the values were encoded in.
1651    ///
1652    /// ```rust
1653    /// # use bonsaidb_core::key::{ByteSource, CompositeKeyEncoder, CompositeKeyDecoder};
1654    ///
1655    /// let value1 = String::from("hello");
1656    /// let value2 = 42_u32;
1657    /// let mut encoder = CompositeKeyEncoder::default();
1658    /// encoder.encode(&value1).unwrap();
1659    /// encoder.encode(&value2).unwrap();
1660    /// let encoded = encoder.finish();
1661    ///
1662    /// let mut decoder = CompositeKeyDecoder::default_for(ByteSource::Borrowed(&encoded));
1663    /// let decoded_string = decoder.decode::<String>().unwrap();
1664    /// assert_eq!(decoded_string, value1);
1665    /// let decoded_u32 = decoder.decode::<u32>().unwrap();
1666    /// assert_eq!(decoded_u32, value2);
1667    /// decoder.finish().expect("trailing bytes");
1668    /// ```
1669    pub fn decode<T: Key<'key>>(&mut self) -> Result<T, CompositeKeyError> {
1670        let length = if let Some(length) = T::LENGTH {
1671            length
1672        } else {
1673            // Read a variable-encoded length from the tail of the bytes.
1674            let mut length = 0;
1675            let mut found_end = false;
1676
1677            let bytes = self.bytes.as_ref();
1678
1679            let iterator = bytes[self.offset..self.end]
1680                .iter()
1681                .copied()
1682                .rev()
1683                .enumerate();
1684
1685            for (index, byte) in iterator {
1686                length |= usize::from(byte & 0x7f) << (index * 7);
1687
1688                if byte & 0x80 == 0 {
1689                    self.end = self.end - index - 1;
1690                    found_end = true;
1691                    break;
1692                }
1693            }
1694
1695            if !found_end {
1696                return Err(CompositeKeyError::new(io::Error::from(
1697                    ErrorKind::UnexpectedEof,
1698                )));
1699            }
1700            length
1701        };
1702        let end = self.offset + length;
1703        if end <= self.end {
1704            let mut bytes = match &self.bytes {
1705                ByteSource::Borrowed(bytes) => ByteSource::Borrowed(&bytes[self.offset..end]),
1706                ByteSource::Ephemeral(bytes) => ByteSource::Ephemeral(&bytes[self.offset..end]),
1707                ByteSource::Owned(bytes) => ByteSource::Ephemeral(&bytes[self.offset..end]),
1708            };
1709            if T::LENGTH.is_none() {
1710                bytes = self.null_handling.decode_nulls_if_needed(bytes)?;
1711            }
1712            let decoded = T::from_ord_bytes(bytes).map_err(CompositeKeyError::new)?;
1713            self.offset = end;
1714            if T::LENGTH.is_none() {
1715                // Variable fields always have an extra null byte to delimit the data
1716                self.offset += 1;
1717            }
1718            Ok(decoded)
1719        } else {
1720            Err(CompositeKeyError::new(io::Error::from(
1721                ErrorKind::UnexpectedEof,
1722            )))
1723        }
1724    }
1725
1726    /// Verifies the underlying byte slice has been fully consumed.
1727    pub fn finish(self) -> Result<(), CompositeKeyError> {
1728        if self.offset == self.end {
1729            Ok(())
1730        } else {
1731            Err(CompositeKeyError::new(io::Error::from(
1732                ErrorKind::InvalidData,
1733            )))
1734        }
1735    }
1736}
1737
1738#[test]
1739fn composite_key_null_check_test() {
1740    let mut encoder = CompositeKeyEncoder::denying_null_bytes();
1741    encoder.encode(&vec![0_u8]).unwrap_err();
1742
1743    let mut encoder = CompositeKeyEncoder::allowing_null_bytes();
1744    encoder.encode(&vec![0_u8]).unwrap();
1745    let bytes = encoder.finish();
1746    let mut decoder = CompositeKeyDecoder::allowing_null_bytes(ByteSource::Borrowed(&bytes));
1747    let decoded_value = decoder.decode::<Cow<'_, [u8]>>().unwrap();
1748    assert_eq!(decoded_value.as_ref(), &[0]);
1749    let mut decoder = CompositeKeyDecoder::denying_null_bytes(ByteSource::Borrowed(&bytes));
1750    let decoded_value = decoder.decode::<Cow<'_, [u8]>>().unwrap();
1751    assert_eq!(decoded_value.as_ref(), &[0]);
1752
1753    let mut encoder = CompositeKeyEncoder::default();
1754    encoder.encode(&vec![1_u8, 0, 1]).unwrap();
1755    let bytes = encoder.finish();
1756    // One byte for the length, 3 original bytes, 1 escaped null, 1 field-delimiting null
1757    assert_eq!(bytes.len(), 6);
1758    let mut decoder = CompositeKeyDecoder::default_for(ByteSource::Borrowed(&bytes));
1759    let decoded_value = decoder.decode::<Cow<'_, [u8]>>().unwrap();
1760    assert_eq!(decoded_value.as_ref(), &[1, 0, 1]);
1761}
1762
1763#[test]
1764#[allow(clippy::cognitive_complexity)] // There's no way to please clippy with this
1765fn composite_key_tests() {
1766    /// This test generates various combinations of every tuple type supported.
1767    /// Each test calls this function, which builds a second Vec containing all
1768    /// of the encoded key values. Next, both the original vec and the encoded
1769    /// vec are sorted. The encoded entries are decoded, and the sorted original
1770    /// vec is compared against the decoded vec to ensure the ordering is the
1771    /// same.
1772    ///
1773    /// The macros just make it less verbose to create the nested loops which
1774    /// create the tuples.
1775    fn verify_key_ordering<T: for<'k> Key<'k> + Ord + Eq + std::fmt::Debug>(
1776        mut cases: Vec<T>,
1777        already_ordered: bool,
1778    ) {
1779        let mut encoded = {
1780            cases
1781                .iter()
1782                .map(|tuple| tuple.as_ord_bytes().unwrap().to_vec())
1783                .collect::<Vec<Vec<u8>>>()
1784        };
1785        if !already_ordered {
1786            cases.sort();
1787        }
1788        encoded.sort();
1789        println!("Tested {} entries", cases.len());
1790        let decoded = encoded
1791            .iter()
1792            .map(|encoded| T::from_ord_bytes(ByteSource::Borrowed(encoded)).unwrap())
1793            .collect::<Vec<_>>();
1794        assert_eq!(cases, decoded);
1795    }
1796
1797    // Simple mixed-length tests
1798    let a2 = (String::from("a"), 2_u8);
1799    let aa1 = (String::from("aa"), 1_u8);
1800    let aa2 = (String::from("aa"), 2_u8);
1801    let b1 = (String::from("b"), 1_u8);
1802    let b2 = (String::from("b"), 2_u8);
1803    verify_key_ordering(vec![a2.clone(), aa1.clone()], true);
1804    verify_key_ordering(vec![a2, aa1, aa2, b1, b2], true);
1805
1806    // Two byte length (0x80)
1807    verify_key_ordering(
1808        vec![(vec![1; 127], vec![2; 128]), (vec![1; 128], vec![2; 127])],
1809        true,
1810    );
1811    // Three byte length (0x80)
1812    verify_key_ordering(
1813        vec![
1814            (vec![1; 16383], vec![1; 16384]),
1815            (vec![1; 16384], vec![2; 16383]),
1816        ],
1817        true,
1818    );
1819
1820    let values = [0_u16, 0xFF00, 0x0FF0, 0xFF];
1821    macro_rules! test_enum_variations {
1822        ($($ident:ident),+) => {
1823            let mut cases = Vec::new();
1824            test_enum_variations!(for cases $($ident),+; $($ident),+);
1825            verify_key_ordering(cases, false);
1826        };
1827        (for $cases:ident $first:ident, $($ident:ident),+; $($variable:ident),+) => {
1828            for $first in values {
1829                test_enum_variations!(for $cases $($ident),+; $($variable),+);
1830            }
1831        };
1832        (for $cases:ident $first:ident; $($ident:ident),+) => {
1833            for $first in values {
1834                $cases.push(($($ident),+,));
1835            }
1836        };
1837    }
1838    macro_rules! recursive_test_enum_variations {
1839        ($ident:ident, $($last_ident:ident),+) => {
1840            recursive_test_enum_variations!($($last_ident),+);
1841            test_enum_variations!($ident, $($last_ident),+);
1842        };
1843        ($ident:ident) => {
1844            test_enum_variations!($ident);
1845        }
1846    }
1847    recursive_test_enum_variations!(t1, t2, t3, t4, t5, t6, t7, t8);
1848}
1849
1850/// An error occurred inside of one of the composite key fields.
1851#[derive(thiserror::Error, Debug)]
1852#[error("key error: {0}")]
1853pub struct CompositeKeyError(Box<dyn AnyError>);
1854
1855impl CompositeKeyError {
1856    /// Returns a new instance wrapping `error`.
1857    pub fn new<E: AnyError>(error: E) -> Self {
1858        Self(Box::new(error))
1859    }
1860}
1861
1862impl From<TryFromIntError> for CompositeKeyError {
1863    fn from(err: TryFromIntError) -> Self {
1864        Self::new(err)
1865    }
1866}
1867
1868impl From<io::Error> for CompositeKeyError {
1869    fn from(err: io::Error) -> Self {
1870        Self::new(err)
1871    }
1872}
1873
1874impl<'k> Key<'k> for Signed {
1875    const CAN_OWN_BYTES: bool = false;
1876
1877    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
1878        Self::decode_variable(bytes.as_ref())
1879    }
1880
1881    fn first_value() -> Result<Self, NextValueError> {
1882        Ok(Self::from(0_i128))
1883    }
1884
1885    fn next_value(&self) -> Result<Self, NextValueError> {
1886        i128::try_from(*self)
1887            .ok()
1888            .and_then(|key| key.checked_add(1))
1889            .map(Self::from)
1890            .ok_or(NextValueError::WouldWrap)
1891    }
1892}
1893
1894impl KeyEncoding<Self> for Signed {
1895    type Error = io::Error;
1896
1897    const LENGTH: Option<usize> = None;
1898
1899    fn describe<Visitor>(visitor: &mut Visitor)
1900    where
1901        Visitor: KeyVisitor,
1902    {
1903        visitor.visit_type(KeyKind::Signed);
1904    }
1905
1906    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1907        self.to_variable_vec().map(Cow::Owned)
1908    }
1909}
1910
1911impl<'k> Key<'k> for Unsigned {
1912    const CAN_OWN_BYTES: bool = false;
1913
1914    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
1915        Self::decode_variable(bytes.as_ref())
1916    }
1917
1918    fn first_value() -> Result<Self, NextValueError> {
1919        Ok(Self::from(0_u128))
1920    }
1921
1922    fn next_value(&self) -> Result<Self, NextValueError> {
1923        u128::try_from(*self)
1924            .ok()
1925            .and_then(|key| key.checked_add(1))
1926            .map(Self::from)
1927            .ok_or(NextValueError::WouldWrap)
1928    }
1929}
1930
1931impl KeyEncoding<Self> for Unsigned {
1932    type Error = io::Error;
1933
1934    const LENGTH: Option<usize> = None;
1935
1936    fn describe<Visitor>(visitor: &mut Visitor)
1937    where
1938        Visitor: KeyVisitor,
1939    {
1940        visitor.visit_type(KeyKind::Unsigned);
1941    }
1942
1943    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1944        self.to_variable_vec().map(Cow::Owned)
1945    }
1946}
1947
1948impl<'k> Key<'k> for isize {
1949    const CAN_OWN_BYTES: bool = false;
1950
1951    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
1952        Self::decode_variable(bytes.as_ref())
1953    }
1954
1955    fn first_value() -> Result<Self, NextValueError> {
1956        Ok(0)
1957    }
1958
1959    fn next_value(&self) -> Result<Self, NextValueError> {
1960        self.checked_add(1).ok_or(NextValueError::WouldWrap)
1961    }
1962}
1963
1964impl KeyEncoding<Self> for isize {
1965    type Error = io::Error;
1966
1967    const LENGTH: Option<usize> = None;
1968
1969    fn describe<Visitor>(visitor: &mut Visitor)
1970    where
1971        Visitor: KeyVisitor,
1972    {
1973        visitor.visit_type(KeyKind::Signed);
1974    }
1975
1976    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
1977        self.to_variable_vec().map(Cow::Owned)
1978    }
1979}
1980
1981impl<'k> Key<'k> for usize {
1982    const CAN_OWN_BYTES: bool = false;
1983
1984    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
1985        Self::decode_variable(bytes.as_ref())
1986    }
1987
1988    fn first_value() -> Result<Self, NextValueError> {
1989        Ok(0)
1990    }
1991
1992    fn next_value(&self) -> Result<Self, NextValueError> {
1993        self.checked_add(1).ok_or(NextValueError::WouldWrap)
1994    }
1995}
1996
1997impl KeyEncoding<Self> for usize {
1998    type Error = io::Error;
1999
2000    const LENGTH: Option<Self> = None;
2001
2002    fn describe<Visitor>(visitor: &mut Visitor)
2003    where
2004        Visitor: KeyVisitor,
2005    {
2006        visitor.visit_type(KeyKind::Unsigned);
2007    }
2008
2009    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2010        self.to_variable_vec().map(Cow::Owned)
2011    }
2012}
2013
2014impl<'k> Key<'k> for NonZeroIsize {
2015    const CAN_OWN_BYTES: bool = false;
2016
2017    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
2018        let possibly_zero = isize::decode_variable(bytes.as_ref())?;
2019        Self::new(possibly_zero)
2020            .ok_or_else(|| io::Error::new(ErrorKind::InvalidData, NonZeroKeyError::ValueIsZero))
2021    }
2022
2023    fn first_value() -> Result<Self, NextValueError> {
2024        Ok(Self::new(1).expect("one is not zero"))
2025    }
2026
2027    fn next_value(&self) -> Result<Self, NextValueError> {
2028        let next = self.get().checked_add(1).ok_or(NextValueError::WouldWrap)?;
2029        Ok(Self::new(next)
2030            .unwrap_or_else(|| Self::first_value().expect("first_value returned error")))
2031    }
2032}
2033
2034impl KeyEncoding<Self> for NonZeroIsize {
2035    type Error = io::Error;
2036
2037    const LENGTH: Option<usize> = None;
2038
2039    fn describe<Visitor>(visitor: &mut Visitor)
2040    where
2041        Visitor: KeyVisitor,
2042    {
2043        visitor.visit_type(KeyKind::Signed);
2044    }
2045
2046    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2047        self.get().to_variable_vec().map(Cow::Owned)
2048    }
2049}
2050
2051impl<'k> Key<'k> for NonZeroUsize {
2052    const CAN_OWN_BYTES: bool = false;
2053
2054    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
2055        let possibly_zero = usize::decode_variable(bytes.as_ref())?;
2056        Self::new(possibly_zero)
2057            .ok_or_else(|| io::Error::new(ErrorKind::InvalidData, NonZeroKeyError::ValueIsZero))
2058    }
2059
2060    fn first_value() -> Result<Self, NextValueError> {
2061        Ok(Self::new(1).expect("one is not zero"))
2062    }
2063
2064    fn next_value(&self) -> Result<Self, NextValueError> {
2065        self.checked_add(1).ok_or(NextValueError::WouldWrap)
2066    }
2067}
2068
2069impl KeyEncoding<Self> for NonZeroUsize {
2070    type Error = io::Error;
2071
2072    const LENGTH: Option<usize> = None;
2073
2074    fn describe<Visitor>(visitor: &mut Visitor)
2075    where
2076        Visitor: KeyVisitor,
2077    {
2078        visitor.visit_type(KeyKind::Unsigned);
2079    }
2080
2081    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2082        self.get().to_variable_vec().map(Cow::Owned)
2083    }
2084}
2085
2086#[cfg(feature = "uuid")]
2087impl<'k> Key<'k> for uuid::Uuid {
2088    const CAN_OWN_BYTES: bool = false;
2089
2090    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
2091        Ok(Self::from_bytes(bytes.as_ref().try_into()?))
2092    }
2093}
2094
2095#[cfg(feature = "uuid")]
2096impl KeyEncoding<Self> for uuid::Uuid {
2097    type Error = std::array::TryFromSliceError;
2098
2099    const LENGTH: Option<usize> = Some(16);
2100
2101    fn describe<Visitor>(visitor: &mut Visitor)
2102    where
2103        Visitor: KeyVisitor,
2104    {
2105        visitor.visit_composite(CompositeKind::Struct(Cow::Borrowed("uuid::Uuid")), 1);
2106        visitor.visit_type(KeyKind::Bytes);
2107    }
2108
2109    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2110        Ok(Cow::Borrowed(self.as_bytes()))
2111    }
2112}
2113
2114fn decode_skipping_first_byte<'k, 'e, T>(bytes: ByteSource<'k, 'e>) -> Result<T, T::Error>
2115where
2116    T: Key<'k>,
2117{
2118    match bytes {
2119        ByteSource::Borrowed(bytes) => T::from_ord_bytes(ByteSource::Borrowed(&bytes[1..])),
2120        ByteSource::Ephemeral(bytes) => T::from_ord_bytes(ByteSource::Ephemeral(&bytes[1..])),
2121        ByteSource::Owned(mut bytes) if T::CAN_OWN_BYTES => {
2122            bytes.remove(0);
2123            T::from_ord_bytes(ByteSource::Owned(bytes))
2124        }
2125        ByteSource::Owned(bytes) => T::from_ord_bytes(ByteSource::Ephemeral(&bytes[1..])),
2126    }
2127}
2128
2129impl<'k, T> Key<'k> for Option<T>
2130where
2131    T: Key<'k>,
2132    Self: KeyEncoding<Self, Error = <T as KeyEncoding<T>>::Error>,
2133{
2134    const CAN_OWN_BYTES: bool = T::CAN_OWN_BYTES;
2135
2136    fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
2137        if bytes.as_ref().is_empty() || bytes.as_ref()[0] == 0 {
2138            Ok(None)
2139        } else {
2140            decode_skipping_first_byte(bytes).map(Some)
2141        }
2142    }
2143
2144    fn first_value() -> Result<Self, NextValueError> {
2145        Ok(Some(T::first_value()?))
2146    }
2147
2148    fn next_value(&self) -> Result<Self, NextValueError> {
2149        self.as_ref().map(T::next_value).transpose()
2150    }
2151}
2152
2153impl<'k, T, K> KeyEncoding<Option<K>> for Option<T>
2154where
2155    T: KeyEncoding<K>,
2156    K: Key<'k>,
2157{
2158    type Error = T::Error;
2159
2160    const LENGTH: Option<usize> = match T::LENGTH {
2161        Some(length) => Some(1 + length),
2162        None => None,
2163    };
2164
2165    fn describe<Visitor>(visitor: &mut Visitor)
2166    where
2167        Visitor: KeyVisitor,
2168    {
2169        visitor.visit_composite(CompositeKind::Option, 1);
2170        T::describe(visitor);
2171    }
2172
2173    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2174        if let Some(contents) = self {
2175            let mut contents = contents.as_ord_bytes()?.to_vec();
2176            contents.insert(0, 1);
2177            Ok(Cow::Owned(contents))
2178        } else {
2179            Ok(Cow::Borrowed(b"\0"))
2180        }
2181    }
2182}
2183
2184const RESULT_OK: u8 = 0;
2185const RESULT_ERR: u8 = 1;
2186
2187impl<'k, T, E> Key<'k> for Result<T, E>
2188where
2189    T: Key<'k>,
2190    E: Key<'k, Error = <T as KeyEncoding<T>>::Error>,
2191    Self: KeyEncoding<Self, Error = <T as KeyEncoding<T>>::Error>,
2192{
2193    const CAN_OWN_BYTES: bool = T::CAN_OWN_BYTES || E::CAN_OWN_BYTES;
2194
2195    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
2196        match bytes.as_ref().first() {
2197            Some(&RESULT_OK) => decode_skipping_first_byte(bytes).map(Ok),
2198            Some(_) => decode_skipping_first_byte(bytes).map(Err),
2199            None => {
2200                // Empty buffer, but we don't have an error type.
2201                E::from_ord_bytes(bytes).map(Err)
2202            }
2203        }
2204    }
2205
2206    fn first_value() -> Result<Self, NextValueError> {
2207        Ok(Ok(T::first_value()?))
2208    }
2209
2210    fn next_value(&self) -> Result<Self, NextValueError> {
2211        match self {
2212            Ok(value) => value.next_value().map(Ok),
2213            Err(err) => err.next_value().map(Err),
2214        }
2215    }
2216}
2217
2218impl<'k, T, E, TBorrowed, EBorrowed> KeyEncoding<Result<T, E>> for Result<TBorrowed, EBorrowed>
2219where
2220    TBorrowed: KeyEncoding<T>,
2221    T: Key<'k, Error = TBorrowed::Error>,
2222    EBorrowed: KeyEncoding<E, Error = TBorrowed::Error>,
2223    E: Key<'k, Error = TBorrowed::Error>,
2224{
2225    type Error = <TBorrowed as KeyEncoding<T>>::Error;
2226
2227    const LENGTH: Option<usize> = None;
2228
2229    fn describe<Visitor>(visitor: &mut Visitor)
2230    where
2231        Visitor: KeyVisitor,
2232    {
2233        visitor.visit_composite(CompositeKind::Result, 2);
2234        TBorrowed::describe(visitor);
2235        EBorrowed::describe(visitor);
2236    }
2237
2238    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2239        let (header, contents) = match self {
2240            Ok(value) => (RESULT_OK, value.as_ord_bytes()?),
2241            Err(value) => (RESULT_ERR, value.as_ord_bytes()?),
2242        };
2243        let mut contents = contents.to_vec();
2244        contents.insert(0, header);
2245        Ok(Cow::Owned(contents))
2246    }
2247}
2248
2249#[test]
2250fn result_key_tests() {
2251    let ok_0 = Result::<u8, u16>::first_value().unwrap();
2252    let ok_1 = ok_0.next_value().unwrap();
2253    assert_eq!(ok_1, Ok(1));
2254    let ok_2 = Result::<u8, u16>::Ok(2_u8);
2255    let err_1 = Result::<u8, u16>::Err(1_u16);
2256    let err_2 = err_1.next_value().unwrap();
2257    assert_eq!(err_2, Err(2));
2258    let ok_1_encoded = ok_1.as_ord_bytes().unwrap();
2259    let ok_2_encoded = ok_2.as_ord_bytes().unwrap();
2260    let err_1_encoded = err_1.as_ord_bytes().unwrap();
2261    let err_2_encoded = err_2.as_ord_bytes().unwrap();
2262    assert!(ok_1_encoded < ok_2_encoded);
2263    assert!(ok_2_encoded < err_1_encoded);
2264    assert!(err_1_encoded < err_2_encoded);
2265    assert_eq!(
2266        Result::from_ord_bytes(ByteSource::Borrowed(&ok_1_encoded)).unwrap(),
2267        ok_1
2268    );
2269    assert_eq!(
2270        Result::from_ord_bytes(ByteSource::Borrowed(&ok_2_encoded)).unwrap(),
2271        ok_2
2272    );
2273    assert_eq!(
2274        Result::from_ord_bytes(ByteSource::Borrowed(&err_1_encoded)).unwrap(),
2275        err_1
2276    );
2277    assert_eq!(
2278        Result::from_ord_bytes(ByteSource::Borrowed(&err_2_encoded)).unwrap(),
2279        err_2
2280    );
2281}
2282
2283/// Adds `Key` support to an enum. Requires implementing
2284/// [`ToPrimitive`](num_traits::ToPrimitive) and
2285/// [`FromPrimitive`](num_traits::FromPrimitive), or using a crate like
2286/// [num-derive](https://crates.io/crates/num-derive) to do it automatically.
2287/// Take care when using enums as keys: if the order changes or if the meaning
2288/// of existing numerical values changes, make sure to update any related views'
2289/// version number to ensure the values are re-evaluated.
2290#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
2291pub struct EnumKey<T>(pub T)
2292where
2293    T: ToPrimitive + FromPrimitive + Clone + Eq + Ord + std::fmt::Debug + Send + Sync;
2294
2295/// An error that indicates an unexpected number of bytes were present.
2296#[derive(thiserror::Error, Debug)]
2297#[error("incorrect byte length")]
2298pub struct IncorrectByteLength;
2299
2300/// An error that indicates an unexpected enum variant value was found.
2301#[derive(thiserror::Error, Debug)]
2302#[error("unknown enum variant")]
2303pub struct UnknownEnumVariant;
2304
2305impl From<std::array::TryFromSliceError> for IncorrectByteLength {
2306    fn from(_: std::array::TryFromSliceError) -> Self {
2307        Self
2308    }
2309}
2310
2311// ANCHOR: impl_key_for_enumkey
2312impl<'k, T> Key<'k> for EnumKey<T>
2313where
2314    T: ToPrimitive + FromPrimitive + Clone + Eq + Ord + std::fmt::Debug + Send + Sync,
2315{
2316    const CAN_OWN_BYTES: bool = false;
2317
2318    fn from_ord_bytes<'b>(bytes: ByteSource<'k, 'b>) -> Result<Self, Self::Error> {
2319        let primitive = u64::decode_variable(bytes.as_ref())?;
2320        T::from_u64(primitive)
2321            .map(Self)
2322            .ok_or_else(|| io::Error::new(ErrorKind::InvalidData, UnknownEnumVariant))
2323    }
2324}
2325
2326impl<T> KeyEncoding<Self> for EnumKey<T>
2327where
2328    T: ToPrimitive + FromPrimitive + Clone + Eq + Ord + std::fmt::Debug + Send + Sync,
2329{
2330    type Error = io::Error;
2331
2332    const LENGTH: Option<usize> = None;
2333
2334    fn describe<Visitor>(visitor: &mut Visitor)
2335    where
2336        Visitor: KeyVisitor,
2337    {
2338        visitor.visit_type(KeyKind::Unsigned);
2339    }
2340
2341    fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2342        let integer = self
2343            .0
2344            .to_u64()
2345            .map(Unsigned::from)
2346            .ok_or_else(|| io::Error::new(ErrorKind::InvalidData, IncorrectByteLength))?;
2347        Ok(Cow::Owned(integer.to_variable_vec()?))
2348    }
2349}
2350// ANCHOR_END: impl_key_for_enumkey
2351
2352macro_rules! impl_key_for_primitive {
2353    ($type:ident, $keykind:expr) => {
2354        impl<'k> Key<'k> for $type {
2355            const CAN_OWN_BYTES: bool = false;
2356
2357            fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
2358                Ok($type::from_be_bytes(bytes.as_ref().try_into()?))
2359            }
2360
2361            fn first_value() -> Result<Self, NextValueError> {
2362                Ok(0)
2363            }
2364
2365            fn next_value(&self) -> Result<Self, NextValueError> {
2366                self.checked_add(1).ok_or(NextValueError::WouldWrap)
2367            }
2368        }
2369        impl KeyEncoding<Self> for $type {
2370            type Error = IncorrectByteLength;
2371
2372            const LENGTH: Option<usize> = Some(std::mem::size_of::<$type>());
2373
2374            fn describe<Visitor>(visitor: &mut Visitor)
2375            where
2376                Visitor: KeyVisitor,
2377            {
2378                visitor.visit_type($keykind);
2379            }
2380
2381            fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2382                Ok(Cow::from(self.to_be_bytes().to_vec()))
2383            }
2384        }
2385    };
2386}
2387
2388impl_key_for_primitive!(i8, KeyKind::I8);
2389impl_key_for_primitive!(u8, KeyKind::U8);
2390impl_key_for_primitive!(i16, KeyKind::I16);
2391impl_key_for_primitive!(u16, KeyKind::U16);
2392impl_key_for_primitive!(i32, KeyKind::I32);
2393impl_key_for_primitive!(u32, KeyKind::U32);
2394impl_key_for_primitive!(i64, KeyKind::I64);
2395impl_key_for_primitive!(u64, KeyKind::U64);
2396impl_key_for_primitive!(i128, KeyKind::I128);
2397impl_key_for_primitive!(u128, KeyKind::U128);
2398
2399macro_rules! impl_key_for_nonzero_primitive {
2400    ($nonzero:ident, $type:ident) => {
2401        impl<'k> Key<'k> for $nonzero {
2402            const CAN_OWN_BYTES: bool = false;
2403
2404            fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error> {
2405                let contents = $type::from_be_bytes(bytes.as_ref().try_into()?);
2406                $nonzero::new(contents).ok_or(NonZeroKeyError::ValueIsZero)
2407            }
2408
2409            fn first_value() -> Result<Self, NextValueError> {
2410                Ok($nonzero::new(1).expect("one is not zero"))
2411            }
2412
2413            fn next_value(&self) -> Result<Self, NextValueError> {
2414                if let Some(nonzero) =
2415                    $nonzero::new(self.get().checked_add(1).ok_or(NextValueError::WouldWrap)?)
2416                {
2417                    Ok(nonzero)
2418                } else {
2419                    // Since we've done a checked_add, we know the only failure
2420                    // case here is going from negative to positive. In this
2421                    // sitaution, we skip 0.
2422                    Self::first_value()
2423                }
2424            }
2425        }
2426
2427        impl KeyEncoding<Self> for $nonzero {
2428            type Error = NonZeroKeyError;
2429
2430            const LENGTH: Option<usize> = Some(std::mem::size_of::<$type>());
2431
2432            fn describe<Visitor>(visitor: &mut Visitor)
2433            where
2434                Visitor: KeyVisitor,
2435            {
2436                $type::describe(visitor);
2437            }
2438
2439            fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error> {
2440                Ok(Cow::from(self.get().to_be_bytes().to_vec()))
2441            }
2442        }
2443    };
2444}
2445
2446impl_key_for_nonzero_primitive!(NonZeroI8, i8);
2447impl_key_for_nonzero_primitive!(NonZeroU8, u8);
2448impl_key_for_nonzero_primitive!(NonZeroI16, i16);
2449impl_key_for_nonzero_primitive!(NonZeroU16, u16);
2450impl_key_for_nonzero_primitive!(NonZeroI32, i32);
2451impl_key_for_nonzero_primitive!(NonZeroU32, u32);
2452impl_key_for_nonzero_primitive!(NonZeroI64, i64);
2453impl_key_for_nonzero_primitive!(NonZeroU64, u64);
2454impl_key_for_nonzero_primitive!(NonZeroI128, i128);
2455impl_key_for_nonzero_primitive!(NonZeroU128, u128);
2456
2457/// An error occurred during a [`Key`] or [`KeyEncoding`] implementation for a
2458/// non-zero type.
2459#[derive(thiserror::Error, Debug)]
2460pub enum NonZeroKeyError {
2461    /// An incorrect number of bytes were encounted for the type specified.
2462    #[error("incorrect byte length")]
2463    IncorrectByteLength,
2464    /// A zero value was encountered for a non-zero type.
2465    #[error("zero is not valid for a non-zero type")]
2466    ValueIsZero,
2467}
2468
2469impl From<std::array::TryFromSliceError> for NonZeroKeyError {
2470    fn from(_value: std::array::TryFromSliceError) -> Self {
2471        Self::IncorrectByteLength
2472    }
2473}
2474
2475#[test]
2476#[allow(clippy::cognitive_complexity)] // I disagree - @ecton
2477fn primitive_key_encoding_tests() -> anyhow::Result<()> {
2478    macro_rules! test_primitive_extremes {
2479        ($type:ident) => {
2480            assert_eq!(
2481                &$type::MAX.to_be_bytes(),
2482                $type::MAX.as_ord_bytes()?.as_ref()
2483            );
2484            assert_eq!(
2485                $type::MAX,
2486                $type::from_ord_bytes(ByteSource::Borrowed(&$type::MAX.as_ord_bytes()?))?
2487            );
2488            assert_eq!(
2489                $type::MIN,
2490                $type::from_ord_bytes(ByteSource::Borrowed(&$type::MIN.as_ord_bytes()?))?
2491            );
2492        };
2493    }
2494
2495    test_primitive_extremes!(i8);
2496    test_primitive_extremes!(u8);
2497    test_primitive_extremes!(i16);
2498    test_primitive_extremes!(u16);
2499    test_primitive_extremes!(i32);
2500    test_primitive_extremes!(u32);
2501    test_primitive_extremes!(i64);
2502    test_primitive_extremes!(u64);
2503    test_primitive_extremes!(i128);
2504    test_primitive_extremes!(u128);
2505
2506    assert_eq!(
2507        usize::from_ord_bytes(ByteSource::Borrowed(&usize::MAX.as_ord_bytes().unwrap())).unwrap(),
2508        usize::MAX
2509    );
2510    assert_eq!(
2511        usize::from_ord_bytes(ByteSource::Borrowed(&usize::MIN.as_ord_bytes().unwrap())).unwrap(),
2512        usize::MIN
2513    );
2514    assert_eq!(
2515        isize::from_ord_bytes(ByteSource::Borrowed(&isize::MAX.as_ord_bytes().unwrap())).unwrap(),
2516        isize::MAX
2517    );
2518    assert_eq!(
2519        isize::from_ord_bytes(ByteSource::Borrowed(&isize::MIN.as_ord_bytes().unwrap())).unwrap(),
2520        isize::MIN
2521    );
2522
2523    Ok(())
2524}
2525
2526#[test]
2527fn nonzero_key_encoding_tests() -> anyhow::Result<()> {
2528    macro_rules! test_nonzero {
2529        ($nonzero:ident, $inner:ident) => {
2530            let zero_bytes = [0; ($inner::BITS / 8) as usize];
2531            assert!(matches!(
2532                $nonzero::from_ord_bytes(ByteSource::Borrowed(&zero_bytes)),
2533                Err(NonZeroKeyError::ValueIsZero)
2534            ));
2535            let max = $nonzero::new($inner::MAX).unwrap();
2536            assert_eq!(&max.get().to_be_bytes(), max.as_ord_bytes()?.as_ref());
2537            assert_eq!(
2538                max,
2539                $nonzero::from_ord_bytes(ByteSource::Borrowed(&max.as_ord_bytes()?))?
2540            );
2541            let min = $nonzero::new(if $inner::MIN == 0 { 1 } else { $inner::MIN }).unwrap();
2542            assert_eq!(
2543                min,
2544                $nonzero::from_ord_bytes(ByteSource::Borrowed(&min.as_ord_bytes()?))?
2545            );
2546        };
2547    }
2548    macro_rules! test_signed {
2549        ($nonzero:ident, $inner:ident) => {
2550            test_nonzero!($nonzero, $inner);
2551            let negative_one = $nonzero::new(-1).unwrap();
2552            assert_eq!(negative_one.next_value().unwrap().get(), 1);
2553        };
2554    }
2555
2556    test_nonzero!(NonZeroU8, u8);
2557    test_nonzero!(NonZeroU16, u16);
2558    test_nonzero!(NonZeroU32, u32);
2559    test_nonzero!(NonZeroU64, u64);
2560    test_nonzero!(NonZeroU128, u128);
2561    test_signed!(NonZeroI8, i8);
2562    test_signed!(NonZeroI16, i16);
2563    test_signed!(NonZeroI32, i32);
2564    test_signed!(NonZeroI64, i64);
2565    test_signed!(NonZeroI128, i128);
2566
2567    // NonZeroUsize
2568    let zero_bytes = [0; (usize::BITS / 8) as usize];
2569    assert!(NonZeroUsize::from_ord_bytes(ByteSource::Borrowed(&zero_bytes)).is_err());
2570    let max = NonZeroUsize::new(usize::MAX).unwrap();
2571    assert_eq!(
2572        max.get().as_ord_bytes()?.as_ref(),
2573        max.as_ord_bytes()?.as_ref()
2574    );
2575    assert_eq!(
2576        max,
2577        NonZeroUsize::from_ord_bytes(ByteSource::Borrowed(&max.as_ord_bytes()?))?
2578    );
2579    let min = NonZeroUsize::new(1).unwrap();
2580    assert_eq!(
2581        min,
2582        NonZeroUsize::from_ord_bytes(ByteSource::Borrowed(&min.as_ord_bytes()?))?
2583    );
2584
2585    // NonZeroIsize
2586    assert!(NonZeroIsize::from_ord_bytes(ByteSource::Borrowed(&zero_bytes)).is_err());
2587    let max = NonZeroIsize::new(isize::MAX).unwrap();
2588    assert_eq!(max.get().as_ord_bytes()?, max.as_ord_bytes()?.as_ref());
2589    let min = NonZeroIsize::new(isize::MIN).unwrap();
2590    assert_eq!(
2591        min,
2592        NonZeroIsize::from_ord_bytes(ByteSource::Borrowed(&min.as_ord_bytes()?))?
2593    );
2594    let negative_one = NonZeroIsize::new(-1).unwrap();
2595    assert_eq!(negative_one.next_value().unwrap().get(), 1);
2596
2597    Ok(())
2598}
2599
2600/// A Transmog [`Format`](transmog::Format) implementation that uses [`Key`] to
2601/// serialize and deserialize the contents.
2602#[derive(Default, Debug)]
2603pub struct KeyFormat;
2604
2605impl KeyFormat {
2606    fn get_bytes<T: KeyEncoding>(value: &T) -> io::Result<Cow<'_, [u8]>> {
2607        value
2608            .as_ord_bytes()
2609            .map_err(|err| io::Error::new(ErrorKind::InvalidInput, err))
2610    }
2611}
2612
2613impl<'a, T> transmog::Format<'a, T> for KeyFormat
2614where
2615    T: KeyEncoding,
2616{
2617    type Error = io::Error;
2618
2619    fn serialize_into<W: io::Write>(&self, value: &T, mut writer: W) -> Result<(), Self::Error> {
2620        let data = Self::get_bytes(value)?;
2621        writer.write_all(&data)
2622    }
2623
2624    fn serialized_size(&self, _value: &T) -> Result<Option<usize>, Self::Error> {
2625        Ok(T::LENGTH)
2626    }
2627
2628    fn serialize(&self, value: &T) -> Result<Vec<u8>, Self::Error> {
2629        Ok(Self::get_bytes(value)?.into_owned())
2630    }
2631}
2632
2633impl<'a, T> transmog::BorrowedDeserializer<'a, T> for KeyFormat
2634where
2635    T: Key<'a>,
2636{
2637    fn deserialize_borrowed(&self, data: &'a [u8]) -> Result<T, Self::Error> {
2638        T::from_ord_bytes(ByteSource::Borrowed(data))
2639            .map_err(|err| io::Error::new(ErrorKind::InvalidData, err))
2640    }
2641}
2642
2643impl<T> transmog::OwnedDeserializer<T> for KeyFormat
2644where
2645    T: for<'a> Key<'a> + 'static,
2646{
2647    fn deserialize_from<R: io::Read>(&self, mut reader: R) -> Result<T, Self::Error> {
2648        let mut buffer = Vec::new();
2649        reader.read_to_end(&mut buffer)?;
2650        self.deserialize_owned(&buffer)
2651    }
2652
2653    fn deserialize_owned(&self, data: &[u8]) -> Result<T, Self::Error> {
2654        let possibly_borrowed = self.deserialize_borrowed(data)?;
2655        Ok(possibly_borrowed)
2656    }
2657}
2658
2659#[test]
2660fn optional_key_encoding_tests() -> anyhow::Result<()> {
2661    let some_string = Some("hello").as_ord_bytes()?;
2662    let empty_string = Some("").as_ord_bytes()?;
2663    let none_string = Option::<String>::None.as_ord_bytes()?;
2664    assert_eq!(
2665        Option::<String>::from_ord_bytes(ByteSource::Borrowed(&some_string))
2666            .unwrap()
2667            .as_deref(),
2668        Some("hello")
2669    );
2670    assert_eq!(
2671        Option::<String>::from_ord_bytes(ByteSource::Borrowed(&empty_string))
2672            .unwrap()
2673            .as_deref(),
2674        Some("")
2675    );
2676    assert_eq!(
2677        Option::<String>::from_ord_bytes(ByteSource::Borrowed(&none_string)).unwrap(),
2678        None
2679    );
2680
2681    #[allow(deprecated)]
2682    {
2683        let some_string = OptionKeyV1(Some("hello")).as_ord_bytes()?.to_vec();
2684        let none_string = OptionKeyV1::<String>(None).as_ord_bytes()?;
2685        assert_eq!(
2686            OptionKeyV1::<String>::from_ord_bytes(ByteSource::Borrowed(&some_string))
2687                .unwrap()
2688                .0
2689                .as_deref(),
2690            Some("hello")
2691        );
2692        assert_eq!(
2693            OptionKeyV1::<String>::from_ord_bytes(ByteSource::Borrowed(&none_string))
2694                .unwrap()
2695                .0,
2696            None
2697        );
2698    }
2699    Ok(())
2700}
2701
2702#[test]
2703#[allow(clippy::unit_cmp)] // this is more of a compilation test
2704fn unit_key_encoding_tests() -> anyhow::Result<()> {
2705    assert!(().as_ord_bytes()?.is_empty());
2706    assert_eq!((), <() as Key>::from_ord_bytes(ByteSource::Borrowed(&[]))?);
2707    Ok(())
2708}
2709
2710#[test]
2711#[allow(clippy::unit_cmp)] // this is more of a compilation test
2712fn bool_key_encoding_tests() -> anyhow::Result<()> {
2713    let true_as_bytes = true.as_ord_bytes()?;
2714    let false_as_bytes = false.as_ord_bytes()?;
2715    assert!(bool::from_ord_bytes(ByteSource::Borrowed(&true_as_bytes))?);
2716    assert!(!bool::from_ord_bytes(ByteSource::Borrowed(
2717        &false_as_bytes
2718    ))?);
2719    Ok(())
2720}
2721
2722#[test]
2723fn vec_key_encoding_tests() -> anyhow::Result<()> {
2724    const ORIGINAL_VALUE: &[u8] = b"bonsaidb";
2725    let vec = Cow::<'_, [u8]>::from(ORIGINAL_VALUE);
2726    assert_eq!(
2727        vec.clone(),
2728        Cow::<'_, [u8]>::from_ord_bytes(ByteSource::Borrowed(&vec.as_ord_bytes()?))?
2729    );
2730    Ok(())
2731}
2732
2733#[test]
2734fn enum_derive_tests() -> anyhow::Result<()> {
2735    #[derive(
2736        Debug,
2737        Clone,
2738        num_derive::ToPrimitive,
2739        num_derive::FromPrimitive,
2740        Ord,
2741        PartialOrd,
2742        Eq,
2743        PartialEq,
2744    )]
2745    enum SomeEnum {
2746        One = 1,
2747        NineNineNine = 999,
2748    }
2749
2750    let encoded = EnumKey(SomeEnum::One).as_ord_bytes()?;
2751    let value = EnumKey::<SomeEnum>::from_ord_bytes(ByteSource::Borrowed(&encoded))?;
2752    assert!(matches!(value.0, SomeEnum::One));
2753
2754    let encoded = EnumKey(SomeEnum::NineNineNine).as_ord_bytes()?;
2755    let value = EnumKey::<SomeEnum>::from_ord_bytes(ByteSource::Borrowed(&encoded))?;
2756    assert!(matches!(value.0, SomeEnum::NineNineNine));
2757
2758    Ok(())
2759}
2760
2761#[test]
2762fn key_descriptions() {
2763    use time::limited::TimeEpoch;
2764    assert_eq!(
2765        KeyDescription::for_key::<Vec<u8>>(),
2766        KeyDescription::Basic(KeyKind::Bytes)
2767    );
2768    assert_eq!(
2769        dbg!(KeyDescription::for_key::<time::TimestampAsNanoseconds>()),
2770        KeyDescription::Composite(CompositeKeyDescription {
2771            kind: CompositeKind::Struct(Cow::Borrowed(
2772                "bonsaidb::core::key::time::LimitedResolutionTimestamp"
2773            )),
2774            fields: vec![KeyDescription::Basic(KeyKind::I64),],
2775            attributes: [(
2776                Cow::Borrowed("epoch"),
2777                KeyAttibuteValue::U128(time::limited::BonsaiEpoch::epoch_offset().as_nanos())
2778            )]
2779            .into_iter()
2780            .collect()
2781        })
2782    );
2783    assert_eq!(
2784        KeyDescription::for_key::<(u64, String, Bytes)>(),
2785        KeyDescription::Composite(CompositeKeyDescription {
2786            kind: CompositeKind::Tuple,
2787            fields: vec![
2788                KeyDescription::Basic(KeyKind::U64),
2789                KeyDescription::Basic(KeyKind::String),
2790                KeyDescription::Basic(KeyKind::Bytes),
2791            ],
2792            attributes: HashMap::new(),
2793        })
2794    );
2795}
2796
2797#[test]
2798fn key_serialization() {
2799    #[derive(crate::schema::Collection, Key, Clone, Eq, PartialEq, Debug)]
2800    #[collection(core = crate, name = "test", serialization = Key)]
2801    #[key(core = crate)]
2802    struct Test {
2803        field: u64,
2804    }
2805    let start = Test { field: 42 };
2806    let encoded = <Test as crate::schema::SerializedCollection>::serialize(&start).unwrap();
2807    assert_eq!(encoded, &[0, 0, 0, 0, 0, 0, 0, 42]);
2808    let decoded = <Test as crate::schema::SerializedCollection>::deserialize(&encoded).unwrap();
2809    assert_eq!(decoded, start);
2810}