Skip to main content

spacetimedb_sats/de/
impls.rs

1use super::{
2    BasicSmallVecVisitor, BasicVecVisitor, Deserialize, DeserializeSeed, Deserializer, Error, FieldNameVisitor,
3    ProductKind, ProductVisitor, SeqProductAccess, SliceVisitor, SumAccess, SumVisitor, VariantAccess, VariantVisitor,
4};
5use crate::{
6    de::{array_visit, ArrayAccess, ArrayVisitor, GrowingVec},
7    AlgebraicType, AlgebraicValue, ArrayType, ArrayValue, ProductType, ProductTypeElement, ProductValue, SumType,
8    SumValue, WithTypespace, F32, F64,
9};
10use crate::{i256, u256};
11use core::{iter, marker::PhantomData, ops::Bound};
12use lean_string::LeanString;
13use smallvec::SmallVec;
14use spacetimedb_primitives::{ColId, ColList};
15use std::{borrow::Cow, rc::Rc, sync::Arc};
16
17/// Implements [`Deserialize`] for a type in a simplified manner.
18///
19/// An example:
20/// ```ignore
21/// impl_deserialize!(
22/// //     Type parameters  Optional where  Impl type
23/// //            v               v             v
24/// //   ----------------  --------------- ----------
25///     [T: Deserialize<'de>] where [T: Copy] std::rc::Rc<T>,
26/// //  The `deserialize` implementation where `de` is the `Deserializer<'de>`
27/// //  and the expression right of `=>` is the body of `deserialize`.
28///     de => T::deserialize(de).map(std::rc::Rc::new)
29/// );
30/// ```
31#[macro_export]
32macro_rules! impl_deserialize {
33    ([$($generics:tt)*] $(where [$($wc:tt)*])? $typ:ty, $de:ident => $body:expr) => {
34        impl<'de, $($generics)*> $crate::de::Deserialize<'de> for $typ {
35            fn deserialize<D: $crate::de::Deserializer<'de>>($de: D) -> Result<Self, D::Error> { $body }
36        }
37    };
38}
39
40/// Implements [`Deserialize`] for a primitive type.
41///
42/// The `$method` is a parameterless method on `deserializer` to call.
43macro_rules! impl_prim {
44    ($(($prim:ty, $method:ident))*) => {
45        $(impl_deserialize!([] $prim, de => de.$method());)*
46    };
47}
48
49impl_prim! {
50    (bool, deserialize_bool)
51    /*(u8, deserialize_u8)*/ (u16, deserialize_u16) (u32, deserialize_u32) (u64, deserialize_u64) (u128, deserialize_u128) (u256, deserialize_u256)
52    (i8, deserialize_i8)     (i16, deserialize_i16) (i32, deserialize_i32) (i64, deserialize_i64) (i128, deserialize_i128) (i256, deserialize_i256)
53    (f32, deserialize_f32) (f64, deserialize_f64)
54}
55
56struct TupleVisitor<A>(PhantomData<A>);
57#[derive(Copy, Clone)]
58struct TupleNameVisitorMax(usize);
59
60impl FieldNameVisitor<'_> for TupleNameVisitorMax {
61    // The index of the field name.
62    type Output = usize;
63
64    fn field_names(&self) -> impl '_ + Iterator<Item = Option<&str>> {
65        iter::repeat_n(None, self.0)
66    }
67
68    fn kind(&self) -> ProductKind {
69        ProductKind::Normal
70    }
71
72    fn visit<E: Error>(self, name: &str) -> Result<Self::Output, E> {
73        let err = || Error::unknown_field_name(name, &self);
74        // Convert `name` to an index.
75        let Ok(index) = name.parse() else {
76            return Err(err());
77        };
78        // Confirm that the index exists or error.
79        if index < self.0 {
80            Ok(index)
81        } else {
82            Err(err())
83        }
84    }
85
86    fn visit_seq(self, index: usize) -> Self::Output {
87        // Assert that the index exists.
88        assert!(index < self.0);
89        index
90    }
91}
92
93macro_rules! impl_deserialize_tuple {
94    ($($ty_name:ident => $const_val:literal),*) => {
95        impl<'de, $($ty_name: Deserialize<'de>),*> ProductVisitor<'de> for TupleVisitor<($($ty_name,)*)> {
96            type Output = ($($ty_name,)*);
97            fn product_name(&self) -> Option<&str> { None }
98            fn product_len(&self) -> usize { crate::count!($($ty_name)*) }
99            fn visit_seq_product<A: SeqProductAccess<'de>>(self, mut _prod: A) -> Result<Self::Output, A::Error> {
100                $(
101                    #[allow(non_snake_case)]
102                    let $ty_name = _prod
103                        .next_element()?
104                        .ok_or_else(|| Error::invalid_product_length($const_val, &self))?;
105                )*
106
107                Ok(($($ty_name,)*))
108            }
109            fn visit_named_product<A: super::NamedProductAccess<'de>>(self, mut prod: A) -> Result<Self::Output, A::Error> {
110                $(
111                    #[allow(non_snake_case)]
112                    let mut $ty_name = None;
113                )*
114
115                let visit = TupleNameVisitorMax(self.product_len());
116                while let Some(index) = prod.get_field_ident(visit)? {
117                    match index {
118                        $($const_val => {
119                            if $ty_name.is_some() {
120                                return Err(A::Error::duplicate_field($const_val, None, &self))
121                            }
122                            $ty_name = Some(prod.get_field_value()?);
123                        })*
124                        index => return Err(Error::invalid_product_length(index, &self)),
125                    }
126                }
127                Ok(($(
128                    $ty_name.ok_or_else(|| A::Error::missing_field($const_val, None, &self))?,
129                )*))
130            }
131        }
132
133        impl_deserialize!([$($ty_name: Deserialize<'de>),*] ($($ty_name,)*), de => {
134            de.deserialize_product(TupleVisitor::<($($ty_name,)*)>(PhantomData))
135        });
136    };
137}
138
139impl_deserialize_tuple!();
140impl_deserialize_tuple!(T0 => 0);
141impl_deserialize_tuple!(T0 => 0, T1 => 1);
142impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2);
143impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3);
144impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4);
145impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5);
146impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5, T6 => 6);
147impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5, T6 => 6, T7 => 7);
148impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5, T6 => 6, T7 => 7, T8 => 8);
149impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5, T6 => 6, T7 => 7, T8 => 8, T9 => 9);
150impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5, T6 => 6, T7 => 7, T8 => 8, T9 => 9, T10 => 10);
151impl_deserialize_tuple!(T0 => 0, T1 => 1, T2 => 2, T3 => 3, T4 => 4, T5 => 5, T6 => 6, T7 => 7, T8 => 8, T9 => 9, T10 => 10, T11 => 11);
152
153impl<'de> Deserialize<'de> for u8 {
154    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
155        deserializer.deserialize_u8()
156    }
157
158    // Specialize `Vec<u8>` deserialization.
159    // This is more likely to compile down to a `memcpy`.
160    fn __deserialize_vec<D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Self>, D::Error> {
161        deserializer.deserialize_bytes(OwnedSliceVisitor)
162    }
163
164    fn __deserialize_array<D: Deserializer<'de>, const N: usize>(deserializer: D) -> Result<[Self; N], D::Error> {
165        deserializer.deserialize_bytes(ByteArrayVisitor)
166    }
167}
168
169impl_deserialize!([] F32, de => f32::deserialize(de).map(Into::into));
170impl_deserialize!([] F64, de => f64::deserialize(de).map(Into::into));
171impl_deserialize!([] String, de => de.deserialize_str(OwnedSliceVisitor));
172impl_deserialize!([] LeanString, de => <Cow<'_, str>>::deserialize(de).map(|s| (&*s).into()));
173impl_deserialize!([T: Deserialize<'de>] Vec<T>, de => T::__deserialize_vec(de));
174impl_deserialize!([T: Deserialize<'de>, const N: usize] SmallVec<[T; N]>, de => {
175    de.deserialize_array(BasicSmallVecVisitor)
176});
177impl_deserialize!([T: Deserialize<'de>, const N: usize] [T; N], de => T::__deserialize_array(de));
178impl_deserialize!([] Box<str>, de => String::deserialize(de).map(|s| s.into_boxed_str()));
179impl_deserialize!([T: Deserialize<'de>] Box<[T]>, de => Vec::deserialize(de).map(|s| s.into_boxed_slice()));
180impl_deserialize!([T: Deserialize<'de>] Rc<[T]>, de => Vec::deserialize(de).map(|s| s.into()));
181impl_deserialize!([T: Deserialize<'de>] Arc<[T]>, de => Vec::deserialize(de).map(|s| s.into()));
182
183/// The visitor converts the slice to its owned version.
184struct OwnedSliceVisitor;
185
186impl<T: ToOwned + ?Sized> SliceVisitor<'_, T> for OwnedSliceVisitor {
187    type Output = T::Owned;
188
189    fn visit<E: Error>(self, slice: &T) -> Result<Self::Output, E> {
190        Ok(slice.to_owned())
191    }
192
193    fn visit_owned<E: Error>(self, buf: T::Owned) -> Result<Self::Output, E> {
194        Ok(buf)
195    }
196}
197
198/// The visitor will convert the byte slice to `[u8; N]`.
199///
200/// When `slice.len() != N` an error will be raised.
201struct ByteArrayVisitor<const N: usize>;
202
203impl<const N: usize> SliceVisitor<'_, [u8]> for ByteArrayVisitor<N> {
204    type Output = [u8; N];
205
206    fn visit<E: Error>(self, slice: &[u8]) -> Result<Self::Output, E> {
207        slice.try_into().map_err(|_| {
208            Error::custom(if slice.len() > N {
209                "too many elements for array"
210            } else {
211                "too few elements for array"
212            })
213        })
214    }
215}
216
217impl_deserialize!([] &'de str, de => de.deserialize_str(BorrowedSliceVisitor));
218impl_deserialize!([] &'de [u8], de => de.deserialize_bytes(BorrowedSliceVisitor));
219
220/// The visitor returns the slice as-is and borrowed.
221pub(crate) struct BorrowedSliceVisitor;
222
223impl<'de, T: ToOwned + ?Sized + 'de> SliceVisitor<'de, T> for BorrowedSliceVisitor {
224    type Output = &'de T;
225
226    fn visit<E: Error>(self, _: &T) -> Result<Self::Output, E> {
227        Err(E::custom("expected *borrowed* slice"))
228    }
229
230    fn visit_borrowed<E: Error>(self, borrowed_slice: &'de T) -> Result<Self::Output, E> {
231        Ok(borrowed_slice)
232    }
233}
234
235impl_deserialize!([] Cow<'de, str>, de => de.deserialize_str(CowSliceVisitor));
236impl_deserialize!([] Cow<'de, [u8]>, de => de.deserialize_bytes(CowSliceVisitor));
237
238/// The visitor works with either owned or borrowed versions to produce `Cow<'de, T>`.
239struct CowSliceVisitor;
240
241impl<'de, T: ToOwned + ?Sized + 'de> SliceVisitor<'de, T> for CowSliceVisitor {
242    type Output = Cow<'de, T>;
243
244    fn visit<E: Error>(self, slice: &T) -> Result<Self::Output, E> {
245        self.visit_owned(slice.to_owned())
246    }
247
248    fn visit_owned<E: Error>(self, buf: <T as ToOwned>::Owned) -> Result<Self::Output, E> {
249        Ok(Cow::Owned(buf))
250    }
251
252    fn visit_borrowed<E: Error>(self, borrowed_slice: &'de T) -> Result<Self::Output, E> {
253        Ok(Cow::Borrowed(borrowed_slice))
254    }
255}
256
257impl_deserialize!([T: Deserialize<'de>] Box<T>, de => T::deserialize(de).map(Box::new));
258impl_deserialize!([T: Deserialize<'de>] Option<T>, de => de.deserialize_sum(OptionVisitor(PhantomData)));
259
260/// The visitor deserializes an `Option<T>`.
261struct OptionVisitor<T>(PhantomData<T>);
262
263impl<'de, T: Deserialize<'de>> SumVisitor<'de> for OptionVisitor<T> {
264    type Output = Option<T>;
265
266    fn sum_name(&self) -> Option<&str> {
267        Some("option")
268    }
269
270    fn is_option(&self) -> bool {
271        true
272    }
273
274    fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error> {
275        // Determine the variant.
276        let (some, data) = data.variant(self)?;
277
278        // Deserialize contents for it.
279        Ok(if some {
280            Some(data.deserialize()?)
281        } else {
282            data.deserialize::<()>()?;
283            None
284        })
285    }
286}
287
288impl<'de, T: Deserialize<'de>> VariantVisitor<'de> for OptionVisitor<T> {
289    type Output = bool;
290
291    fn variant_names(&self) -> impl '_ + Iterator<Item = &str> {
292        ["some", "none"].into_iter()
293    }
294
295    fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E> {
296        match tag {
297            0 => Ok(true),
298            1 => Ok(false),
299            _ => Err(E::unknown_variant_tag(tag, &self)),
300        }
301    }
302
303    fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E> {
304        match name {
305            "some" => Ok(true),
306            "none" => Ok(false),
307            _ => Err(E::unknown_variant_name(name, &self)),
308        }
309    }
310}
311
312impl_deserialize!([T: Deserialize<'de>, E: Deserialize<'de>] Result<T, E>, de =>
313    de.deserialize_sum(ResultVisitor(PhantomData))
314);
315
316/// Visitor to deserialize a `Result<T, E>`.
317struct ResultVisitor<T, E>(PhantomData<(T, E)>);
318
319/// Variant determined by the [`VariantVisitor`] for `Result<T, E>`.
320enum ResultVariant {
321    Ok,
322    Err,
323}
324
325impl<'de, T: Deserialize<'de>, E: Deserialize<'de>> SumVisitor<'de> for ResultVisitor<T, E> {
326    type Output = Result<T, E>;
327
328    fn sum_name(&self) -> Option<&str> {
329        Some("result")
330    }
331
332    fn is_option(&self) -> bool {
333        false
334    }
335
336    fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error> {
337        let (variant, data) = data.variant(self)?;
338        Ok(match variant {
339            ResultVariant::Ok => Ok(data.deserialize()?),
340            ResultVariant::Err => Err(data.deserialize()?),
341        })
342    }
343}
344
345impl<'de, T: Deserialize<'de>, U: Deserialize<'de>> VariantVisitor<'de> for ResultVisitor<T, U> {
346    type Output = ResultVariant;
347
348    fn variant_names(&self) -> impl '_ + Iterator<Item = &str> {
349        ["ok", "err"].into_iter()
350    }
351
352    fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E> {
353        match tag {
354            0 => Ok(ResultVariant::Ok),
355            1 => Ok(ResultVariant::Err),
356            _ => Err(E::unknown_variant_tag(tag, &self)),
357        }
358    }
359
360    fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E> {
361        match name {
362            "ok" => Ok(ResultVariant::Ok),
363            "err" => Ok(ResultVariant::Err),
364            _ => Err(E::unknown_variant_name(name, &self)),
365        }
366    }
367}
368
369/// The visitor deserializes a `Bound<T>`.
370#[derive(Clone, Copy)]
371pub struct WithBound<S>(pub S);
372
373impl<'de, S: Copy + DeserializeSeed<'de>> DeserializeSeed<'de> for WithBound<S> {
374    type Output = Bound<S::Output>;
375
376    fn deserialize<D: Deserializer<'de>>(self, de: D) -> Result<Self::Output, D::Error> {
377        de.deserialize_sum(BoundVisitor(self.0))
378    }
379}
380
381/// The visitor deserializes a `Bound<T>`.
382struct BoundVisitor<S>(S);
383
384/// Variant determined by the [`BoundVisitor`] for `Bound<T>`.
385enum BoundVariant {
386    Included,
387    Excluded,
388    Unbounded,
389}
390
391impl<'de, S: Copy + DeserializeSeed<'de>> SumVisitor<'de> for BoundVisitor<S> {
392    type Output = Bound<S::Output>;
393
394    fn sum_name(&self) -> Option<&str> {
395        Some("bound")
396    }
397
398    fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error> {
399        // Determine the variant.
400        let this = self.0;
401        let (variant, data) = data.variant(self)?;
402
403        // Deserialize contents for it.
404        match variant {
405            BoundVariant::Included => data.deserialize_seed(this).map(Bound::Included),
406            BoundVariant::Excluded => data.deserialize_seed(this).map(Bound::Excluded),
407            BoundVariant::Unbounded => data.deserialize::<()>().map(|_| Bound::Unbounded),
408        }
409    }
410}
411
412impl<'de, T: Copy + DeserializeSeed<'de>> VariantVisitor<'de> for BoundVisitor<T> {
413    type Output = BoundVariant;
414
415    fn variant_names(&self) -> impl '_ + Iterator<Item = &str> {
416        ["included", "excluded", "unbounded"].into_iter()
417    }
418
419    fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E> {
420        match tag {
421            0 => Ok(BoundVariant::Included),
422            1 => Ok(BoundVariant::Excluded),
423            // if this ever changes, edit crates/bindings/src/table.rs
424            2 => Ok(BoundVariant::Unbounded),
425            _ => Err(E::unknown_variant_tag(tag, &self)),
426        }
427    }
428
429    fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E> {
430        match name {
431            "included" => Ok(BoundVariant::Included),
432            "excluded" => Ok(BoundVariant::Excluded),
433            "unbounded" => Ok(BoundVariant::Unbounded),
434            _ => Err(E::unknown_variant_name(name, &self)),
435        }
436    }
437}
438
439impl<'de> DeserializeSeed<'de> for WithTypespace<'_, AlgebraicType> {
440    type Output = AlgebraicValue;
441
442    fn deserialize<D: Deserializer<'de>>(self, de: D) -> Result<Self::Output, D::Error> {
443        match self.ty() {
444            AlgebraicType::Ref(r) => self.resolve(*r).deserialize(de),
445            AlgebraicType::Sum(sum) => self.with(sum).deserialize(de).map(Into::into),
446            AlgebraicType::Product(prod) => self.with(prod).deserialize(de).map(Into::into),
447            AlgebraicType::Array(ty) => self.with(ty).deserialize(de).map(Into::into),
448            AlgebraicType::Bool => bool::deserialize(de).map(Into::into),
449            AlgebraicType::I8 => i8::deserialize(de).map(Into::into),
450            AlgebraicType::U8 => u8::deserialize(de).map(Into::into),
451            AlgebraicType::I16 => i16::deserialize(de).map(Into::into),
452            AlgebraicType::U16 => u16::deserialize(de).map(Into::into),
453            AlgebraicType::I32 => i32::deserialize(de).map(Into::into),
454            AlgebraicType::U32 => u32::deserialize(de).map(Into::into),
455            AlgebraicType::I64 => i64::deserialize(de).map(Into::into),
456            AlgebraicType::U64 => u64::deserialize(de).map(Into::into),
457            AlgebraicType::I128 => i128::deserialize(de).map(Into::into),
458            AlgebraicType::U128 => u128::deserialize(de).map(Into::into),
459            AlgebraicType::I256 => i256::deserialize(de).map(Into::into),
460            AlgebraicType::U256 => u256::deserialize(de).map(Into::into),
461            AlgebraicType::F32 => f32::deserialize(de).map(Into::into),
462            AlgebraicType::F64 => f64::deserialize(de).map(Into::into),
463            AlgebraicType::String => <Box<str>>::deserialize(de).map(Into::into),
464        }
465    }
466}
467
468impl<'de> DeserializeSeed<'de> for WithTypespace<'_, SumType> {
469    type Output = SumValue;
470
471    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
472        deserializer.deserialize_sum(self)
473    }
474}
475
476impl<'de> SumVisitor<'de> for WithTypespace<'_, SumType> {
477    type Output = SumValue;
478
479    fn sum_name(&self) -> Option<&str> {
480        None
481    }
482
483    fn is_option(&self) -> bool {
484        self.ty().as_option().is_some()
485    }
486
487    fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error> {
488        let (tag, data) = data.variant(self)?;
489        // Find the variant type by `tag`.
490        let variant_ty = self.map(|ty| &ty.variants[tag as usize].algebraic_type);
491
492        let value = Box::new(data.deserialize_seed(variant_ty)?);
493        Ok(SumValue { tag, value })
494    }
495}
496
497impl VariantVisitor<'_> for WithTypespace<'_, SumType> {
498    type Output = u8;
499
500    fn variant_names(&self) -> impl '_ + Iterator<Item = &str> {
501        // Provide the names known from the `SumType`.
502        self.ty().variants.iter().filter_map(|v| v.name().map(|n| &**n))
503    }
504
505    fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E> {
506        // Verify that tag identifies a valid variant in `SumType`.
507        self.ty()
508            .variants
509            .get(tag as usize)
510            .ok_or_else(|| E::unknown_variant_tag(tag, &self))?;
511
512        Ok(tag)
513    }
514
515    fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E> {
516        // Translate the variant `name` to its tag.
517        self.ty()
518            .variants
519            .iter()
520            .position(|var| var.has_name(name))
521            .map(|pos| pos as u8)
522            .ok_or_else(|| E::unknown_variant_name(name, &self))
523    }
524}
525
526impl<'de> DeserializeSeed<'de> for WithTypespace<'_, ProductType> {
527    type Output = ProductValue;
528
529    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
530        deserializer.deserialize_product(self.map(|pt| &*pt.elements))
531    }
532}
533
534impl<'de> DeserializeSeed<'de> for WithTypespace<'_, [ProductTypeElement]> {
535    type Output = ProductValue;
536
537    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
538        deserializer.deserialize_product(self)
539    }
540}
541
542impl<'de> ProductVisitor<'de> for WithTypespace<'_, [ProductTypeElement]> {
543    type Output = ProductValue;
544
545    fn product_name(&self) -> Option<&str> {
546        None
547    }
548    fn product_len(&self) -> usize {
549        self.ty().len()
550    }
551
552    fn visit_seq_product<A: SeqProductAccess<'de>>(self, tup: A) -> Result<Self::Output, A::Error> {
553        visit_seq_product(self, &self, tup)
554    }
555
556    fn visit_named_product<A: super::NamedProductAccess<'de>>(self, tup: A) -> Result<Self::Output, A::Error> {
557        visit_named_product(self, &self, tup)
558    }
559}
560
561impl<'de> DeserializeSeed<'de> for WithTypespace<'_, ArrayType> {
562    type Output = ArrayValue;
563
564    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
565        /// Deserialize a vector and `map` it to the appropriate `ArrayValue` variant.
566        fn de_array<'de, D: Deserializer<'de>, T: Deserialize<'de>>(
567            de: D,
568            map: impl FnOnce(Box<[T]>) -> ArrayValue,
569        ) -> Result<ArrayValue, D::Error> {
570            de.deserialize_array(BasicVecVisitor).map(<Box<[_]>>::from).map(map)
571        }
572
573        let mut ty = &*self.ty().elem_ty;
574
575        // Loop, resolving `Ref`s, until we reach a non-`Ref` type.
576        loop {
577            break match ty {
578                AlgebraicType::Ref(r) => {
579                    // The only arm that will loop.
580                    ty = self.resolve(*r).ty();
581                    continue;
582                }
583                AlgebraicType::Sum(ty) => deserializer
584                    .deserialize_array_seed(BasicVecVisitor, self.with(ty))
585                    .map(<Box<[_]>>::from)
586                    .map(ArrayValue::Sum),
587                AlgebraicType::Product(ty) => deserializer
588                    .deserialize_array_seed(BasicVecVisitor, self.with(ty))
589                    .map(<Box<[_]>>::from)
590                    .map(ArrayValue::Product),
591                AlgebraicType::Array(ty) => deserializer
592                    .deserialize_array_seed(BasicVecVisitor, self.with(ty))
593                    .map(<Box<[_]>>::from)
594                    .map(ArrayValue::Array),
595                &AlgebraicType::Bool => de_array(deserializer, ArrayValue::Bool),
596                &AlgebraicType::I8 => de_array(deserializer, ArrayValue::I8),
597                &AlgebraicType::U8 => deserializer
598                    .deserialize_bytes(OwnedSliceVisitor)
599                    .map(<Box<[_]>>::from)
600                    .map(ArrayValue::U8),
601                &AlgebraicType::I16 => de_array(deserializer, ArrayValue::I16),
602                &AlgebraicType::U16 => de_array(deserializer, ArrayValue::U16),
603                &AlgebraicType::I32 => de_array(deserializer, ArrayValue::I32),
604                &AlgebraicType::U32 => de_array(deserializer, ArrayValue::U32),
605                &AlgebraicType::I64 => de_array(deserializer, ArrayValue::I64),
606                &AlgebraicType::U64 => de_array(deserializer, ArrayValue::U64),
607                &AlgebraicType::I128 => de_array(deserializer, ArrayValue::I128),
608                &AlgebraicType::U128 => de_array(deserializer, ArrayValue::U128),
609                &AlgebraicType::I256 => de_array(deserializer, ArrayValue::I256),
610                &AlgebraicType::U256 => de_array(deserializer, ArrayValue::U256),
611                &AlgebraicType::F32 => de_array(deserializer, ArrayValue::F32),
612                &AlgebraicType::F64 => de_array(deserializer, ArrayValue::F64),
613                &AlgebraicType::String => de_array(deserializer, ArrayValue::String),
614            };
615        }
616    }
617}
618
619// impl<'de> DeserializeSeed<'de> for &ReducerDef {
620//     type Output = ProductValue;
621
622//     fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
623//         deserializer.deserialize_product(self)
624//     }
625// }
626
627// impl<'de> ProductVisitor<'de> for &ReducerDef {
628//     type Output = ProductValue;
629
630//     fn product_name(&self) -> Option<&str> {
631//         self.name.as_deref()
632//     }
633//     fn product_len(&self) -> usize {
634//         self.args.len()
635//     }
636//     fn product_kind(&self) -> ProductKind {
637//         ProductKind::ReducerArgs
638//     }
639
640//     fn visit_seq_product<A: super::SeqProductAccess<'de>>(self, tup: A) -> Result<Self::Output, A::Error> {
641//         visit_seq_product(&self.args, &self, tup)
642//     }
643
644//     fn visit_named_product<A: super::NamedProductAccess<'de>>(self, tup: A) -> Result<Self::Output, A::Error> {
645//         visit_named_product(&self.args, &self, tup)
646//     }
647// }
648
649/// Deserialize, provided the fields' types, a product value with unnamed fields.
650pub fn visit_seq_product<'de, A: SeqProductAccess<'de>>(
651    elems: WithTypespace<[ProductTypeElement]>,
652    visitor: &impl ProductVisitor<'de>,
653    mut tup: A,
654) -> Result<ProductValue, A::Error> {
655    let elements = elems.ty().iter().enumerate().map(|(i, el)| {
656        tup.next_element_seed(elems.with(&el.algebraic_type))?
657            .ok_or_else(|| Error::invalid_product_length(i, visitor))
658    });
659    let elements = elements.collect::<Result<_, _>>()?;
660    Ok(ProductValue { elements })
661}
662
663/// Deserialize, provided the fields' types, a product value with named fields.
664pub fn visit_named_product<'de, A: super::NamedProductAccess<'de>>(
665    elems_tys: WithTypespace<[ProductTypeElement]>,
666    visitor: &impl ProductVisitor<'de>,
667    mut tup: A,
668) -> Result<ProductValue, A::Error> {
669    let elems = elems_tys.ty();
670    let mut elements = vec![None; elems.len()];
671    let kind = visitor.product_kind();
672
673    // Deserialize a product value corresponding to each product type field.
674    // This is worst case quadratic in complexity
675    // as fields can be specified out of order (value side) compared to `elems` (type side).
676    for _ in 0..elems.len() {
677        // Deserialize a field name, match against the element types.
678        let index = tup.get_field_ident(TupleNameVisitor { elems, kind })?.ok_or_else(|| {
679            // Couldn't deserialize a field name.
680            // Find the first field name we haven't filled an element for.
681            let missing = elements.iter().position(|field| field.is_none()).unwrap();
682            let field_name = elems[missing].name().map(|n| &**n);
683            Error::missing_field(missing, field_name, visitor)
684        })?;
685
686        let element = &elems[index];
687
688        // By index we can select which element to deserialize a value for.
689        let slot = &mut elements[index];
690        if slot.is_some() {
691            return Err(Error::duplicate_field(index, element.name().map(|n| &**n), visitor));
692        }
693
694        // Deserialize the value for this field's type.
695        *slot = Some(tup.get_field_value_seed(elems_tys.with(&element.algebraic_type))?);
696    }
697
698    // Get rid of the `Option<_>` layer.
699    let elements = elements
700        .into_iter()
701        // We reached here, so we know nothing was missing, i.e., `None`.
702        .map(|x| x.unwrap_or_else(|| unreachable!("visit_named_product")))
703        .collect();
704
705    Ok(ProductValue { elements })
706}
707
708/// A visitor for extracting indices of field names in the elements of a [`ProductType`].
709struct TupleNameVisitor<'a> {
710    /// The elements of a product type, in order.
711    elems: &'a [ProductTypeElement],
712    /// The kind of product this is.
713    kind: ProductKind,
714}
715
716impl FieldNameVisitor<'_> for TupleNameVisitor<'_> {
717    // The index of the field name.
718    type Output = usize;
719
720    fn field_names(&self) -> impl '_ + Iterator<Item = Option<&str>> {
721        self.elems.iter().map(|f| f.name().map(|n| &**n))
722    }
723
724    fn kind(&self) -> ProductKind {
725        self.kind
726    }
727
728    fn visit<E: Error>(self, name: &str) -> Result<Self::Output, E> {
729        // Finds the index of a field with `name`.
730        self.elems
731            .iter()
732            .position(|f| f.has_name(name))
733            .ok_or_else(|| Error::unknown_field_name(name, &self))
734    }
735
736    fn visit_seq(self, index: usize) -> Self::Output {
737        // Confirm that the index exists.
738        self.elems
739            .get(index)
740            .expect("`index` should exist when `visit_seq` is called");
741
742        index
743    }
744}
745
746impl_deserialize!([] spacetimedb_primitives::ArgId, de => u64::deserialize(de).map(Self));
747impl_deserialize!([] spacetimedb_primitives::TableId, de => u32::deserialize(de).map(Self));
748impl_deserialize!([] spacetimedb_primitives::ViewId, de => u32::deserialize(de).map(Self));
749impl_deserialize!([] spacetimedb_primitives::SequenceId, de => u32::deserialize(de).map(Self));
750impl_deserialize!([] spacetimedb_primitives::IndexId, de => u32::deserialize(de).map(Self));
751impl_deserialize!([] spacetimedb_primitives::ConstraintId, de => u32::deserialize(de).map(Self));
752impl_deserialize!([] spacetimedb_primitives::ColId, de => u16::deserialize(de).map(Self));
753impl_deserialize!([] spacetimedb_primitives::ScheduleId, de => u32::deserialize(de).map(Self));
754
755impl GrowingVec<ColId> for ColList {
756    fn with_capacity(cap: usize) -> Self {
757        Self::with_capacity(cap as u16)
758    }
759    fn push(&mut self, elem: ColId) {
760        self.push(elem);
761    }
762}
763impl_deserialize!([] spacetimedb_primitives::ColList, de => {
764    struct ColListVisitor;
765    impl<'de> ArrayVisitor<'de, ColId> for ColListVisitor {
766        type Output = ColList;
767
768        fn visit<A: ArrayAccess<'de, Element = ColId>>(self, vec: A) -> Result<Self::Output, A::Error> {
769            array_visit(vec)
770        }
771    }
772    de.deserialize_array(ColListVisitor)
773});
774impl_deserialize!([] spacetimedb_primitives::ColSet, de => ColList::deserialize(de).map(Into::into));
775
776#[cfg(feature = "blake3")]
777impl_deserialize!([] blake3::Hash, de => <[u8; blake3::OUT_LEN]>::deserialize(de).map(blake3::Hash::from_bytes));
778
779// TODO(perf): integrate Bytes with Deserializer to reduce copying
780impl_deserialize!([] bytes::Bytes, de => <Vec<u8>>::deserialize(de).map(Into::into));
781
782#[cfg(feature = "bytestring")]
783impl_deserialize!([] bytestring::ByteString, de => <String>::deserialize(de).map(Into::into));
784
785#[cfg(test)]
786mod test {
787    use crate::{
788        algebraic_value::{de::ValueDeserializer, ser::value_serialize},
789        bsatn,
790        serde::SerdeWrapper,
791        Deserialize, Serialize,
792    };
793    use core::fmt::Debug;
794
795    #[test]
796    fn roundtrip_tuples_in_different_data_formats() {
797        fn test<T: Serialize + for<'de> Deserialize<'de> + Eq + Debug>(x: T) {
798            let bsatn = bsatn::to_vec(&x).unwrap();
799            let y: T = bsatn::from_slice(&bsatn).unwrap();
800            assert_eq!(x, y);
801
802            let val = value_serialize(&x);
803            let y = T::deserialize(ValueDeserializer::new(val)).unwrap();
804            assert_eq!(x, y);
805
806            let json = serde_json::to_string(SerdeWrapper::from_ref(&x)).unwrap();
807            let SerdeWrapper(y) = serde_json::from_str::<SerdeWrapper<T>>(&json).unwrap();
808            assert_eq!(x, y);
809        }
810
811        test(());
812        test((true,));
813        test((1337u64, false));
814        test(((7331u64, false), 42u32, 24u8));
815    }
816}