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 match one_of_names(|| expected.field_names()) {
193 Some(one_of) => Self::custom(format_args!("unknown {el_ty} `{field_name}`, expected {one_of}")),
194 _ => Self::custom(format_args!("unknown {el_ty} `{field_name}`, there are no {el_ty}s")),
195 }
196 }
197
198 fn unknown_variant_tag<'de, T: SumVisitor<'de>>(tag: u8, expected: &T) -> Self {
200 Self::custom(format_args!(
201 "unknown tag {tag:#x} for sum type {}",
202 expected.sum_name().unwrap_or("<unknown>"),
203 ))
204 }
205
206 fn unknown_variant_name<'de, T: VariantVisitor<'de>>(name: &str, expected: &T) -> Self {
208 match one_of_names(|| expected.variant_names().map(Some)) {
209 Some(one_of) => Self::custom(format_args!("unknown variant `{name}`, expected {one_of}",)),
210 _ => Self::custom(format_args!("unknown variant `{name}`, there are no variants")),
211 }
212 }
213}
214
215pub struct FDisplay<F>(F);
217
218impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for FDisplay<F> {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 (self.0)(f)
221 }
222}
223
224pub fn fmt_fn<F: Fn(&mut fmt::Formatter) -> fmt::Result>(f: F) -> FDisplay<F> {
226 FDisplay(f)
227}
228
229fn error_on_field<'a, 'de>(
231 problem: &'static str,
232 index: usize,
233 name: Option<&'a str>,
234 prod: &impl ProductVisitor<'de>,
235) -> impl fmt::Display + 'a {
236 let field_kind = match prod.product_kind() {
237 ProductKind::Normal => "field",
238 ProductKind::ReducerArgs => "reducer argument",
239 };
240 fmt_fn(move |f| {
241 f.write_str(problem)?;
243 f.write_str(field_kind)?;
244 if let Some(name) = name {
245 write!(f, " `{name}`")
246 } else {
247 write!(f, " (index {index})")
248 }
249 })
250}
251
252fn fmt_invalid_len<'de>(
254 expected: &impl ProductVisitor<'de>,
255) -> FDisplay<impl '_ + Fn(&mut fmt::Formatter) -> fmt::Result> {
256 fmt_fn(|f| {
257 let ty = match expected.product_kind() {
258 ProductKind::Normal => "product type",
259 ProductKind::ReducerArgs => "reducer args for",
260 };
261 let name = expected.product_name().unwrap_or("<product>");
262 let len = expected.product_len();
263
264 write!(f, "{ty} {name} with {len} elements")
265 })
266}
267
268pub trait ProductVisitor<'de> {
270 type Output;
272
273 fn product_name(&self) -> Option<&str>;
275
276 fn product_len(&self) -> usize;
278
279 fn product_kind(&self) -> ProductKind {
281 ProductKind::Normal
282 }
283
284 fn visit_seq_product<A: SeqProductAccess<'de>>(self, prod: A) -> Result<Self::Output, A::Error>;
286
287 fn visit_named_product<A: NamedProductAccess<'de>>(self, prod: A) -> Result<Self::Output, A::Error>;
289}
290
291#[derive(Clone, Copy)]
293pub enum ProductKind {
294 Normal,
296 ReducerArgs,
298}
299
300pub trait SeqProductAccess<'de> {
304 type Error: Error;
306
307 fn next_element<T: Deserialize<'de>>(&mut self) -> Result<Option<T>, Self::Error> {
315 self.next_element_seed(PhantomData)
316 }
317
318 fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Output>, Self::Error>;
326}
327
328pub trait NamedProductAccess<'de> {
332 type Error: Error;
334
335 fn get_field_ident<V: FieldNameVisitor<'de>>(&mut self, visitor: V) -> Result<Option<V::Output>, Self::Error>;
338
339 fn get_field_value<T: Deserialize<'de>>(&mut self) -> Result<T, Self::Error> {
344 self.get_field_value_seed(PhantomData)
345 }
346
347 fn get_field_value_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<T::Output, Self::Error>;
352}
353
354pub trait FieldNameVisitor<'de> {
356 type Output;
358
359 fn kind(&self) -> ProductKind {
361 ProductKind::Normal
362 }
363
364 fn field_names(&self) -> impl '_ + Iterator<Item = Option<&str>>;
368
369 fn visit<E: Error>(self, name: &str) -> Result<Self::Output, E>;
371
372 fn visit_seq(self, index: usize) -> Self::Output;
377}
378
379pub trait SumVisitor<'de> {
384 type Output;
386
387 fn sum_name(&self) -> Option<&str>;
389
390 fn is_option(&self) -> bool {
394 false
395 }
396
397 fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error>;
407}
408
409pub trait SumAccess<'de> {
415 type Error: Error;
417
418 type Variant: VariantAccess<'de, Error = Self::Error>;
420
421 fn variant<V: VariantVisitor<'de>>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error>;
429}
430
431pub trait VariantVisitor<'de> {
434 type Output;
436
437 fn variant_names(&self) -> impl '_ + Iterator<Item = &str>;
439
440 fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E>;
442
443 fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E>;
445}
446
447pub trait VariantAccess<'de>: Sized {
450 type Error: Error;
451
452 fn deserialize<T: Deserialize<'de>>(self) -> Result<T, Self::Error> {
456 self.deserialize_seed(PhantomData)
457 }
458
459 fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error>;
461}
462
463pub trait SliceVisitor<'de, T: ToOwned + ?Sized>: Sized {
466 type Output;
468
469 fn visit<E: Error>(self, slice: &T) -> Result<Self::Output, E>;
474
475 fn visit_owned<E: Error>(self, buf: T::Owned) -> Result<Self::Output, E> {
477 self.visit(buf.borrow())
478 }
479
480 fn visit_borrowed<E: Error>(self, borrowed_slice: &'de T) -> Result<Self::Output, E> {
482 self.visit(borrowed_slice)
483 }
484}
485
486pub trait ArrayVisitor<'de, T> {
488 type Output;
490
491 fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error>;
493}
494
495pub trait ArrayAccess<'de> {
499 type Element;
501
502 type Error: Error;
504
505 fn next_element(&mut self) -> Result<Option<Self::Element>, Self::Error>;
508
509 fn size_hint(&self) -> Option<usize> {
511 None
512 }
513}
514
515pub trait DeserializeSeed<'de> {
517 type Output;
519
520 fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error>;
523}
524
525use crate::de::impls::BorrowedSliceVisitor;
526pub use spacetimedb_bindings_macro::Deserialize;
527
528pub trait Deserialize<'de>: Sized {
543 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>;
545
546 #[doc(hidden)]
547 fn deserialize_from_bsatn<R: BufReader<'de>>(
549 deserializer: bsatn::Deserializer<'de, R>,
550 ) -> Result<Self, bsatn::DecodeError> {
551 Self::deserialize(deserializer)
552 }
553
554 #[doc(hidden)]
556 #[inline(always)]
557 fn __deserialize_vec<D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Self>, D::Error> {
558 deserializer.deserialize_array(BasicVecVisitor)
559 }
560
561 #[doc(hidden)]
562 #[inline(always)]
563 fn __deserialize_array<D: Deserializer<'de>, const N: usize>(deserializer: D) -> Result<[Self; N], D::Error> {
564 deserializer.deserialize_array(BasicArrayVisitor)
565 }
566}
567
568pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
571impl<T: for<'de> Deserialize<'de>> DeserializeOwned for T {}
572
573impl<'de, T: Deserialize<'de>> DeserializeSeed<'de> for PhantomData<T> {
574 type Output = T;
575
576 fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
577 T::deserialize(deserializer)
578 }
579}
580
581pub trait GrowingVec<T> {
583 fn with_capacity(cap: usize) -> Self;
585
586 fn push(&mut self, elem: T);
588}
589
590impl<T> GrowingVec<T> for Vec<T> {
591 fn with_capacity(cap: usize) -> Self {
592 Self::with_capacity(cap)
593 }
594 fn push(&mut self, elem: T) {
595 self.push(elem)
596 }
597}
598
599impl<T, const N: usize> GrowingVec<T> for SmallVec<[T; N]> {
600 fn with_capacity(cap: usize) -> Self {
601 Self::with_capacity(cap)
602 }
603 fn push(&mut self, elem: T) {
604 self.push(elem)
605 }
606}
607
608pub fn array_visit<'de, A: ArrayAccess<'de>, V: GrowingVec<A::Element>>(mut access: A) -> Result<V, A::Error> {
610 let mut v = V::with_capacity(access.size_hint().unwrap_or(0));
611 while let Some(x) = access.next_element()? {
612 v.push(x)
613 }
614 Ok(v)
615}
616
617pub struct BasicVecVisitor;
619
620impl<'de, T> ArrayVisitor<'de, T> for BasicVecVisitor {
621 type Output = Vec<T>;
622
623 fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error> {
624 array_visit(vec)
625 }
626}
627
628pub struct BasicSmallVecVisitor<const N: usize>;
630
631impl<'de, T, const N: usize> ArrayVisitor<'de, T> for BasicSmallVecVisitor<N> {
632 type Output = SmallVec<[T; N]>;
633
634 fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error> {
635 array_visit(vec)
636 }
637}
638
639struct BasicArrayVisitor<const N: usize>;
641
642impl<'de, T, const N: usize> ArrayVisitor<'de, T> for BasicArrayVisitor<N> {
643 type Output = [T; N];
644
645 fn visit<A: ArrayAccess<'de, Element = T>>(self, mut vec: A) -> Result<Self::Output, A::Error> {
646 let mut v = arrayvec::ArrayVec::<T, N>::new();
647 while let Some(el) = vec.next_element()? {
648 v.try_push(el)
649 .map_err(|_| Error::custom("too many elements for array"))?
650 }
651 v.into_inner().map_err(|_| Error::custom("too few elements for array"))
652 }
653}
654
655fn one_of_names<'a, I: Iterator<Item = Option<&'a str>>>(names: impl Fn() -> I) -> Option<impl fmt::Display> {
659 let count = names().count();
661
662 (count != 0).then(move || {
664 fmt_fn(move |f| {
665 let mut anon_name = 0;
666 for (index, mut name) in names().enumerate() {
672 let mut name_buf: String = String::new();
673 let name = name.get_or_insert_with(|| {
674 name_buf = format!("{anon_name}");
675 anon_name += 1;
676 &name_buf
677 });
678 match (count, index) {
679 (1, _) => write!(f, "`{name}`"),
680 (2, 1) => write!(f, "`{name}`"),
681 (2, 2) => write!(f, "`or `{name}`"),
682 (_, 1) => write!(f, "one of `{name}`"),
683 (c, i) if i < c => write!(f, ", `{name}`"),
684 (_, _) => write!(f, ", `, or {name}`"),
685 }?;
686 }
687
688 Ok(())
689 })
690 })
691}
692
693pub struct NoneAccess<E>(PhantomData<E>);
695
696impl<E: Error> NoneAccess<E> {
697 pub fn new() -> Self {
699 Self(PhantomData)
700 }
701}
702
703impl<E: Error> Default for NoneAccess<E> {
704 fn default() -> Self {
705 Self::new()
706 }
707}
708
709impl<'de, E: Error> SumAccess<'de> for NoneAccess<E> {
710 type Error = E;
711 type Variant = Self;
712
713 fn variant<V: VariantVisitor<'de>>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error> {
714 visitor.visit_name("none").map(|var| (var, self))
715 }
716}
717impl<'de, E: Error> VariantAccess<'de> for NoneAccess<E> {
718 type Error = E;
719 fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error> {
720 seed.deserialize(UnitAccess::new())
721 }
722}
723
724pub struct SomeAccess<D>(D);
726
727impl<D> SomeAccess<D> {
728 pub fn new(de: D) -> Self {
730 Self(de)
731 }
732}
733
734impl<'de, D: Deserializer<'de>> SumAccess<'de> for SomeAccess<D> {
735 type Error = D::Error;
736 type Variant = Self;
737
738 fn variant<V: VariantVisitor<'de>>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error> {
739 visitor.visit_name("some").map(|var| (var, self))
740 }
741}
742
743impl<'de, D: Deserializer<'de>> VariantAccess<'de> for SomeAccess<D> {
744 type Error = D::Error;
745 fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error> {
746 seed.deserialize(self.0)
747 }
748}
749
750pub struct UnitAccess<E>(PhantomData<E>);
753
754impl<E: Error> UnitAccess<E> {
755 pub fn new() -> Self {
757 Self(PhantomData)
758 }
759}
760
761impl<E: Error> Default for UnitAccess<E> {
762 fn default() -> Self {
763 Self::new()
764 }
765}
766
767impl<'de, E: Error> SeqProductAccess<'de> for UnitAccess<E> {
768 type Error = E;
769
770 fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, _seed: T) -> Result<Option<T::Output>, Self::Error> {
771 Ok(None)
772 }
773}
774
775impl<'de, E: Error> NamedProductAccess<'de> for UnitAccess<E> {
776 type Error = E;
777
778 fn get_field_ident<V: FieldNameVisitor<'de>>(&mut self, _visitor: V) -> Result<Option<V::Output>, Self::Error> {
779 Ok(None)
780 }
781
782 fn get_field_value_seed<T: DeserializeSeed<'de>>(&mut self, _seed: T) -> Result<T::Output, Self::Error> {
783 unreachable!()
784 }
785}
786
787impl<'de, E: Error> Deserializer<'de> for UnitAccess<E> {
788 type Error = E;
789
790 fn deserialize_product<V: ProductVisitor<'de>>(self, visitor: V) -> Result<V::Output, Self::Error> {
791 visitor.visit_seq_product(self)
792 }
793
794 fn deserialize_sum<V: SumVisitor<'de>>(self, _visitor: V) -> Result<V::Output, Self::Error> {
795 Err(E::custom("invalid type"))
796 }
797
798 fn deserialize_bool(self) -> Result<bool, Self::Error> {
799 Err(E::custom("invalid type"))
800 }
801
802 fn deserialize_u8(self) -> Result<u8, Self::Error> {
803 Err(E::custom("invalid type"))
804 }
805
806 fn deserialize_u16(self) -> Result<u16, Self::Error> {
807 Err(E::custom("invalid type"))
808 }
809
810 fn deserialize_u32(self) -> Result<u32, Self::Error> {
811 Err(E::custom("invalid type"))
812 }
813
814 fn deserialize_u64(self) -> Result<u64, Self::Error> {
815 Err(E::custom("invalid type"))
816 }
817
818 fn deserialize_u128(self) -> Result<u128, Self::Error> {
819 Err(E::custom("invalid type"))
820 }
821
822 fn deserialize_u256(self) -> Result<u256, Self::Error> {
823 Err(E::custom("invalid type"))
824 }
825
826 fn deserialize_i8(self) -> Result<i8, Self::Error> {
827 Err(E::custom("invalid type"))
828 }
829
830 fn deserialize_i16(self) -> Result<i16, Self::Error> {
831 Err(E::custom("invalid type"))
832 }
833
834 fn deserialize_i32(self) -> Result<i32, Self::Error> {
835 Err(E::custom("invalid type"))
836 }
837
838 fn deserialize_i64(self) -> Result<i64, Self::Error> {
839 Err(E::custom("invalid type"))
840 }
841
842 fn deserialize_i128(self) -> Result<i128, Self::Error> {
843 Err(E::custom("invalid type"))
844 }
845
846 fn deserialize_i256(self) -> Result<i256, Self::Error> {
847 Err(E::custom("invalid type"))
848 }
849
850 fn deserialize_f32(self) -> Result<f32, Self::Error> {
851 Err(E::custom("invalid type"))
852 }
853
854 fn deserialize_f64(self) -> Result<f64, Self::Error> {
855 Err(E::custom("invalid type"))
856 }
857
858 fn deserialize_str<V: SliceVisitor<'de, str>>(self, _visitor: V) -> Result<V::Output, Self::Error> {
859 Err(E::custom("invalid type"))
860 }
861
862 fn deserialize_bytes<V: SliceVisitor<'de, [u8]>>(self, _visitor: V) -> Result<V::Output, Self::Error> {
863 Err(E::custom("invalid type"))
864 }
865
866 fn deserialize_array_seed<V: ArrayVisitor<'de, T::Output>, T: DeserializeSeed<'de> + Clone>(
867 self,
868 _visitor: V,
869 _seed: T,
870 ) -> Result<V::Output, Self::Error> {
871 Err(E::custom("invalid type"))
872 }
873}