spacetimedb_sats/
de.rs

1// Some parts copyright Serde developers under the MIT / Apache-2.0 licenses at your option.
2// See `serde` version `v1.0.169` for the parts where MIT / Apache-2.0 applies.
3
4mod impls;
5#[cfg(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
18/// A data format that can deserialize any data structure supported by SATS.
19///
20/// The `Deserializer` trait in SATS performs the same function as `serde::Deserializer` in [`serde`].
21/// See the documentation of `serde::Deserializer` for more information of the data model.
22///
23/// Implementations of `Deserialize` map themselves into this data model
24/// by passing to the `Deserializer` a visitor that can receive the necessary types.
25/// The kind of visitor depends on the `deserialize_*` method.
26/// Unlike in Serde, there isn't a single monolithic `Visitor` trait,
27/// but rather, this functionality is split up into more targeted traits such as `SumVisitor<'de>`.
28///
29/// The lifetime `'de` allows us to deserialize lifetime-generic types in a zero-copy fashion.
30///
31/// [`serde`]: https://crates.io/crates/serde
32pub trait Deserializer<'de>: Sized {
33    /// The error type that can be returned if some error occurs during deserialization.
34    type Error: Error;
35
36    /// Deserializes a product value from the input.
37    fn deserialize_product<V: ProductVisitor<'de>>(self, visitor: V) -> Result<V::Output, Self::Error>;
38
39    /// Deserializes a sum value from the input.
40    ///
41    /// The entire process of deserializing a sum, starting from `deserialize(args...)`, is roughly:
42    ///
43    /// - [`deserialize`][Deserialize::deserialize] calls this method,
44    ///   [`deserialize_sum(sum_visitor)`](Deserializer::deserialize_sum),
45    ///   providing us with a [`sum_visitor`](SumVisitor).
46    ///
47    /// - This method calls [`sum_visitor.visit_sum(sum_access)`](SumVisitor::visit_sum),
48    ///   where [`sum_access`](SumAccess) deals with extracting the tag and the variant data,
49    ///   with the latter provided as [`VariantAccess`]).
50    ///   The `SumVisitor` will then assemble these into the representation of a sum value
51    ///   that the [`Deserialize`] implementation wants.
52    ///
53    /// - [`visit_sum`](SumVisitor::visit_sum) then calls
54    ///   [`sum_access.variant(variant_visitor)`](SumAccess::variant),
55    ///   and uses the provided `variant_visitor` to translate extracted variant names / tags
56    ///   into something that is meaningful for `visit_sum`, e.g., an index.
57    ///
58    ///   The call to `variant` will also return [`variant_access`](VariantAccess)
59    ///   that can deserialize the contents of the variant.
60    ///
61    /// - Finally, after `variant` returns,
62    ///   `visit_sum` deserializes the variant data using
63    ///   [`variant_access.deserialize_seed(seed)`](VariantAccess::deserialize_seed)
64    ///   or [`variant_access.deserialize()`](VariantAccess::deserialize).
65    ///   This part may require some conditional logic depending on the identified variant.
66    ///
67    ///
68    /// The data format will also return an object ([`VariantAccess`])
69    /// that can deserialize the contents of the variant.
70    fn deserialize_sum<V: SumVisitor<'de>>(self, visitor: V) -> Result<V::Output, Self::Error>;
71
72    /// Deserializes a `bool` value from the input.
73    fn deserialize_bool(self) -> Result<bool, Self::Error>;
74
75    /// Deserializes a `u8` value from the input.
76    fn deserialize_u8(self) -> Result<u8, Self::Error>;
77
78    /// Deserializes a `u16` value from the input.
79    fn deserialize_u16(self) -> Result<u16, Self::Error>;
80
81    /// Deserializes a `u32` value from the input.
82    fn deserialize_u32(self) -> Result<u32, Self::Error>;
83
84    /// Deserializes a `u64` value from the input.
85    fn deserialize_u64(self) -> Result<u64, Self::Error>;
86
87    /// Deserializes a `u128` value from the input.
88    fn deserialize_u128(self) -> Result<u128, Self::Error>;
89
90    /// Deserializes a `u256` value from the input.
91    fn deserialize_u256(self) -> Result<u256, Self::Error>;
92
93    /// Deserializes an `i8` value from the input.
94    fn deserialize_i8(self) -> Result<i8, Self::Error>;
95
96    /// Deserializes an `i16` value from the input.
97    fn deserialize_i16(self) -> Result<i16, Self::Error>;
98
99    /// Deserializes an `i32` value from the input.
100    fn deserialize_i32(self) -> Result<i32, Self::Error>;
101
102    /// Deserializes an `i64` value from the input.
103    fn deserialize_i64(self) -> Result<i64, Self::Error>;
104
105    /// Deserializes an `i128` value from the input.
106    fn deserialize_i128(self) -> Result<i128, Self::Error>;
107
108    /// Deserializes an `i256` value from the input.
109    fn deserialize_i256(self) -> Result<i256, Self::Error>;
110
111    /// Deserializes an `f32` value from the input.
112    fn deserialize_f32(self) -> Result<f32, Self::Error>;
113
114    /// Deserializes an `f64` value from the input.
115    fn deserialize_f64(self) -> Result<f64, Self::Error>;
116
117    /// Deserializes a string-like object the input.
118    fn deserialize_str<V: SliceVisitor<'de, str>>(self, visitor: V) -> Result<V::Output, Self::Error>;
119
120    /// Deserializes an `&str` string value.
121    fn deserialize_str_slice(self) -> Result<&'de str, Self::Error> {
122        self.deserialize_str(BorrowedSliceVisitor)
123    }
124
125    /// Deserializes a byte slice-like value.
126    fn deserialize_bytes<V: SliceVisitor<'de, [u8]>>(self, visitor: V) -> Result<V::Output, Self::Error>;
127
128    /// Deserializes an array value.
129    ///
130    /// This is typically the same as [`deserialize_array_seed`](Deserializer::deserialize_array_seed)
131    /// with an uninteresting `seed` value.
132    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    /// Deserializes an array value.
140    ///
141    /// The deserialization is provided with a `seed` value.
142    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
149/// The `Error` trait allows [`Deserialize`] implementations to create descriptive error messages
150/// belonging to the [`Deserializer`] against which they are currently running.
151///
152/// Every [`Deserializer`] declares an [`Error`] type
153/// that encompasses both general-purpose deserialization errors
154/// as well as errors specific to the particular deserialization format.
155///
156/// Most deserializers should only need to provide the [`Error::custom`] method
157/// and inherit the default behavior for the other methods.
158pub trait Error: Sized {
159    /// Raised when there is general error when deserializing a type.
160    fn custom(msg: impl fmt::Display) -> Self;
161
162    /// The product length was not as promised.
163    fn invalid_product_length<'de, T: ProductVisitor<'de>>(len: usize, expected: &T) -> Self {
164        Self::custom(format_args!(
165            "invalid length {}, expected {}",
166            len,
167            fmt_invalid_len(expected)
168        ))
169    }
170
171    /// There was a missing field at `index`.
172    fn missing_field<'de, T: ProductVisitor<'de>>(index: usize, field_name: Option<&str>, prod: &T) -> Self {
173        Self::custom(error_on_field("missing ", index, field_name, prod))
174    }
175
176    /// A field with `index` was specified more than once.
177    fn duplicate_field<'de, T: ProductVisitor<'de>>(index: usize, field_name: Option<&str>, prod: &T) -> Self {
178        Self::custom(error_on_field("duplicate ", index, field_name, prod))
179    }
180
181    /// A field with name `field_name` does not exist.
182    fn unknown_field_name<'de, T: FieldNameVisitor<'de>>(field_name: &str, expected: &T) -> Self {
183        let el_ty = match expected.kind() {
184            ProductKind::Normal => "field",
185            ProductKind::ReducerArgs => "reducer argument",
186        };
187        if let Some(one_of) = one_of_names(|n| expected.field_names(n)) {
188            Self::custom(format_args!("unknown {el_ty} `{field_name}`, expected {one_of}"))
189        } else {
190            Self::custom(format_args!("unknown {el_ty} `{field_name}`, there are no {el_ty}s"))
191        }
192    }
193
194    /// The `tag` does not specify a variant of the sum type.
195    fn unknown_variant_tag<'de, T: SumVisitor<'de>>(tag: u8, expected: &T) -> Self {
196        Self::custom(format_args!(
197            "unknown tag {tag:#x} for sum type {}",
198            expected.sum_name().unwrap_or("<unknown>"),
199        ))
200    }
201
202    /// The `name` is not that of a variant of the sum type.
203    fn unknown_variant_name<T: VariantVisitor>(name: &str, expected: &T) -> Self {
204        if let Some(one_of) = one_of_names(|n| expected.variant_names(n)) {
205            Self::custom(format_args!("unknown variant `{name}`, expected {one_of}",))
206        } else {
207            Self::custom(format_args!("unknown variant `{name}`, there are no variants"))
208        }
209    }
210}
211
212/// Turns a closure `impl Fn(&mut Formatter) -> Result` into a `Display`able object.
213pub struct FDisplay<F>(F);
214
215impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Display for FDisplay<F> {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        (self.0)(f)
218    }
219}
220
221/// Turns a closure `F: Fn(&mut Formatter) -> Result` into a `Display`able object.
222pub fn fmt_fn<F: Fn(&mut fmt::Formatter) -> fmt::Result>(f: F) -> FDisplay<F> {
223    FDisplay(f)
224}
225
226/// Returns an error message for a `problem` with field at `index` and an optional `name`.
227fn error_on_field<'a, 'de>(
228    problem: &'static str,
229    index: usize,
230    name: Option<&'a str>,
231    prod: &impl ProductVisitor<'de>,
232) -> impl fmt::Display + 'a {
233    let field_kind = match prod.product_kind() {
234        ProductKind::Normal => "field",
235        ProductKind::ReducerArgs => "reducer argument",
236    };
237    fmt_fn(move |f| {
238        // e.g. "missing field `foo`"
239        f.write_str(problem)?;
240        f.write_str(field_kind)?;
241        if let Some(name) = name {
242            write!(f, " `{}`", name)
243        } else {
244            write!(f, " (index {})", index)
245        }
246    })
247}
248
249/// Returns an error message for invalid product type lengths.
250fn fmt_invalid_len<'de>(
251    expected: &impl ProductVisitor<'de>,
252) -> FDisplay<impl '_ + Fn(&mut fmt::Formatter) -> fmt::Result> {
253    fmt_fn(|f| {
254        let ty = match expected.product_kind() {
255            ProductKind::Normal => "product type",
256            ProductKind::ReducerArgs => "reducer args for",
257        };
258        let name = expected.product_name().unwrap_or("<product>");
259        let len = expected.product_len();
260
261        write!(f, "{ty} {name} with {len} elements")
262    })
263}
264
265/// A visitor walking through a [`Deserializer`] for products.
266pub trait ProductVisitor<'de> {
267    /// The resulting product.
268    type Output;
269
270    /// Returns the name of the product, if any.
271    fn product_name(&self) -> Option<&str>;
272
273    /// Returns the length of the product.
274    fn product_len(&self) -> usize;
275
276    /// Returns the kind of the product.
277    fn product_kind(&self) -> ProductKind {
278        ProductKind::Normal
279    }
280
281    /// The input contains an unnamed product.
282    fn visit_seq_product<A: SeqProductAccess<'de>>(self, prod: A) -> Result<Self::Output, A::Error>;
283
284    /// The input contains a named product.
285    fn visit_named_product<A: NamedProductAccess<'de>>(self, prod: A) -> Result<Self::Output, A::Error>;
286}
287
288/// What kind of product is this?
289#[derive(Clone, Copy)]
290pub enum ProductKind {
291    // A normal product.
292    Normal,
293    /// A product in the context of reducer arguments.
294    ReducerArgs,
295}
296
297/// Provides a [`ProductVisitor`] with access to each element of the unnamed product in the input.
298///
299/// This is a trait that a [`Deserializer`] passes to a [`ProductVisitor`] implementation.
300pub trait SeqProductAccess<'de> {
301    /// The error type that can be returned if some error occurs during deserialization.
302    type Error: Error;
303
304    /// Deserializes an `T` from the input.
305    ///
306    /// Returns `Ok(Some(value))` for the next element in the product,
307    /// or `Ok(None)` if there are no more remaining items.
308    ///
309    /// This method exists as a convenience for [`Deserialize`] implementations.
310    /// [`SeqProductAccess`] implementations should not override the default behavior.
311    fn next_element<T: Deserialize<'de>>(&mut self) -> Result<Option<T>, Self::Error> {
312        self.next_element_seed(PhantomData)
313    }
314
315    /// Statefully deserializes `T::Output` from the input provided a `seed` value.
316    ///
317    /// Returns `Ok(Some(value))` for the next element in the unnamed product,
318    /// or `Ok(None)` if there are no more remaining items.
319    ///
320    /// [`Deserialize`] implementations should typically use
321    /// [`next_element`](SeqProductAccess::next_element) instead.
322    fn next_element_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<Option<T::Output>, Self::Error>;
323}
324
325/// Provides a [`ProductVisitor`] with access to each element of the named product in the input.
326///
327/// This is a trait that a [`Deserializer`] passes to a [`ProductVisitor`] implementation.
328pub trait NamedProductAccess<'de> {
329    /// The error type that can be returned if some error occurs during deserialization.
330    type Error: Error;
331
332    /// Deserializes field name of type `V::Output` from the input using a visitor
333    /// provided by the deserializer.
334    fn get_field_ident<V: FieldNameVisitor<'de>>(&mut self, visitor: V) -> Result<Option<V::Output>, Self::Error>;
335
336    /// Deserializes field value of type `T` from the input.
337    ///
338    /// This method exists as a convenience for [`Deserialize`] implementations.
339    /// [`NamedProductAccess`] implementations should not override the default behavior.
340    fn get_field_value<T: Deserialize<'de>>(&mut self) -> Result<T, Self::Error> {
341        self.get_field_value_seed(PhantomData)
342    }
343
344    /// Statefully deserializes the field value `T::Output` from the input provided a `seed` value.
345    ///
346    /// [`Deserialize`] implementations should typically use
347    /// [`next_element`](NamedProductAccess::get_field_value) instead.
348    fn get_field_value_seed<T: DeserializeSeed<'de>>(&mut self, seed: T) -> Result<T::Output, Self::Error>;
349}
350
351/// Visitor used to deserialize the name of a field.
352pub trait FieldNameVisitor<'de> {
353    /// The resulting field name.
354    type Output;
355
356    /// The sort of product deserialized.
357    fn kind(&self) -> ProductKind {
358        ProductKind::Normal
359    }
360
361    /// Provides the visitor the chance to add valid names into `names`.
362    fn field_names(&self, names: &mut dyn ValidNames);
363
364    fn visit<E: Error>(self, name: &str) -> Result<Self::Output, E>;
365}
366
367/// A trait for types storing a set of valid names.
368pub trait ValidNames {
369    /// Adds the name `s` to the set.
370    fn push(&mut self, s: &str);
371
372    /// Runs the function `names` provided with `self` as the store
373    /// and then returns back `self`.
374    /// This method exists for convenience.
375    fn run(mut self, names: &impl Fn(&mut dyn ValidNames)) -> Self
376    where
377        Self: Sized,
378    {
379        names(&mut self);
380        self
381    }
382}
383
384impl dyn ValidNames + '_ {
385    /// Adds the names in `iter` to the set.
386    pub fn extend<I: IntoIterator>(&mut self, iter: I)
387    where
388        I::Item: AsRef<str>,
389    {
390        for name in iter {
391            self.push(name.as_ref())
392        }
393    }
394}
395
396/// A visitor walking through a [`Deserializer`] for sums.
397///
398/// This side is provided by a [`Deserialize`] implementation
399/// when calling [`Deserializer::deserialize_sum`].
400pub trait SumVisitor<'de> {
401    /// The resulting sum.
402    type Output;
403
404    /// Returns the name of the sum, if any.
405    fn sum_name(&self) -> Option<&str>;
406
407    /// Returns whether an option is expected.
408    ///
409    /// The provided implementation does not.
410    fn is_option(&self) -> bool {
411        false
412    }
413
414    /// Drives the deserialization of a sum value.
415    ///
416    /// This method will ask the data format ([`A: SumAccess`][SumAccess])
417    /// which variant of the sum to select in terms of a variant name / tag.
418    /// `A` will use a [`VariantVisitor`], that `SumVisitor` has provided,
419    /// to translate into something that is meaningful for `visit_sum`, e.g., an index.
420    ///
421    /// The data format will also return an object ([`VariantAccess`])
422    /// that can deserialize the contents of the variant.
423    fn visit_sum<A: SumAccess<'de>>(self, data: A) -> Result<Self::Output, A::Error>;
424}
425
426/// Provides a [`SumVisitor`] access to the data of a sum in the input.
427///
428/// An `A: SumAccess` object is created by the [`D: Deserializer`]
429/// which passes `A` to a [`V: SumVisitor`] that `D` in turn was passed.
430/// `A` is then used by `V` to split tag and value input apart.
431pub trait SumAccess<'de> {
432    /// The error type that can be returned if some error occurs during deserialization.
433    type Error: Error;
434
435    /// The visitor used to deserialize the content of the sum variant.
436    type Variant: VariantAccess<'de, Error = Self::Error>;
437
438    /// Called to identify which variant to deserialize.
439    /// Returns a tuple with the result of identification (`V::Output`)
440    /// and the input to variant data deserialization.
441    ///
442    /// The `visitor` is provided by the [`Deserializer`].
443    /// This method is typically called from [`SumVisitor::visit_sum`]
444    /// which will provide the [`V: VariantVisitor`](VariantVisitor).
445    fn variant<V: VariantVisitor>(self, visitor: V) -> Result<(V::Output, Self::Variant), Self::Error>;
446}
447
448/// A visitor passed from [`SumVisitor`] to [`SumAccess::variant`]
449/// which the latter uses to decide what variant to deserialize.
450pub trait VariantVisitor {
451    /// The result of identifying a variant, e.g., some index type.
452    type Output;
453
454    /// Provides the visitor the chance to add valid names into `names`.
455    fn variant_names(&self, names: &mut dyn ValidNames);
456
457    /// Identify the variant based on `tag`.
458    fn visit_tag<E: Error>(self, tag: u8) -> Result<Self::Output, E>;
459
460    /// Identify the variant based on `name`.
461    fn visit_name<E: Error>(self, name: &str) -> Result<Self::Output, E>;
462}
463
464/// A visitor passed from [`SumAccess`] to [`SumVisitor::visit_sum`]
465/// which the latter uses to deserialize the data of a selected variant.
466pub trait VariantAccess<'de>: Sized {
467    type Error: Error;
468
469    /// Called when deserializing the contents of a sum variant.
470    ///
471    /// This method exists as a convenience for [`Deserialize`] implementations.
472    fn deserialize<T: Deserialize<'de>>(self) -> Result<T, Self::Error> {
473        self.deserialize_seed(PhantomData)
474    }
475
476    /// Called when deserializing the contents of a sum variant, and provided with a `seed` value.
477    fn deserialize_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Output, Self::Error>;
478}
479
480/// A `SliceVisitor` is provided a slice `T` of some elements by a [`Deserializer`]
481/// and is tasked with translating this slice to the `Output` type.
482pub trait SliceVisitor<'de, T: ToOwned + ?Sized>: Sized {
483    /// The output produced by this visitor.
484    type Output;
485
486    /// The input contains a slice.
487    ///
488    /// The lifetime of the slice is ephemeral
489    /// and it may be destroyed after this method returns.
490    fn visit<E: Error>(self, slice: &T) -> Result<Self::Output, E>;
491
492    /// The input contains a slice and ownership of the slice is being given to the [`SliceVisitor`].
493    fn visit_owned<E: Error>(self, buf: T::Owned) -> Result<Self::Output, E> {
494        self.visit(buf.borrow())
495    }
496
497    /// The input contains a slice that lives at least as long (`'de`) as the [`Deserializer`].
498    fn visit_borrowed<E: Error>(self, borrowed_slice: &'de T) -> Result<Self::Output, E> {
499        self.visit(borrowed_slice)
500    }
501}
502
503/// A visitor walking through a [`Deserializer`] for arrays.
504pub trait ArrayVisitor<'de, T> {
505    /// The output produced by this visitor.
506    type Output;
507
508    /// The input contains an array.
509    fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error>;
510}
511
512/// Provides an [`ArrayVisitor`] with access to each element of the array in the input.
513///
514/// This is a trait that a [`Deserializer`] passes to an [`ArrayVisitor`] implementation.
515pub trait ArrayAccess<'de> {
516    /// The element / base type of the array.
517    type Element;
518
519    /// The error type that can be returned if some error occurs during deserialization.
520    type Error: Error;
521
522    /// This returns `Ok(Some(value))` for the next element in the array,
523    /// or `Ok(None)` if there are no more remaining elements.
524    fn next_element(&mut self) -> Result<Option<Self::Element>, Self::Error>;
525
526    /// Returns the number of elements remaining in the array, if known.
527    fn size_hint(&self) -> Option<usize> {
528        None
529    }
530}
531
532/// `DeserializeSeed` is the stateful form of the [`Deserialize`] trait.
533pub trait DeserializeSeed<'de> {
534    /// The type produced by using this seed.
535    type Output;
536
537    /// Equivalent to the more common [`Deserialize::deserialize`] associated function,
538    /// except with some initial piece of data (the seed `self`) passed in.
539    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error>;
540}
541
542use crate::de::impls::BorrowedSliceVisitor;
543pub use spacetimedb_bindings_macro::Deserialize;
544
545/// A data structure that can be deserialized from any data format supported by the SpacetimeDB Algebraic Type System.
546///
547/// In most cases, implementations of `Deserialize` may be `#[derive(Deserialize)]`d.
548///
549/// The `Deserialize` trait in SATS performs the same function as `serde::Deserialize` in [`serde`].
550/// See the documentation of `serde::Deserialize` for more information of the data model.
551///
552/// The lifetime `'de` allows us to deserialize lifetime-generic types in a zero-copy fashion.
553///
554/// Do not manually implement this trait unless you know what you are doing.
555/// Implementations must be consistent with `Serialize for T`, `SpacetimeType for T` and `Serialize, Deserialize for AlgebraicValue`.
556/// Implementations that are inconsistent across these traits may result in data loss.
557///
558/// [`serde`]: https://crates.io/crates/serde
559pub trait Deserialize<'de>: Sized {
560    /// Deserialize this value from the given `deserializer`.
561    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>;
562
563    #[doc(hidden)]
564    /// Deserialize this value from the given the BSATN `deserializer`.
565    fn deserialize_from_bsatn<R: BufReader<'de>>(
566        deserializer: bsatn::Deserializer<'de, R>,
567    ) -> Result<Self, bsatn::DecodeError> {
568        Self::deserialize(deserializer)
569    }
570
571    /// used in the Deserialize for Vec<T> impl to allow specializing deserializing Vec<T> as bytes
572    #[doc(hidden)]
573    #[inline(always)]
574    fn __deserialize_vec<D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Self>, D::Error> {
575        deserializer.deserialize_array(BasicVecVisitor)
576    }
577
578    #[doc(hidden)]
579    #[inline(always)]
580    fn __deserialize_array<D: Deserializer<'de>, const N: usize>(deserializer: D) -> Result<[Self; N], D::Error> {
581        deserializer.deserialize_array(BasicArrayVisitor)
582    }
583}
584
585/// A data structure that can be deserialized in SATS
586/// without borrowing any data from the deserializer.
587pub trait DeserializeOwned: for<'de> Deserialize<'de> {}
588impl<T: for<'de> Deserialize<'de>> DeserializeOwned for T {}
589
590impl<'de, T: Deserialize<'de>> DeserializeSeed<'de> for PhantomData<T> {
591    type Output = T;
592
593    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Output, D::Error> {
594        T::deserialize(deserializer)
595    }
596}
597
598/// A vector with two operations: `with_capacity` and `push`.
599pub trait GrowingVec<T> {
600    /// Create the collection with the given capacity.
601    fn with_capacity(cap: usize) -> Self;
602
603    /// Push to the vector the `elem`.
604    fn push(&mut self, elem: T);
605}
606
607impl<T> GrowingVec<T> for Vec<T> {
608    fn with_capacity(cap: usize) -> Self {
609        Self::with_capacity(cap)
610    }
611    fn push(&mut self, elem: T) {
612        self.push(elem)
613    }
614}
615
616impl<T, const N: usize> GrowingVec<T> for SmallVec<[T; N]> {
617    fn with_capacity(cap: usize) -> Self {
618        Self::with_capacity(cap)
619    }
620    fn push(&mut self, elem: T) {
621        self.push(elem)
622    }
623}
624
625/// A basic implementation of `ArrayVisitor::visit` using the provided size hint.
626pub fn array_visit<'de, A: ArrayAccess<'de>, V: GrowingVec<A::Element>>(mut access: A) -> Result<V, A::Error> {
627    let mut v = V::with_capacity(access.size_hint().unwrap_or(0));
628    while let Some(x) = access.next_element()? {
629        v.push(x)
630    }
631    Ok(v)
632}
633
634/// An implementation of [`ArrayVisitor<'de, T>`] where the output is a `Vec<T>`.
635pub struct BasicVecVisitor;
636
637impl<'de, T> ArrayVisitor<'de, T> for BasicVecVisitor {
638    type Output = Vec<T>;
639
640    fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error> {
641        array_visit(vec)
642    }
643}
644
645/// An implementation of [`ArrayVisitor<'de, T>`] where the output is a `SmallVec<[T; N]>`.
646pub struct BasicSmallVecVisitor<const N: usize>;
647
648impl<'de, T, const N: usize> ArrayVisitor<'de, T> for BasicSmallVecVisitor<N> {
649    type Output = SmallVec<[T; N]>;
650
651    fn visit<A: ArrayAccess<'de, Element = T>>(self, vec: A) -> Result<Self::Output, A::Error> {
652        array_visit(vec)
653    }
654}
655
656/// An implementation of [`ArrayVisitor<'de, T>`] where the output is a `[T; N]`.
657struct BasicArrayVisitor<const N: usize>;
658
659impl<'de, T, const N: usize> ArrayVisitor<'de, T> for BasicArrayVisitor<N> {
660    type Output = [T; N];
661
662    fn visit<A: ArrayAccess<'de, Element = T>>(self, mut vec: A) -> Result<Self::Output, A::Error> {
663        let mut v = arrayvec::ArrayVec::<T, N>::new();
664        while let Some(el) = vec.next_element()? {
665            v.try_push(el)
666                .map_err(|_| Error::custom("too many elements for array"))?
667        }
668        v.into_inner().map_err(|_| Error::custom("too few elements for array"))
669    }
670}
671
672/// Provided a function `names` that is allowed to store a name into a valid set,
673/// returns a human readable list of all the names,
674/// or `None` in the case of an empty list of names.
675fn one_of_names(names: impl Fn(&mut dyn ValidNames)) -> Option<impl fmt::Display> {
676    /// An implementation of `ValidNames` that just counts how many valid names are pushed into it.
677    struct CountNames(usize);
678
679    impl ValidNames for CountNames {
680        fn push(&mut self, _: &str) {
681            self.0 += 1
682        }
683    }
684
685    /// An implementation of `ValidNames` that provides a human friendly enumeration of names.
686    struct OneOfNames<'a, 'b> {
687        /// A `.push(_)` counter.
688        index: usize,
689        /// How many names there were.
690        count: usize,
691        /// Result of formatting thus far.
692        f: Result<&'a mut fmt::Formatter<'b>, fmt::Error>,
693    }
694
695    impl<'a, 'b> OneOfNames<'a, 'b> {
696        fn new(count: usize, f: &'a mut fmt::Formatter<'b>) -> Self {
697            Self {
698                index: 0,
699                count,
700                f: Ok(f),
701            }
702        }
703    }
704
705    impl ValidNames for OneOfNames<'_, '_> {
706        fn push(&mut self, name: &str) {
707            // This will give us, after all `.push()`es have been made, the following:
708            //
709            // count = 1 -> "`foo`"
710            //       = 2 -> "`foo` or `bar`"
711            //       > 2 -> "one of `foo`, `bar`, or `baz`"
712
713            let Ok(f) = &mut self.f else {
714                return;
715            };
716
717            self.index += 1;
718
719            if let Err(e) = match (self.count, self.index) {
720                (1, _) => write!(f, "`{name}`"),
721                (2, 1) => write!(f, "`{name}`"),
722                (2, 2) => write!(f, "`or `{name}`"),
723                (_, 1) => write!(f, "one of `{name}`"),
724                (c, i) if i < c => write!(f, ", `{name}`"),
725                (_, _) => write!(f, ", `, or {name}`"),
726            } {
727                self.f = Err(e);
728            }
729        }
730    }
731
732    // Count how many names have been pushed.
733    let count = CountNames(0).run(&names).0;
734
735    // There was at least one name; render those names.
736    (count != 0).then(|| fmt_fn(move |fmt| OneOfNames::new(count, fmt).run(&names).f.map(drop)))
737}