1mod impls;
5#[cfg(any(test, feature = "serde"))]
6pub mod serde;
7
8#[doc(hidden)]
9pub use impls::{visit_named_product, visit_seq_product, WithBound};
10
11use crate::buffer::BufReader;
12use crate::{bsatn, i256, u256};
13use core::fmt;
14use core::marker::PhantomData;
15use smallvec::SmallVec;
16use std::borrow::Borrow;
17
18pub trait Deserializer<'de>: Sized {
33 type Error: Error;
35
36 fn deserialize_product<V: ProductVisitor<'de>>(self, visitor: V) -> Result<V::Output, Self::Error>;
38
39 fn deserialize_sum<V: SumVisitor<'de>>(self, visitor: V) -> Result<V::Output, Self::Error>;
71
72 fn deserialize_bool(self) -> Result<bool, Self::Error>;
74
75 fn deserialize_u8(self) -> Result<u8, Self::Error>;
77
78 fn deserialize_u16(self) -> Result<u16, Self::Error>;
80
81 fn deserialize_u32(self) -> Result<u32, Self::Error>;
83
84 fn deserialize_u64(self) -> Result<u64, Self::Error>;
86
87 fn deserialize_u128(self) -> Result<u128, Self::Error>;
89
90 fn deserialize_u256(self) -> Result<u256, Self::Error>;
92
93 fn deserialize_i8(self) -> Result<i8, Self::Error>;
95
96 fn deserialize_i16(self) -> Result<i16, Self::Error>;
98
99 fn deserialize_i32(self) -> Result<i32, Self::Error>;
101
102 fn deserialize_i64(self) -> Result<i64, Self::Error>;
104
105 fn deserialize_i128(self) -> Result<i128, Self::Error>;
107
108 fn deserialize_i256(self) -> Result<i256, Self::Error>;
110
111 fn deserialize_f32(self) -> Result<f32, Self::Error>;
113
114 fn deserialize_f64(self) -> Result<f64, Self::Error>;
116
117 fn deserialize_str<V: SliceVisitor<'de, str>>(self, visitor: V) -> Result<V::Output, Self::Error>;
119
120 fn deserialize_str_slice(self) -> Result<&'de str, Self::Error> {
122 self.deserialize_str(BorrowedSliceVisitor)
123 }
124
125 fn deserialize_bytes<V: SliceVisitor<'de, [u8]>>(self, visitor: V) -> Result<V::Output, Self::Error>;
127
128 fn deserialize_array<V: ArrayVisitor<'de, T>, T: Deserialize<'de>>(
133 self,
134 visitor: V,
135 ) -> Result<V::Output, Self::Error> {
136 self.deserialize_array_seed(visitor, PhantomData)
137 }
138
139 fn deserialize_array_seed<V: ArrayVisitor<'de, T::Output>, T: DeserializeSeed<'de> + Clone>(
143 self,
144 visitor: V,
145 seed: T,
146 ) -> Result<V::Output, Self::Error>;
147}
148
149pub trait Error: Sized {
159 fn custom(msg: impl fmt::Display) -> Self;
161
162 fn named_products_not_supported() -> Self {
164 Self::custom("named products not supported")
165 }
166
167 fn invalid_product_length<'de, T: ProductVisitor<'de>>(len: usize, expected: &T) -> Self {
169 Self::custom(format_args!(
170 "invalid length {}, expected {}",
171 len,
172 fmt_invalid_len(expected)
173 ))
174 }
175
176 fn missing_field<'de, T: ProductVisitor<'de>>(index: usize, field_name: Option<&str>, prod: &T) -> Self {
178 Self::custom(error_on_field("missing ", index, field_name, prod))
179 }
180
181 fn duplicate_field<'de, T: ProductVisitor<'de>>(index: usize, field_name: Option<&str>, prod: &T) -> Self {
183 Self::custom(error_on_field("duplicate ", index, field_name, prod))
184 }
185
186 fn unknown_field_name<'de, T: FieldNameVisitor<'de>>(field_name: &str, expected: &T) -> Self {
188 let el_ty = match expected.kind() {
189 ProductKind::Normal => "field",
190 ProductKind::ReducerArgs => "reducer argument",
191 };
192 if let Some(one_of) = one_of_names(|| expected.field_names()) {
193 Self::custom(format_args!("unknown {el_ty} `{field_name}`, expected {one_of}"))
194 } else {
195 Self::custom(format_args!("unknown {el_ty} `{field_name}`, there are no {el_ty}s"))
196 }
197 }
198
199 fn unknown_variant_tag<'de, T: SumVisitor<'de>>(tag: u8, expected: &T) -> Self {
201 Self::custom(format_args!(
202 "unknown tag {tag:#x} for sum type {}",
203 expected.sum_name().unwrap_or("<unknown>"),
204 ))
205 }
206
207 fn unknown_variant_name<'de, T: VariantVisitor<'de>>(name: &str, expected: &T) -> Self {
209 if let Some(one_of) = one_of_names(|| expected.variant_names().map(Some)) {
210 Self::custom(format_args!("unknown variant `{name}`, expected {one_of}",))
211 } else {
212 Self::custom(format_args!("unknown variant `{name}`, there are no variants"))
213 }
214 }
215}
216
217pub struct FDisplay<F>(F);
219
220impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for FDisplay<F> {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 (self.0)(f)
223 }
224}
225
226pub fn fmt_fn<F: Fn(&mut fmt::Formatter) -> fmt::Result>(f: F) -> FDisplay<F> {
228 FDisplay(f)
229}
230
231fn error_on_field<'a, 'de>(
233 problem: &'static str,
234 index: usize,
235 name: Option<&'a str>,
236 prod: &impl ProductVisitor<'de>,
237) -> impl fmt::Display + 'a {
238 let field_kind = match prod.product_kind() {
239 ProductKind::Normal => "field",
240 ProductKind::ReducerArgs => "reducer argument",
241 };
242 fmt_fn(move |f| {
243 f.write_str(problem)?;
245 f.write_str(field_kind)?;
246 if let Some(name) = name {
247 write!(f, " `{name}`")
248 } else {
249 write!(f, " (index {index})")
250 }
251 })
252}
253
254fn fmt_invalid_len<'de>(
256 expected: &impl ProductVisitor<'de>,
257) -> FDisplay<impl '_ + Fn(&mut fmt::Formatter) -> fmt::Result> {
258 fmt_fn(|f| {
259 let ty = match expected.product_kind() {
260 ProductKind::Normal => "product type",
261 ProductKind::ReducerArgs => "reducer args for",
262 };
263 let name = expected.product_name().unwrap_or("<product>");
264 let len = expected.product_len();
265
266 write!(f, "{ty} {name} with {len} elements")
267 })
268}
269
270pub trait ProductVisitor<'de> {
272 type Output;
274
275 fn product_name(&self) -> Option<&str>;
277
278 fn product_len(&self) -> usize;
280
281 fn product_kind(&self) -> ProductKind {
283 ProductKind::Normal
284 }
285
286 fn visit_seq_product<A: SeqProductAccess<'de>>(self, prod: A) -> Result<Self::Output, A::Error>;
288
289 fn visit_named_product<A: NamedProductAccess<'de>>(self, prod: A) -> Result<Self::Output, A::Error>;
291}
292
293#[derive(Clone, Copy)]
295pub enum ProductKind {
296 Normal,
298 ReducerArgs,
300}
301
302pub trait SeqProductAccess<'de> {
306 type Error: Error;
308
309 fn next_element<T: Deserialize<'de>>(&mut self) -> Result<Option<T>, Self::Error> {
317 self.next_element_seed(PhantomData)
318 }
319
320 fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Output>, Self::Error>;
328}
329
330pub trait NamedProductAccess<'de> {
334 type Error: Error;
336
337 fn get_field_ident<V: FieldNameVisitor<'de>>(&mut self, visitor: V) -> Result<Option<V::Output>, Self::Error>;
340
341 fn get_field_value<T: Deserialize<'de>>(&mut self) -> Result<T, Self::Error> {
346 self.get_field_value_seed(PhantomData)
347 }
348
349 fn get_field_value_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<T::Output, Self::Error>;
354}
355
356pub trait FieldNameVisitor<'de> {
358 type Output;
360
361 fn kind(&self) -> ProductKind {
363 ProductKind::Normal
364 }
365
366 fn field_names(&self) -> impl '_ + Iterator<Item = Option<&str>>;
370
371 fn visit<E: Error>(self, name: &str) -> Result<Self::Output, E>;
373
374 fn visit_seq(self, index: usize) -> Self::Output;
379}
380
381pub trait SumVisitor<'de> {
386 type Output;
388
389 fn sum_name(&self) -> Option<&str>;
391
392 fn is_option(&self) -> bool {
396 false
397 }
398
399 fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error>;
409}
410
411pub trait SumAccess<'de> {
417 type Error: Error;
419
420 type Variant: VariantAccess<'de, Error = Self::Error>;
422
423 fn variant<V: VariantVisitor<'de>>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error>;
431}
432
433pub trait VariantVisitor<'de> {
436 type Output;
438
439 fn variant_names(&self) -> impl '_ + Iterator<Item = &str>;
441
442 fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E>;
444
445 fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E>;
447}
448
449pub trait VariantAccess<'de>: Sized {
452 type Error: Error;
453
454 fn deserialize<T: Deserialize<'de>>(self) -> Result<T, Self::Error> {
458 self.deserialize_seed(PhantomData)
459 }
460
461 fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error>;
463}
464
465pub trait SliceVisitor<'de, T: ToOwned + ?Sized>: Sized {
468 type Output;
470
471 fn visit<E: Error>(self, slice: &T) -> Result<Self::Output, E>;
476
477 fn visit_owned<E: Error>(self, buf: T::Owned) -> Result<Self::Output, E> {
479 self.visit(buf.borrow())
480 }
481
482 fn visit_borrowed<E: Error>(self, borrowed_slice: &'de T) -> Result<Self::Output, E> {
484 self.visit(borrowed_slice)
485 }
486}
487
488pub trait ArrayVisitor<'de, T> {
490 type Output;
492
493 fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error>;
495}
496
497pub trait ArrayAccess<'de> {
501 type Element;
503
504 type Error: Error;
506
507 fn next_element(&mut self) -> Result<Option<Self::Element>, Self::Error>;
510
511 fn size_hint(&self) -> Option<usize> {
513 None
514 }
515}
516
517pub trait DeserializeSeed<'de> {
519 type Output;
521
522 fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error>;
525}
526
527use crate::de::impls::BorrowedSliceVisitor;
528pub use spacetimedb_bindings_macro::Deserialize;
529
530pub trait Deserialize<'de>: Sized {
545 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>;
547
548 #[doc(hidden)]
549 fn deserialize_from_bsatn<R: BufReader<'de>>(
551 deserializer: bsatn::Deserializer<'de, R>,
552 ) -> Result<Self, bsatn::DecodeError> {
553 Self::deserialize(deserializer)
554 }
555
556 #[doc(hidden)]
558 #[inline(always)]
559 fn __deserialize_vec<D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Self>, D::Error> {
560 deserializer.deserialize_array(BasicVecVisitor)
561 }
562
563 #[doc(hidden)]
564 #[inline(always)]
565 fn __deserialize_array<D: Deserializer<'de>, const N: usize>(deserializer: D) -> Result<[Self; N], D::Error> {
566 deserializer.deserialize_array(BasicArrayVisitor)
567 }
568}
569
570pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
573impl<T: for<'de> Deserialize<'de>> DeserializeOwned for T {}
574
575impl<'de, T: Deserialize<'de>> DeserializeSeed<'de> for PhantomData<T> {
576 type Output = T;
577
578 fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
579 T::deserialize(deserializer)
580 }
581}
582
583pub trait GrowingVec<T> {
585 fn with_capacity(cap: usize) -> Self;
587
588 fn push(&mut self, elem: T);
590}
591
592impl<T> GrowingVec<T> for Vec<T> {
593 fn with_capacity(cap: usize) -> Self {
594 Self::with_capacity(cap)
595 }
596 fn push(&mut self, elem: T) {
597 self.push(elem)
598 }
599}
600
601impl<T, const N: usize> GrowingVec<T> for SmallVec<[T; N]> {
602 fn with_capacity(cap: usize) -> Self {
603 Self::with_capacity(cap)
604 }
605 fn push(&mut self, elem: T) {
606 self.push(elem)
607 }
608}
609
610pub fn array_visit<'de, A: ArrayAccess<'de>, V: GrowingVec<A::Element>>(mut access: A) -> Result<V, A::Error> {
612 let mut v = V::with_capacity(access.size_hint().unwrap_or(0));
613 while let Some(x) = access.next_element()? {
614 v.push(x)
615 }
616 Ok(v)
617}
618
619pub struct BasicVecVisitor;
621
622impl<'de, T> ArrayVisitor<'de, T> for BasicVecVisitor {
623 type Output = Vec<T>;
624
625 fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error> {
626 array_visit(vec)
627 }
628}
629
630pub struct BasicSmallVecVisitor<const N: usize>;
632
633impl<'de, T, const N: usize> ArrayVisitor<'de, T> for BasicSmallVecVisitor<N> {
634 type Output = SmallVec<[T; N]>;
635
636 fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error> {
637 array_visit(vec)
638 }
639}
640
641struct BasicArrayVisitor<const N: usize>;
643
644impl<'de, T, const N: usize> ArrayVisitor<'de, T> for BasicArrayVisitor<N> {
645 type Output = [T; N];
646
647 fn visit<A: ArrayAccess<'de, Element = T>>(self, mut vec: A) -> Result<Self::Output, A::Error> {
648 let mut v = arrayvec::ArrayVec::<T, N>::new();
649 while let Some(el) = vec.next_element()? {
650 v.try_push(el)
651 .map_err(|_| Error::custom("too many elements for array"))?
652 }
653 v.into_inner().map_err(|_| Error::custom("too few elements for array"))
654 }
655}
656
657fn one_of_names<'a, I: Iterator<Item = Option<&'a str>>>(names: impl Fn() -> I) -> Option<impl fmt::Display> {
661 let count = names().count();
663
664 (count != 0).then(move || {
666 fmt_fn(move |f| {
667 let mut anon_name = 0;
668 for (index, mut name) in names().enumerate() {
674 let mut name_buf: String = String::new();
675 let name = name.get_or_insert_with(|| {
676 name_buf = format!("{anon_name}");
677 anon_name += 1;
678 &name_buf
679 });
680 match (count, index) {
681 (1, _) => write!(f, "`{name}`"),
682 (2, 1) => write!(f, "`{name}`"),
683 (2, 2) => write!(f, "`or `{name}`"),
684 (_, 1) => write!(f, "one of `{name}`"),
685 (c, i) if i < c => write!(f, ", `{name}`"),
686 (_, _) => write!(f, ", `, or {name}`"),
687 }?;
688 }
689
690 Ok(())
691 })
692 })
693}
694
695pub struct NoneAccess<E>(PhantomData<E>);
697
698impl<E: Error> NoneAccess<E> {
699 pub fn new() -> Self {
701 Self(PhantomData)
702 }
703}
704
705impl<E: Error> Default for NoneAccess<E> {
706 fn default() -> Self {
707 Self::new()
708 }
709}
710
711impl<'de, E: Error> SumAccess<'de> for NoneAccess<E> {
712 type Error = E;
713 type Variant = Self;
714
715 fn variant<V: VariantVisitor<'de>>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error> {
716 visitor.visit_name("none").map(|var| (var, self))
717 }
718}
719impl<'de, E: Error> VariantAccess<'de> for NoneAccess<E> {
720 type Error = E;
721 fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error> {
722 seed.deserialize(UnitAccess::new())
723 }
724}
725
726pub struct SomeAccess<D>(D);
728
729impl<D> SomeAccess<D> {
730 pub fn new(de: D) -> Self {
732 Self(de)
733 }
734}
735
736impl<'de, D: Deserializer<'de>> SumAccess<'de> for SomeAccess<D> {
737 type Error = D::Error;
738 type Variant = Self;
739
740 fn variant<V: VariantVisitor<'de>>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error> {
741 visitor.visit_name("some").map(|var| (var, self))
742 }
743}
744
745impl<'de, D: Deserializer<'de>> VariantAccess<'de> for SomeAccess<D> {
746 type Error = D::Error;
747 fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error> {
748 seed.deserialize(self.0)
749 }
750}
751
752pub struct UnitAccess<E>(PhantomData<E>);
755
756impl<E: Error> UnitAccess<E> {
757 pub fn new() -> Self {
759 Self(PhantomData)
760 }
761}
762
763impl<E: Error> Default for UnitAccess<E> {
764 fn default() -> Self {
765 Self::new()
766 }
767}
768
769impl<'de, E: Error> SeqProductAccess<'de> for UnitAccess<E> {
770 type Error = E;
771
772 fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, _seed: T) -> Result<Option<T::Output>, Self::Error> {
773 Ok(None)
774 }
775}
776
777impl<'de, E: Error> NamedProductAccess<'de> for UnitAccess<E> {
778 type Error = E;
779
780 fn get_field_ident<V: FieldNameVisitor<'de>>(&mut self, _visitor: V) -> Result<Option<V::Output>, Self::Error> {
781 Ok(None)
782 }
783
784 fn get_field_value_seed<T: DeserializeSeed<'de>>(&mut self, _seed: T) -> Result<T::Output, Self::Error> {
785 unreachable!()
786 }
787}
788
789impl<'de, E: Error> Deserializer<'de> for UnitAccess<E> {
790 type Error = E;
791
792 fn deserialize_product<V: ProductVisitor<'de>>(self, visitor: V) -> Result<V::Output, Self::Error> {
793 visitor.visit_seq_product(self)
794 }
795
796 fn deserialize_sum<V: SumVisitor<'de>>(self, _visitor: V) -> Result<V::Output, Self::Error> {
797 Err(E::custom("invalid type"))
798 }
799
800 fn deserialize_bool(self) -> Result<bool, Self::Error> {
801 Err(E::custom("invalid type"))
802 }
803
804 fn deserialize_u8(self) -> Result<u8, Self::Error> {
805 Err(E::custom("invalid type"))
806 }
807
808 fn deserialize_u16(self) -> Result<u16, Self::Error> {
809 Err(E::custom("invalid type"))
810 }
811
812 fn deserialize_u32(self) -> Result<u32, Self::Error> {
813 Err(E::custom("invalid type"))
814 }
815
816 fn deserialize_u64(self) -> Result<u64, Self::Error> {
817 Err(E::custom("invalid type"))
818 }
819
820 fn deserialize_u128(self) -> Result<u128, Self::Error> {
821 Err(E::custom("invalid type"))
822 }
823
824 fn deserialize_u256(self) -> Result<u256, Self::Error> {
825 Err(E::custom("invalid type"))
826 }
827
828 fn deserialize_i8(self) -> Result<i8, Self::Error> {
829 Err(E::custom("invalid type"))
830 }
831
832 fn deserialize_i16(self) -> Result<i16, Self::Error> {
833 Err(E::custom("invalid type"))
834 }
835
836 fn deserialize_i32(self) -> Result<i32, Self::Error> {
837 Err(E::custom("invalid type"))
838 }
839
840 fn deserialize_i64(self) -> Result<i64, Self::Error> {
841 Err(E::custom("invalid type"))
842 }
843
844 fn deserialize_i128(self) -> Result<i128, Self::Error> {
845 Err(E::custom("invalid type"))
846 }
847
848 fn deserialize_i256(self) -> Result<i256, Self::Error> {
849 Err(E::custom("invalid type"))
850 }
851
852 fn deserialize_f32(self) -> Result<f32, Self::Error> {
853 Err(E::custom("invalid type"))
854 }
855
856 fn deserialize_f64(self) -> Result<f64, Self::Error> {
857 Err(E::custom("invalid type"))
858 }
859
860 fn deserialize_str<V: SliceVisitor<'de, str>>(self, _visitor: V) -> Result<V::Output, Self::Error> {
861 Err(E::custom("invalid type"))
862 }
863
864 fn deserialize_bytes<V: SliceVisitor<'de, [u8]>>(self, _visitor: V) -> Result<V::Output, Self::Error> {
865 Err(E::custom("invalid type"))
866 }
867
868 fn deserialize_array_seed<V: ArrayVisitor<'de, T::Output>, T: DeserializeSeed<'de> + Clone>(
869 self,
870 _visitor: V,
871 _seed: T,
872 ) -> Result<V::Output, Self::Error> {
873 Err(E::custom("invalid type"))
874 }
875}