1pub 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
31pub trait KeyEncoding<K = Self>: Send + Sync {
34 type Error: AnyError;
37
38 const LENGTH: Option<usize>;
41
42 fn describe<Visitor>(visitor: &mut Visitor)
50 where
51 Visitor: KeyVisitor;
52
53 fn as_ord_bytes(&self) -> Result<Cow<'_, [u8]>, Self::Error>;
57}
58
59pub trait Key<'k>: KeyEncoding<Self> + Clone + Send + Sync {
188 const CAN_OWN_BYTES: bool;
192
193 fn from_ord_bytes<'e>(bytes: ByteSource<'k, 'e>) -> Result<Self, Self::Error>;
196
197 fn first_value() -> Result<Self, NextValueError> {
200 Err(NextValueError::Unsupported)
201 }
202
203 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
231pub trait KeyVisitor {
244 fn visit_type(&mut self, kind: KeyKind);
246
247 fn visit_composite(&mut self, kind: CompositeKind, count: usize);
254
255 fn visit_composite_attribute(
263 &mut self,
264 key: impl Into<Cow<'static, str>>,
265 value: impl Into<KeyAttibuteValue>,
266 );
267}
268
269#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
271pub enum KeyKind {
272 Unit,
274 U8,
276 U16,
278 U32,
280 U64,
282 U128,
284 Usize,
286 I8,
288 I16,
290 I32,
292 I64,
294 I128,
296 Isize,
298 Signed,
300 Unsigned,
302 Bool,
304 String,
306 Bytes,
308}
309
310#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
312pub enum KeyAttibuteValue {
313 U8(u8),
315 I8(i8),
317 U16(u16),
319 I16(i16),
321 U32(u32),
323 I32(i32),
325 U64(u64),
327 I64(i64),
329 U128(u128),
331 I128(i128),
333 Usize(usize),
335 Isize(isize),
337 Bool(bool),
339 Str(Cow<'static, str>),
341 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#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
380pub enum CompositeKind {
381 Option,
383 Result,
386 Tuple,
388 Struct(Cow<'static, str>),
393}
394
395#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
397pub enum KeyDescription {
398 Basic(KeyKind),
400 Composite(CompositeKeyDescription),
402 Other(Cow<'static, str>),
404}
405
406impl KeyDescription {
407 #[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 #[must_use]
429 pub fn for_key<K: for<'k> Key<'k>>() -> Self {
430 Self::for_encoding::<K, K>()
431 }
432}
433
434#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
436pub struct CompositeKeyDescription {
437 pub kind: CompositeKind,
439 pub fields: Vec<KeyDescription>,
441 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 let completed = self.stack.pop().expect("just matched");
459 self.record(KeyDescription::Composite(completed));
460 }
461 }
462 None => {
463 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#[derive(Clone, thiserror::Error, Debug, Serialize, Deserialize)]
499pub enum NextValueError {
500 #[error("the key type does not support automatic ids")]
502 Unsupported,
503 #[error("the key type has run out of unique values")]
505 WouldWrap,
506}
507
508pub enum ByteSource<'borrowed, 'ephemeral> {
514 Borrowed(&'borrowed [u8]),
516
517 Ephemeral(&'ephemeral [u8]),
519
520 Owned(Vec<u8>),
522}
523
524impl<'borrowed, 'ephemeral> ByteSource<'borrowed, 'ephemeral>
525where
526 'borrowed: 'ephemeral,
527{
528 #[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 #[must_use]
544 #[allow(clippy::match_same_arms)] 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)] 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
588pub trait IntoPrefixRange<'a, TOwned>: PartialEq
590where
591 TOwned: Borrow<Self> + PartialEq<Self>,
592{
593 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 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
1306pub 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 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 self.bytes.push(0);
1354 }
1355 Ok(())
1356 }
1357
1358 #[must_use]
1360 #[allow(clippy::missing_panics_doc)] 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 #[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 #[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#[derive(Default, Debug, Clone, Copy)]
1431pub struct EscapeNullBytes;
1432#[derive(Default, Debug, Clone, Copy)]
1438pub struct AllowNullBytes;
1439#[derive(Default, Debug, Clone, Copy)]
1440pub struct DenyNullBytes;
1445
1446pub trait CompositeKeyNullHandler {
1461 fn handle_nulls(&self, field_bytes: &mut Cow<'_, [u8]>) -> Result<(), CompositeKeyError>;
1463 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 if let Some(mut index) = encoded
1532 .iter()
1533 .enumerate()
1534 .find_map(|(index, b)| (*b == 0).then_some(index))
1535 {
1536 let mut bytes = encoded.into_owned();
1539 loop {
1540 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 }
1550
1551 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#[derive(thiserror::Error, Debug)]
1585#[error("a variable length field contained a null byte.")]
1586pub struct CompositeKeyFieldContainsNullByte;
1587
1588pub 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 #[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 #[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 #[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 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 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 self.offset += 1;
1717 }
1718 Ok(decoded)
1719 } else {
1720 Err(CompositeKeyError::new(io::Error::from(
1721 ErrorKind::UnexpectedEof,
1722 )))
1723 }
1724 }
1725
1726 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 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)] fn composite_key_tests() {
1766 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 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 verify_key_ordering(
1808 vec![(vec![1; 127], vec![2; 128]), (vec![1; 128], vec![2; 127])],
1809 true,
1810 );
1811 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#[derive(thiserror::Error, Debug)]
1852#[error("key error: {0}")]
1853pub struct CompositeKeyError(Box<dyn AnyError>);
1854
1855impl CompositeKeyError {
1856 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 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#[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#[derive(thiserror::Error, Debug)]
2297#[error("incorrect byte length")]
2298pub struct IncorrectByteLength;
2299
2300#[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
2311impl<'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}
2350macro_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 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#[derive(thiserror::Error, Debug)]
2460pub enum NonZeroKeyError {
2461 #[error("incorrect byte length")]
2463 IncorrectByteLength,
2464 #[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)] fn 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 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 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#[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)] fn 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)] fn 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}