Skip to main content

wincode_dynamic/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(not(feature = "std"), no_std)]
4extern crate alloc;
5
6use {
7    alloc::{boxed::Box, string::String},
8    core::{iter::FusedIterator, marker::PhantomData, slice},
9    wincode::{ReadResult, SchemaRead, SchemaWrite, error::invalid_tag_encoding, io::Reader},
10};
11
12mod compile_fail;
13mod ty;
14mod value;
15mod wincode_extra;
16#[cfg(feature = "derive")]
17pub use wincode_dynamic_derive::*;
18pub use {ty::*, value::*};
19#[cfg(test)]
20mod proptest_config;
21
22/// Describes a field in a runtime [`Schema`].
23///
24/// A field definition records the field's name and dynamic type, along with its
25/// encoded size when that size is statically known.
26#[derive(SchemaRead, SchemaWrite, Debug, Clone, PartialEq)]
27pub struct FieldDef {
28    name: String,
29    ty: Ty,
30    size: Option<usize>,
31}
32
33/// A decoded field yielded by [`Fields`].
34///
35/// The field borrows its metadata from the decoder's schema and its value from
36/// the encoded input data.
37#[derive(Debug, Clone)]
38pub struct Field<'meta, 'data> {
39    name: &'meta str,
40    ty: Ty,
41    size: Option<usize>,
42    value: Value<'data>,
43}
44
45/// An iterator that lazily decodes a payload's fields in schema order.
46///
47/// Returned by [`Schema::fields`], [`Decoder::fields`],
48/// [`SchemaDecoder::fields`], and [`VariantDecoder::fields`]. The iterator
49/// owns its reader and borrows field definitions from the schema. Decoded
50/// values can borrow from the input when the reader supports it.
51///
52/// Each item contains a decoded [`Field`] or its decoding error. The exact
53/// remaining length counts fields, including any that may fail to decode.
54/// Dropping the iterator early leaves the remaining fields unread.
55#[derive(Debug)]
56pub struct Fields<'schema, 'de, R> {
57    fields: slice::Iter<'schema, FieldDef>,
58    reader: R,
59    _marker: PhantomData<&'de ()>,
60}
61
62impl<'schema, 'de, R: Reader<'de>> Iterator for Fields<'schema, 'de, R> {
63    type Item = ReadResult<Field<'schema, 'de>>;
64
65    #[inline]
66    fn next(&mut self) -> Option<Self::Item> {
67        let field = self.fields.next()?;
68        Some(field.parse(self.reader.by_ref()).map(|value| Field {
69            name: &field.name,
70            ty: field.ty,
71            size: field.size,
72            value,
73        }))
74    }
75
76    #[inline]
77    fn size_hint(&self) -> (usize, Option<usize>) {
78        self.fields.size_hint()
79    }
80}
81
82impl<'de, R: Reader<'de>> ExactSizeIterator for Fields<'_, 'de, R> {
83    #[inline]
84    fn len(&self) -> usize {
85        self.fields.len()
86    }
87}
88
89impl<'de, R: Reader<'de>> FusedIterator for Fields<'_, 'de, R> {}
90
91impl<'meta, 'data> Field<'meta, 'data> {
92    /// Returns the field's name.
93    #[inline]
94    pub const fn name(&self) -> &str {
95        self.name
96    }
97
98    /// Returns the field's dynamic type.
99    #[inline]
100    pub const fn ty(&self) -> Ty {
101        self.ty
102    }
103
104    /// Returns the field's complete encoded size when it is fixed.
105    ///
106    /// The size uses wincode's default configuration. `None` means the field's
107    /// size depends on its value, as it does for strings and vectors.
108    #[inline]
109    pub const fn size(&self) -> Option<usize> {
110        self.size
111    }
112
113    /// Returns the decoded value.
114    #[inline]
115    pub const fn value(&self) -> &Value<'data> {
116        &self.value
117    }
118
119    /// Consumes the field and returns its decoded value.
120    #[inline]
121    pub fn into_value(self) -> Value<'data> {
122        self.value
123    }
124}
125
126impl FieldDef {
127    /// Creates a new [`FieldDef`] with the given name, type, and size.
128    pub fn new(name: impl Into<String>, ty: Ty, size: impl Into<Option<usize>>) -> Self {
129        Self {
130            name: name.into(),
131            ty,
132            size: size.into(),
133        }
134    }
135
136    /// Returns the field's name.
137    #[inline]
138    pub fn name(&self) -> &str {
139        &self.name
140    }
141
142    /// Returns the field's dynamic type.
143    #[inline]
144    pub const fn ty(&self) -> Ty {
145        self.ty
146    }
147
148    /// Returns the field's complete encoded size when it is fixed.
149    ///
150    /// The size uses wincode's default configuration. `None` means the field's
151    /// size depends on its value, as it does for strings and vectors.
152    #[inline]
153    pub const fn size(&self) -> Option<usize> {
154        self.size
155    }
156
157    /// Parse a [`Value`] of this field from the given [`Reader`].
158    #[inline]
159    pub fn parse<'de>(&self, reader: impl Reader<'de>) -> ReadResult<Value<'de>> {
160        self.ty.parse(reader)
161    }
162}
163
164/// A serializable runtime schema for a top-level struct or enum.
165///
166/// This is the schema value exchanged before encoded values and passed to
167/// [`Decoder::new`] for reflective decoding.
168///
169/// Deriving [`SchemaDynamic`] implements [`schema`](SchemaDynamic::schema) on
170/// the derived type, which generates its `RootSchema`.
171///
172/// # Examples
173///
174/// ```
175/// use wincode::{SchemaRead, SchemaWrite};
176/// use wincode_dynamic::{PrimitiveTy, RootSchema, SchemaDynamic, Ty};
177///
178/// #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
179/// struct Message {
180///     id: u64,
181///     active: bool,
182/// }
183///
184/// let schema: RootSchema = Message::schema();
185/// let RootSchema::Struct(schema) = schema else {
186///     panic!("expected a struct schema");
187/// };
188///
189/// assert_eq!(schema.name(), "Message");
190/// assert_eq!(schema.size(), Some(9));
191///
192/// let fields = schema.field_defs();
193/// assert_eq!(fields.len(), 2);
194/// assert_eq!(fields[0].name(), "id");
195/// assert_eq!(fields[0].ty(), Ty::PrimitiveTy(PrimitiveTy::U64));
196/// assert_eq!(fields[0].size(), Some(8));
197/// assert_eq!(fields[1].name(), "active");
198/// assert_eq!(fields[1].ty(), Ty::PrimitiveTy(PrimitiveTy::Bool));
199/// assert_eq!(fields[1].size(), Some(1));
200/// ```
201#[derive(SchemaRead, SchemaWrite, Debug, Clone, PartialEq)]
202#[wincode(tag_encoding = "u8")]
203pub enum RootSchema {
204    /// The schema of a struct.
205    Struct(Schema),
206    /// The schema of an enum.
207    Enum {
208        /// The field schema for each variant, in declaration order.
209        variants: Box<[Schema]>,
210        /// The complete encoded size, including the tag, when it is fixed.
211        size: Option<usize>,
212        /// The enum type's name.
213        name: String,
214        /// The primitive type used to encode the variant tag.
215        tag_encoding: PrimitiveTy,
216    },
217}
218
219impl RootSchema {
220    /// Returns the root struct or enum name.
221    #[inline]
222    pub fn name(&self) -> &str {
223        match self {
224            RootSchema::Struct(schema) => &schema.name,
225            RootSchema::Enum { name, .. } => name,
226        }
227    }
228
229    /// Returns the complete encoded size of a root value when it is fixed.
230    ///
231    /// For enums, this includes the variant tag. The size uses wincode's
232    /// default configuration; `None` means it depends on the encoded value.
233    #[inline]
234    pub const fn size(&self) -> Option<usize> {
235        match self {
236            RootSchema::Struct(schema) => schema.size,
237            RootSchema::Enum { size, .. } => *size,
238        }
239    }
240
241    /// Creates a decoder for encoded values of this schema.
242    #[inline]
243    pub fn decoder(&self) -> Decoder<'_> {
244        Decoder::new(self)
245    }
246}
247
248/// Describes the fields and encoded-size metadata of a struct or enum variant.
249///
250/// Enum schemas use one `Schema` per variant, while struct schemas use a single
251/// `Schema` for the root value.
252#[derive(SchemaRead, SchemaWrite, Debug, Clone, PartialEq)]
253pub struct Schema {
254    name: String,
255    fields: Box<[FieldDef]>,
256    size: Option<usize>,
257}
258
259impl Schema {
260    /// Creates a schema with the given name, fields, and fixed-size metadata.
261    pub fn new(
262        name: impl Into<String>,
263        fields: Box<[FieldDef]>,
264        size: impl Into<Option<usize>>,
265    ) -> Self {
266        Self {
267            name: name.into(),
268            fields,
269            size: size.into(),
270        }
271    }
272
273    /// Returns the complete encoded size of this schema when it is fixed.
274    ///
275    /// For a root struct, this is the complete struct encoding. For an enum
276    /// variant, it covers the variant's fields but not the enum tag. The size
277    /// uses wincode's default configuration; `None` means it depends on the
278    /// encoded value.
279    #[inline]
280    pub const fn size(&self) -> Option<usize> {
281        self.size
282    }
283
284    /// Returns the struct or enum variant name.
285    #[inline]
286    pub fn name(&self) -> &str {
287        &self.name
288    }
289
290    /// Returns the fields in their encoded order.
291    #[inline]
292    pub const fn field_defs(&self) -> &[FieldDef] {
293        &self.fields
294    }
295
296    /// Creates an iterator that lazily decodes the payload, yielding decoded
297    /// fields in schema order.
298    ///
299    /// The reader must supply a wincode-encoded value matching this schema,
300    /// positioned at its first field. For an enum variant, the variant tag
301    /// must already have been consumed; use
302    /// [`EnumDecoder::decode_variant`] to select the variant and read its tag.
303    ///
304    /// Creating the iterator does not read from the input and cannot fail.
305    /// Each field is decoded as the iterator advances, with decoding errors
306    /// returned by the corresponding iterator item.
307    /// Dropping the iterator early leaves the remaining fields unread.
308    #[inline]
309    pub fn fields<'de, R: Reader<'de>>(&self, reader: R) -> Fields<'_, 'de, R> {
310        Fields {
311            fields: self.fields.iter(),
312            reader,
313            _marker: PhantomData,
314        }
315    }
316}
317
318/// Information known at compile time about a type's serialized size.
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320pub enum SerializedSize {
321    /// Every serialized value fits within this many bytes.
322    ///
323    /// Individual values may be smaller, such as enum variants with different
324    /// encoded sizes.
325    Static(usize),
326    /// A complete upper bound cannot be derived, but statically sized fields
327    /// contribute at most this many bytes.
328    Dynamic(usize),
329}
330
331/// Runtime schema metadata derived for a serializable type.
332pub trait SchemaDynamic {
333    /// Serialized-size information under wincode's default configuration.
334    ///
335    /// - [`SerializedSize::Static`] means the entire encoding has a finite
336    ///   maximum. Its value is the maximum number of serialized bytes;
337    ///   individual enum variants may be smaller.
338    /// - [`SerializedSize::Dynamic`] means a complete upper bound cannot be
339    ///   derived from wincode's type metadata. Its value is the portion that
340    ///   can still be determined statically: the sum of fixed-size fields for a
341    ///   struct, or the tag plus the largest fixed-size portion of any enum
342    ///   variant.
343    ///
344    /// This constant is sizing metadata; it does not impose or validate a
345    /// serialization limit.
346    ///
347    /// A `#[wincode(with = ...)]` adapter supplies the field's serialized-size
348    /// metadata, but the runtime [`RootSchema`] continues to describe the
349    /// Rust field's [`DynTy`]. Such an adapter must therefore preserve that
350    /// field's wire representation when the schema is used with
351    /// [`Decoder`].
352    const SERIALIZED_SIZE: SerializedSize = SerializedSize::Dynamic(0);
353
354    /// Generates the type's serializable runtime schema.
355    fn schema() -> RootSchema;
356}
357
358/// Decodes a wincode-encoded payload reflectively using a runtime
359/// [`RootSchema`].
360///
361/// A decoder borrows its [`RootSchema`] and can be reused for every value
362/// encoded with that schema. Create one with [`RootSchema::decoder`] or
363/// [`Decoder::new`].
364///
365/// Call [`Decoder::fields`] to iterate lazily over a payload's fields for
366/// either a struct or an enum. For enums, this reads the variant tag and
367/// selects its fields automatically.
368///
369/// Match on the decoder when the distinction between structs and enums matters:
370///
371/// - [`Decoder::Struct`] exposes a [`SchemaDecoder`]. Its
372///   [`fields`](SchemaDecoder::fields) method creates the iterator infallibly,
373///   since there is no variant tag to read.
374/// - [`Decoder::Enum`] exposes an [`EnumDecoder`]. Call
375///   [`decode_variant`](EnumDecoder::decode_variant) to read and validate the
376///   variant tag, returning a [`VariantDecoder`]. Its
377///   [`variant_name`](VariantDecoder::variant_name) is always available,
378///   including for unit variants. Then consume it with
379///   [`fields`](VariantDecoder::fields) to iterate over the selected fields.
380///   The tag is read once; field iteration continues from the reader's
381///   resulting position.
382///
383/// In every path, individual fields are decoded as the iterator advances, and
384/// field decoding errors are returned by the corresponding iterator item.
385///
386/// # Examples
387///
388/// Inspect an enum variant before decoding its fields using the same reader:
389///
390/// ```
391/// use wincode::{SchemaRead, SchemaWrite};
392/// use wincode_dynamic::{Decoder, SchemaDynamic, Value};
393///
394/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
395/// #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
396/// enum Message {
397///     Ping,
398///     Value(u64),
399/// }
400///
401/// let schema = Message::schema();
402/// let Decoder::Enum(decoder) = schema.decoder() else {
403///     panic!("expected an enum schema");
404/// };
405///
406/// let encoded = wincode::serialize(&Message::Value(42))?;
407/// let mut reader = &encoded[..];
408/// let variant = decoder.decode_variant(reader)?;
409/// let name = variant.variant_name();
410/// let mut fields = variant.fields();
411/// assert_eq!(name, "Value");
412/// assert_eq!(fields.next().expect("value field")?.value(), &Value::U64(42));
413/// assert!(fields.next().is_none());
414/// # Ok(())
415/// # }
416/// ```
417#[derive(Debug)]
418pub enum Decoder<'schema> {
419    /// A decoder for struct payloads.
420    Struct(SchemaDecoder<'schema>),
421    /// A decoder for selecting and decoding enum variants.
422    Enum(EnumDecoder<'schema>),
423}
424
425impl<'schema> Decoder<'schema> {
426    /// Creates a decoder for encoded values matching the borrowed schema.
427    pub fn new(schema: &'schema RootSchema) -> Self {
428        match schema {
429            RootSchema::Struct(schema) => Self::Struct(SchemaDecoder(schema)),
430            RootSchema::Enum {
431                variants,
432                tag_encoding,
433                ..
434            } => Self::Enum(EnumDecoder {
435                variants,
436                tag_encoding: *tag_encoding,
437            }),
438        }
439    }
440
441    /// Returns a lazy iterator over the fields in an encoded payload.
442    ///
443    /// Fields are decoded in schema order as the iterator advances. For an
444    /// enum, this method first reads the variant tag and then iterates over
445    /// that variant's fields.
446    /// Dropping the iterator early leaves the remaining fields unread.
447    ///
448    /// # Errors
449    ///
450    /// Returns an error if an enum variant tag is invalid. Errors encountered
451    /// while decoding a field are returned by the corresponding iterator item.
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// use wincode::{SchemaRead, SchemaWrite};
457    /// use wincode_dynamic::{Decoder, RootSchema, SchemaDynamic, Value};
458    ///
459    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
460    /// #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
461    /// struct Message {
462    ///     id: u64,
463    ///     active: bool,
464    /// }
465    ///
466    /// let encoded_schema = wincode::serialize(&Message::schema())?;
467    /// let encoded_value = wincode::serialize(&Message {
468    ///     id: 42,
469    ///     active: true,
470    /// })?;
471    ///
472    /// let schema = wincode::deserialize::<RootSchema>(&encoded_schema)?;
473    /// let decoder = Decoder::new(&schema);
474    /// let mut fields = decoder.fields(&encoded_value[..])?;
475    ///
476    /// let id = fields.next().expect("id field")?;
477    /// assert_eq!(id.name(), "id");
478    /// assert_eq!(id.value(), &Value::U64(42));
479    ///
480    /// let active = fields.next().expect("active field")?;
481    /// assert_eq!(active.name(), "active");
482    /// assert_eq!(active.value(), &Value::Bool(true));
483    /// assert!(fields.next().is_none());
484    ///
485    /// # Ok(())
486    /// # }
487    /// ```
488    #[inline]
489    pub fn fields<'de, R: Reader<'de>>(&self, reader: R) -> ReadResult<Fields<'schema, 'de, R>> {
490        match self {
491            Self::Struct(decoder) => Ok(decoder.fields(reader)),
492            Self::Enum(decoder) => Ok(decoder.decode_variant(reader)?.fields()),
493        }
494    }
495}
496
497/// Decodes struct payloads using a borrowed [`Schema`].
498///
499/// Obtained from [`Decoder::Struct`]. Call [`fields`](Self::fields) to lazily
500/// decode a payload's fields.
501#[derive(Debug)]
502pub struct SchemaDecoder<'schema>(&'schema Schema);
503
504impl<'schema> SchemaDecoder<'schema> {
505    /// Creates an iterator that lazily decodes the payload, yielding decoded
506    /// fields in schema order.
507    ///
508    /// The reader must supply a wincode-encoded struct matching this schema,
509    /// positioned at its first field.
510    ///
511    /// Creating the iterator does not read from the input and cannot fail.
512    /// Each field is decoded as the iterator advances, with decoding errors
513    /// returned by the corresponding iterator item.
514    /// Dropping the iterator early leaves the remaining fields unread.
515    #[inline]
516    pub fn fields<'de, R: Reader<'de>>(&self, reader: R) -> Fields<'schema, 'de, R> {
517        self.0.fields(reader)
518    }
519}
520
521/// Decodes enum payloads using borrowed variant schemas.
522///
523/// Obtained from [`Decoder::Enum`]. Call
524/// [`decode_variant`](Self::decode_variant) to read a payload's variant tag and
525/// obtain a [`VariantDecoder`] for inspecting its name and lazily decoding its
526/// fields.
527#[derive(Debug)]
528pub struct EnumDecoder<'schema> {
529    variants: &'schema [Schema],
530    tag_encoding: PrimitiveTy,
531}
532
533impl<'schema> EnumDecoder<'schema> {
534    /// Reads an enum payload's variant tag and returns a decoder for that
535    /// variant.
536    ///
537    /// The reader must supply an encoded enum value matching this decoder's
538    /// schema, positioned at its variant tag. The returned [`VariantDecoder`]
539    /// exposes the variant's name and retains the reader positioned at its
540    /// fields, which are decoded lazily by [`VariantDecoder::fields`].
541    ///
542    /// # Errors
543    ///
544    /// Returns an error if the tag cannot be read or does not identify a
545    /// variant in the schema.
546    #[inline]
547    pub fn decode_variant<'de, R: Reader<'de>>(
548        &self,
549        mut reader: R,
550    ) -> ReadResult<VariantDecoder<'schema, 'de, R>> {
551        let disc = self.tag_encoding.parse_into_usize(reader.by_ref())?;
552
553        let schema = self
554            .variants
555            .get(disc)
556            .ok_or_else(|| invalid_tag_encoding(disc))?;
557        Ok(VariantDecoder {
558            schema,
559            reader,
560            _marker: PhantomData,
561        })
562    }
563}
564
565/// Decodes the fields of a selected enum variant.
566///
567/// Returned by [`EnumDecoder::decode_variant`] after reading and validating
568/// the variant tag. Holds the selected schema and the reader positioned at
569/// the variant's first field. Call [`variant_name`](Self::variant_name) to
570/// inspect its name, then consume the decoder with [`fields`](Self::fields)
571/// to lazily decode its fields.
572#[derive(Debug)]
573pub struct VariantDecoder<'schema, 'de, R> {
574    schema: &'schema Schema,
575    reader: R,
576    _marker: PhantomData<&'de ()>,
577}
578
579impl<'schema, 'de, R> VariantDecoder<'schema, 'de, R> {
580    /// Returns the selected enum variant's name.
581    #[inline]
582    pub fn variant_name(&self) -> &'schema str {
583        &self.schema.name
584    }
585
586    /// Consumes this decoder, creating an iterator that lazily yields the
587    /// selected variant's decoded fields in schema order.
588    ///
589    /// Iteration uses the retained reader, continuing after the variant tag
590    /// already consumed by [`EnumDecoder::decode_variant`].
591    ///
592    /// Creating the iterator does not read from the input and cannot fail.
593    /// Each field is decoded as the iterator advances, with decoding errors
594    /// returned by the corresponding iterator item.
595    /// Dropping the iterator early leaves the remaining fields unread.
596    #[inline]
597    pub fn fields(self) -> Fields<'schema, 'de, R>
598    where
599        R: Reader<'de>,
600    {
601        self.schema.fields(self.reader)
602    }
603}
604
605impl<'schema, 'de, R> IntoIterator for VariantDecoder<'schema, 'de, R>
606where
607    R: Reader<'de>,
608{
609    type Item = ReadResult<Field<'schema, 'de>>;
610    type IntoIter = Fields<'schema, 'de, R>;
611
612    #[inline]
613    fn into_iter(self) -> Self::IntoIter {
614        self.fields()
615    }
616}
617
618#[cfg(all(test, feature = "std"))]
619mod test {
620    use {
621        super::*,
622        crate::proptest_config::proptest_cfg,
623        alloc::borrow::Cow,
624        core::mem::{align_of, size_of},
625        proptest::prelude::*,
626        proptest_derive::Arbitrary,
627    };
628
629    wincode::pod_wrapper! {
630        unsafe struct PodU64(u64);
631    }
632
633    #[derive(Arbitrary, SchemaDynamic, SchemaRead, SchemaWrite, PartialEq, Debug)]
634    #[wincode_dynamic(internal)]
635    struct StructMessage {
636        a: u64,
637        b: bool,
638        vals: Vec<u64>,
639        str: String,
640        bytes: Vec<u8>,
641        ar: [u64; 4],
642        ar_bytes: [u8; 8],
643    }
644
645    #[derive(Arbitrary, SchemaDynamic, SchemaRead, SchemaWrite, Debug)]
646    #[wincode_dynamic(internal)]
647    enum EnumMessage {
648        Ping,
649        Coordinates(u64, bool),
650        Payload { text: String, bytes: Vec<u8> },
651    }
652
653    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
654    #[wincode_dynamic(internal)]
655    #[wincode(tag_encoding = "u8")]
656    enum U8EnumMessage {
657        Ping,
658        Value(u64),
659    }
660
661    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
662    #[wincode_dynamic(internal)]
663    struct FixedSizeMessage {
664        value: u64,
665        enabled: bool,
666    }
667
668    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
669    #[wincode_dynamic(internal)]
670    enum FixedSizeEnum {
671        Flag(bool),
672        Value(u64),
673    }
674
675    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
676    #[wincode_dynamic(internal)]
677    enum SameSizeEnum {
678        First(u64),
679        Second(u64),
680    }
681
682    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
683    #[wincode_dynamic(internal)]
684    enum MixedSizeEnum {
685        Flag(bool),
686        Payload { id: u64, data: Vec<u8> },
687    }
688
689    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
690    #[wincode_dynamic(internal)]
691    struct SkippedFieldStruct {
692        before: u8,
693        #[wincode(skip)]
694        skipped: String,
695        after: u64,
696    }
697
698    #[derive(Default)]
699    struct Opaque;
700
701    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
702    #[wincode_dynamic(internal)]
703    struct OpaqueSkippedField {
704        #[wincode(skip)]
705        skipped: Opaque,
706        value: u64,
707    }
708
709    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
710    #[wincode_dynamic(internal)]
711    enum SkippedFieldEnum {
712        Skipped(#[wincode(skip)] String, bool),
713        Value(u64),
714    }
715
716    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
717    #[wincode_dynamic(internal)]
718    enum AdaptedFieldEnum {
719        Adapted(#[wincode(with = "PodU64")] u64),
720        Flag(bool),
721    }
722
723    // Keep this in a module so the lint allowance needed by SchemaRead's empty-enum
724    // expansion does not apply to the rest of the tests.
725    mod empty_enum {
726        #![allow(unreachable_code)]
727
728        use super::*;
729
730        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
731        #[wincode_dynamic(internal)]
732        pub(super) enum EmptyEnum {}
733    }
734
735    fn assert_enum_message(
736        decoder: &Decoder,
737        message: &EnumMessage,
738        expected: Vec<(&str, Ty, Option<usize>, Value<'_>)>,
739    ) {
740        let payload = wincode::serialize(message).unwrap();
741        let actual = decoder
742            .fields(payload.as_slice())
743            .unwrap()
744            .collect::<ReadResult<Vec<_>>>()
745            .unwrap();
746        assert_eq!(actual.len(), expected.len());
747        for (actual, (name, ty, size, value)) in actual.iter().zip(expected.iter()) {
748            assert_field(actual, name, *ty, *size, value);
749        }
750    }
751
752    fn assert_field(
753        field: &Field<'_, '_>,
754        name: &str,
755        ty: Ty,
756        size: Option<usize>,
757        value: &Value<'_>,
758    ) {
759        assert_eq!(field.name(), name);
760        assert_eq!(field.ty(), ty);
761        assert_eq!(field.size(), size);
762        assert_eq!(field.value(), value);
763    }
764
765    #[test]
766    fn serialized_size_metadata() {
767        assert_eq!(FixedSizeMessage::SERIALIZED_SIZE, SerializedSize::Static(9));
768        assert_eq!(FixedSizeEnum::SERIALIZED_SIZE, SerializedSize::Static(12));
769        assert_eq!(U8EnumMessage::SERIALIZED_SIZE, SerializedSize::Static(9));
770        assert_eq!(StructMessage::SERIALIZED_SIZE, SerializedSize::Dynamic(49));
771        assert_eq!(EnumMessage::SERIALIZED_SIZE, SerializedSize::Dynamic(13));
772        assert_eq!(SameSizeEnum::SERIALIZED_SIZE, SerializedSize::Static(12));
773        assert_eq!(MixedSizeEnum::SERIALIZED_SIZE, SerializedSize::Dynamic(12));
774        assert_eq!(
775            SkippedFieldStruct::SERIALIZED_SIZE,
776            SerializedSize::Static(9)
777        );
778        assert_eq!(
779            OpaqueSkippedField::SERIALIZED_SIZE,
780            SerializedSize::Static(8)
781        );
782        assert_eq!(
783            SkippedFieldEnum::SERIALIZED_SIZE,
784            SerializedSize::Static(12)
785        );
786        assert_eq!(
787            AdaptedFieldEnum::SERIALIZED_SIZE,
788            SerializedSize::Static(12)
789        );
790        assert_eq!(
791            empty_enum::EmptyEnum::SERIALIZED_SIZE,
792            SerializedSize::Static(0)
793        );
794
795        assert_eq!(
796            wincode::serialize(&FixedSizeEnum::Flag(false))
797                .unwrap()
798                .len(),
799            5
800        );
801        assert_eq!(
802            wincode::serialize(&FixedSizeEnum::Value(0)).unwrap().len(),
803            12
804        );
805        let skipped = SkippedFieldEnum::Skipped(String::new(), true);
806        assert!(matches!(
807            &skipped,
808            SkippedFieldEnum::Skipped(value, true) if value.is_empty()
809        ));
810        assert_eq!(wincode::serialize(&skipped).unwrap().len(), 5);
811        assert_eq!(
812            wincode::serialize(&SkippedFieldEnum::Value(0))
813                .unwrap()
814                .len(),
815            12
816        );
817        assert_eq!(
818            wincode::serialize(&AdaptedFieldEnum::Adapted(0))
819                .unwrap()
820                .len(),
821            12
822        );
823        assert_eq!(
824            wincode::serialize(&AdaptedFieldEnum::Flag(false))
825                .unwrap()
826                .len(),
827            5
828        );
829    }
830
831    #[test]
832    fn skipped_fields_are_omitted_from_runtime_schemas() {
833        let opaque = OpaqueSkippedField {
834            skipped: Opaque,
835            value: 3,
836        };
837        let _ = &opaque.skipped;
838        let payload = wincode::serialize(&opaque).unwrap();
839        let schema = OpaqueSkippedField::schema();
840        let decoder = Decoder::new(&schema);
841        let fields = decoder
842            .fields(payload.as_slice())
843            .unwrap()
844            .collect::<ReadResult<Vec<_>>>()
845            .unwrap();
846        assert_eq!(fields.len(), 1);
847        assert_field(
848            &fields[0],
849            "value",
850            Ty::PrimitiveTy(PrimitiveTy::U64),
851            Some(8),
852            &Value::U64(3),
853        );
854
855        let message = SkippedFieldStruct {
856            before: 1,
857            skipped: "not serialized".into(),
858            after: 2,
859        };
860        let payload = wincode::serialize(&message).unwrap();
861        let schema = SkippedFieldStruct::schema();
862        let decoder = Decoder::new(&schema);
863        let fields = decoder
864            .fields(payload.as_slice())
865            .unwrap()
866            .collect::<ReadResult<Vec<_>>>()
867            .unwrap();
868        assert_eq!(fields.len(), 2);
869        assert_field(
870            &fields[0],
871            "before",
872            Ty::PrimitiveTy(PrimitiveTy::U8),
873            Some(1),
874            &Value::U8(1),
875        );
876        assert_field(
877            &fields[1],
878            "after",
879            Ty::PrimitiveTy(PrimitiveTy::U64),
880            Some(8),
881            &Value::U64(2),
882        );
883
884        let message = SkippedFieldEnum::Skipped("not serialized".into(), true);
885        let payload = wincode::serialize(&message).unwrap();
886        let schema = SkippedFieldEnum::schema();
887        let decoder = Decoder::new(&schema);
888        let fields = decoder
889            .fields(payload.as_slice())
890            .unwrap()
891            .collect::<ReadResult<Vec<_>>>()
892            .unwrap();
893        assert_eq!(fields.len(), 1);
894        assert_field(
895            &fields[0],
896            "1",
897            Ty::PrimitiveTy(PrimitiveTy::Bool),
898            Some(1),
899            &Value::Bool(true),
900        );
901    }
902
903    #[test]
904    fn struct_roundtrip() {
905        let message = StructMessage {
906            a: 42,
907            b: true,
908            vals: vec![333; 4],
909            str: String::from("hello world"),
910            bytes: vec![42; 8],
911            ar: [444; 4],
912            ar_bytes: [43; 8],
913        };
914
915        let schema = StructMessage::schema();
916        let decoder = Decoder::new(&schema);
917
918        let payload = wincode::serialize(&message).unwrap();
919        let result = decoder
920            .fields(&payload[..])
921            .unwrap()
922            .collect::<ReadResult<Vec<_>>>()
923            .unwrap();
924        let mut result = result.into_iter();
925
926        let field = result.next().unwrap();
927        assert_field(
928            &field,
929            "a",
930            Ty::PrimitiveTy(PrimitiveTy::U64),
931            Some(8),
932            &Value::U64(42),
933        );
934        let field = result.next().unwrap();
935        assert_field(
936            &field,
937            "b",
938            Ty::PrimitiveTy(PrimitiveTy::Bool),
939            Some(1),
940            &Value::Bool(true),
941        );
942
943        let field = result.next().unwrap();
944        assert_eq!(field.name(), "vals");
945        assert_eq!(field.ty(), Ty::Vec(PrimitiveTy::U64));
946        assert_eq!(field.size(), None);
947        let Value::Vec(vals) = field.value else {
948            panic!("expected vals to be a lazy vector");
949        };
950        assert_eq!(vals.ty(), PrimitiveTy::U64);
951        assert_eq!(vals.len(), 4);
952        assert!(!vals.is_empty());
953        assert_eq!(
954            vals.clone().into_dyn_vec().unwrap(),
955            vec![PrimitiveValue::U64(333); 4]
956        );
957        let mut iter = vals.try_iter_as::<u64>().unwrap();
958        fn assert_fused(_: &impl core::iter::FusedIterator) {}
959        assert_fused(&iter);
960        assert_eq!(iter.size_hint(), (4, Some(4)));
961        assert_eq!(iter.len(), 4);
962
963        assert_eq!(iter.next().unwrap().unwrap(), 333);
964        assert_eq!(iter.size_hint(), (3, Some(3)));
965        assert_eq!(iter.len(), 3);
966
967        assert_eq!(
968            iter.by_ref().collect::<ReadResult<Vec<_>>>().unwrap(),
969            vec![333; 3]
970        );
971        assert_eq!(iter.size_hint(), (0, Some(0)));
972        assert_eq!(iter.len(), 0);
973        assert!(iter.next().is_none());
974        assert!(iter.next().is_none());
975        assert!(vals.try_iter_as::<u32>().is_err());
976
977        let field = result.next().unwrap();
978        assert_field(
979            &field,
980            "str",
981            Ty::String,
982            None,
983            &Value::String("hello world".into()),
984        );
985        let field = result.next().unwrap();
986        assert_field(
987            &field,
988            "bytes",
989            Ty::Vec(PrimitiveTy::U8),
990            None,
991            &Value::Bytes(vec![42; 8].into()),
992        );
993
994        let field = result.next().unwrap();
995        assert_eq!(field.name(), "ar");
996        assert_eq!(
997            field.ty(),
998            Ty::Array {
999                ty: PrimitiveTy::U64,
1000                len: 4
1001            }
1002        );
1003        assert_eq!(field.size(), Some(32));
1004        let Value::Vec(vals) = field.value else {
1005            panic!("expected ar to be a lazy vector");
1006        };
1007        assert_eq!(
1008            vals.try_into_iter_as::<u64>()
1009                .unwrap()
1010                .collect::<ReadResult<Vec<_>>>()
1011                .unwrap(),
1012            vec![444; 4]
1013        );
1014
1015        let field = result.next().unwrap();
1016        assert_field(
1017            &field,
1018            "ar_bytes",
1019            Ty::Array {
1020                ty: PrimitiveTy::U8,
1021                len: 8,
1022            },
1023            Some(8),
1024            &Value::Bytes(vec![43; 8].into()),
1025        );
1026        assert!(result.next().is_none());
1027    }
1028
1029    #[test]
1030    fn lazy_vector_reports_element_errors_during_iteration() {
1031        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1032        #[wincode_dynamic(internal)]
1033        struct Bools {
1034            values: Vec<bool>,
1035        }
1036
1037        let mut payload = wincode::serialize(&Bools {
1038            values: vec![true, false],
1039        })
1040        .unwrap();
1041        *payload.last_mut().unwrap() = 2;
1042
1043        let schema = Bools::schema();
1044        let decoder = Decoder::new(&schema);
1045        let value = decoder
1046            .fields(payload.as_slice())
1047            .unwrap()
1048            .next()
1049            .unwrap()
1050            .unwrap();
1051        let Value::Vec(values) = value.value else {
1052            panic!("expected a lazy vector");
1053        };
1054
1055        let mut values = values.try_into_iter_as::<bool>().unwrap();
1056        assert_eq!(values.size_hint(), (2, Some(2)));
1057        assert!(values.next().unwrap().unwrap());
1058        assert_eq!(values.size_hint(), (1, Some(1)));
1059
1060        let error = values.next().unwrap().unwrap_err();
1061        assert!(matches!(error, wincode::ReadError::InvalidBoolEncoding(2)));
1062        assert_eq!(values.size_hint(), (0, Some(0)));
1063        assert_eq!(values.len(), 0);
1064        assert!(values.next().is_none());
1065    }
1066
1067    #[test]
1068    fn lazy_vector_iterators_can_borrow_or_own_the_payload() {
1069        // SAFETY: the payload contains exactly three encoded `u8` elements.
1070        let values: LazyVec<'static> =
1071            unsafe { LazyVec::new_unchecked(PrimitiveTy::U8, 3, Cow::Owned(vec![1, 2, 3])) };
1072
1073        assert_eq!(
1074            values
1075                .try_iter_as::<u8>()
1076                .unwrap()
1077                .collect::<ReadResult<Vec<_>>>()
1078                .unwrap(),
1079            [1, 2, 3]
1080        );
1081
1082        let mut values = values.try_into_iter_as::<u8>().unwrap();
1083        fn assert_fused(_: &impl core::iter::FusedIterator) {}
1084        assert_fused(&values);
1085        assert_eq!(values.next().unwrap().unwrap(), 1);
1086        assert_eq!(values.len(), 2);
1087        assert_eq!(values.collect::<ReadResult<Vec<_>>>().unwrap(), [2, 3]);
1088    }
1089
1090    #[test]
1091    fn lazy_vector_decodes_from_an_unaligned_borrowed_payload() {
1092        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1093        #[wincode_dynamic(internal)]
1094        struct Message {
1095            values: Vec<u64>,
1096        }
1097
1098        let values = [10, 20, 30];
1099        let payload = wincode::serialize(&Message {
1100            values: values.into(),
1101        })
1102        .unwrap();
1103        let length_prefix_size = wincode::serialize(&Vec::<u64>::new()).unwrap().len();
1104        let mut storage = vec![0; payload.len() + align_of::<u64>()];
1105        let offset = (0..align_of::<u64>())
1106            .find(|offset| {
1107                // The vector elements begin immediately after its length prefix.
1108                unsafe { storage.as_ptr().add(*offset + length_prefix_size) }
1109                    .align_offset(align_of::<u64>())
1110                    != 0
1111            })
1112            .expect("an unaligned offset");
1113        storage[offset..offset + payload.len()].copy_from_slice(&payload);
1114        let payload = &storage[offset..offset + payload.len()];
1115
1116        let schema = Message::schema();
1117        let decoder = Decoder::new(&schema);
1118        let field = decoder.fields(payload).unwrap().next().unwrap().unwrap();
1119        let Value::Vec(values) = field.value() else {
1120            panic!("expected a lazy vector");
1121        };
1122
1123        assert!(values.has_borrowed_payload());
1124        assert_eq!(
1125            values
1126                .try_iter_as::<u64>()
1127                .unwrap()
1128                .collect::<ReadResult<Vec<_>>>()
1129                .unwrap(),
1130            [10, 20, 30]
1131        );
1132    }
1133
1134    #[test]
1135    fn owned_lazy_payloads_enforce_the_byte_preallocation_limit() {
1136        use wincode::{
1137            config::{Config, DEFAULT_PREALLOCATION_SIZE_LIMIT, DefaultConfig},
1138            io::Cursor,
1139            len::SeqLen,
1140        };
1141
1142        type LengthEncoding = <DefaultConfig as Config>::LengthEncoding;
1143
1144        let len = DEFAULT_PREALLOCATION_SIZE_LIMIT / PrimitiveTy::U64.size() + 1;
1145        let mut encoded_len = Vec::new();
1146        <LengthEncoding as SeqLen<DefaultConfig>>::write(&mut encoded_len, len).unwrap();
1147
1148        let vector_error = Ty::Vec(PrimitiveTy::U64)
1149            .parse(Cursor::new(encoded_len))
1150            .unwrap_err();
1151        assert!(matches!(
1152            vector_error,
1153            wincode::ReadError::PreallocationSizeLimit { needed, limit }
1154                if needed == len * PrimitiveTy::U64.size()
1155                    && limit == DEFAULT_PREALLOCATION_SIZE_LIMIT
1156        ));
1157
1158        let array_error = Ty::Array {
1159            ty: PrimitiveTy::U64,
1160            len,
1161        }
1162        .parse(Cursor::new(Vec::<u8>::new()))
1163        .unwrap_err();
1164        assert!(matches!(
1165            array_error,
1166            wincode::ReadError::PreallocationSizeLimit { needed, limit }
1167                if needed == len * PrimitiveTy::U64.size()
1168                    && limit == DEFAULT_PREALLOCATION_SIZE_LIMIT
1169        ));
1170    }
1171
1172    #[test]
1173    fn dynamic_lazy_decode_enforces_its_allocation_limit() {
1174        use wincode::config::DEFAULT_PREALLOCATION_SIZE_LIMIT;
1175
1176        let len = DEFAULT_PREALLOCATION_SIZE_LIMIT / size_of::<PrimitiveValue>() + 1;
1177        // SAFETY: `PrimitiveTy::U8` has an element width of one byte, so the
1178        // payload contains exactly `len` elements.
1179        let values =
1180            unsafe { LazyVec::new_unchecked(PrimitiveTy::U8, len, Cow::Owned(vec![0; len])) };
1181
1182        let error = values.into_dyn_vec().unwrap_err();
1183        assert!(matches!(
1184            error,
1185            wincode::ReadError::PreallocationSizeLimit { needed, limit }
1186                if needed == len * size_of::<PrimitiveValue>()
1187                    && limit == DEFAULT_PREALLOCATION_SIZE_LIMIT
1188        ));
1189    }
1190
1191    #[test]
1192    fn enum_schema() {
1193        let RootSchema::Enum {
1194            name,
1195            variants,
1196            size,
1197            tag_encoding,
1198        } = EnumMessage::schema()
1199        else {
1200            panic!("expected an enum schema");
1201        };
1202
1203        assert_eq!(name, "EnumMessage");
1204        assert_eq!(size, None);
1205        assert_eq!(variants.len(), 3);
1206        assert_eq!(tag_encoding, PrimitiveTy::U32);
1207
1208        assert_eq!(variants[0].name, "Ping");
1209        assert!(variants[0].fields.is_empty());
1210        assert_eq!(variants[0].size, Some(0));
1211
1212        assert_eq!(variants[1].name, "Coordinates");
1213        assert_eq!(variants[1].fields[0].name, "0");
1214        assert_eq!(variants[1].fields[0].ty, Ty::PrimitiveTy(PrimitiveTy::U64));
1215        assert_eq!(variants[1].fields[1].name, "1");
1216        assert_eq!(variants[1].fields[1].ty, Ty::PrimitiveTy(PrimitiveTy::Bool));
1217        assert_eq!(variants[1].size, Some(9));
1218
1219        assert_eq!(variants[2].name, "Payload");
1220        assert_eq!(variants[2].fields[0].name, "text");
1221        assert_eq!(variants[2].fields[0].ty, Ty::String);
1222        assert_eq!(variants[2].fields[1].name, "bytes");
1223        assert_eq!(variants[2].fields[1].ty, Ty::Vec(PrimitiveTy::U8));
1224        assert_eq!(variants[2].size, None);
1225    }
1226
1227    #[test]
1228    fn enum_with_u8_tag_encoding_roundtrips() {
1229        let RootSchema::Enum { tag_encoding, .. } = U8EnumMessage::schema() else {
1230            panic!("expected an enum schema");
1231        };
1232        assert_eq!(tag_encoding, PrimitiveTy::U8);
1233
1234        let schema = U8EnumMessage::schema();
1235        let decoder = Decoder::new(&schema);
1236
1237        let ping = wincode::serialize(&U8EnumMessage::Ping).unwrap();
1238        assert_eq!(decoder.fields(ping.as_slice()).unwrap().count(), 0);
1239
1240        let value = wincode::serialize(&U8EnumMessage::Value(42)).unwrap();
1241        let fields = decoder
1242            .fields(value.as_slice())
1243            .unwrap()
1244            .collect::<ReadResult<Vec<_>>>()
1245            .unwrap();
1246        assert_eq!(fields.len(), 1);
1247        assert_field(
1248            &fields[0],
1249            "0",
1250            Ty::PrimitiveTy(PrimitiveTy::U64),
1251            Some(8),
1252            &Value::U64(42),
1253        );
1254    }
1255
1256    #[test]
1257    fn enum_variants_decode_consecutively_from_a_mutable_reader() {
1258        let schema = U8EnumMessage::schema();
1259        let Decoder::Enum(decoder) = schema.decoder() else {
1260            panic!("expected an enum decoder");
1261        };
1262        let records = [
1263            (U8EnumMessage::Value(42), "Value", vec![Value::U64(42)]),
1264            (U8EnumMessage::Ping, "Ping", vec![]),
1265            (U8EnumMessage::Value(7), "Value", vec![Value::U64(7)]),
1266        ];
1267        let encoded = records
1268            .iter()
1269            .map(|(message, _, _)| wincode::serialize(message).unwrap())
1270            .collect::<Vec<_>>();
1271        let payload = encoded.concat();
1272        let mut reader = payload.as_slice();
1273        let mut consumed = 0;
1274
1275        for ((_, expected_name, expected_fields), record) in records.iter().zip(&encoded) {
1276            let variant = decoder.decode_variant(&mut reader).unwrap();
1277            assert_eq!(variant.variant_name(), *expected_name);
1278            let fields = variant
1279                .fields()
1280                .map(|field| field.map(Field::into_value))
1281                .collect::<ReadResult<Vec<_>>>()
1282                .unwrap();
1283            assert_eq!(&fields, expected_fields);
1284            consumed += record.len();
1285            assert_eq!(reader, &payload[consumed..]);
1286        }
1287        assert!(reader.is_empty());
1288    }
1289
1290    #[test]
1291    fn decoded_fields_and_variant_names_outlive_decoder_wrappers() {
1292        let schema = FixedSizeMessage::schema();
1293        let payload = wincode::serialize(&FixedSizeMessage {
1294            value: 42,
1295            enabled: true,
1296        })
1297        .unwrap();
1298
1299        let fields = {
1300            let decoder = schema.decoder();
1301            decoder.fields(payload.as_slice()).unwrap()
1302        };
1303        let fields = fields.collect::<ReadResult<Vec<_>>>().unwrap();
1304        assert_eq!(fields[0].name(), "value");
1305        assert_eq!(fields[0].value(), &Value::U64(42));
1306        assert_eq!(fields[1].value(), &Value::Bool(true));
1307
1308        let fields = {
1309            let Decoder::Struct(decoder) = schema.decoder() else {
1310                panic!("expected a struct decoder");
1311            };
1312            decoder.fields(payload.as_slice())
1313        };
1314        let fields = fields.collect::<ReadResult<Vec<_>>>().unwrap();
1315        assert_eq!(fields[0].name(), "value");
1316        assert_eq!(fields[0].value(), &Value::U64(42));
1317        assert_eq!(fields[1].value(), &Value::Bool(true));
1318
1319        let schema = U8EnumMessage::schema();
1320        let payload = wincode::serialize(&U8EnumMessage::Value(7)).unwrap();
1321        let variant = {
1322            let Decoder::Enum(decoder) = schema.decoder() else {
1323                panic!("expected an enum decoder");
1324            };
1325            decoder.decode_variant(payload.as_slice()).unwrap()
1326        };
1327        let name = variant.variant_name();
1328        let fields = variant.fields().collect::<ReadResult<Vec<_>>>().unwrap();
1329        assert_eq!(name, "Value");
1330        assert_eq!(fields[0].name(), "0");
1331        assert_eq!(fields[0].value(), &Value::U64(7));
1332    }
1333
1334    #[test]
1335    fn dropping_field_iterator_leaves_remaining_fields_unread() {
1336        let schema = FixedSizeMessage::schema();
1337        let payload = wincode::serialize(&FixedSizeMessage {
1338            value: 42,
1339            enabled: true,
1340        })
1341        .unwrap();
1342        let decoder = schema.decoder();
1343        let mut reader = payload.as_slice();
1344        let field = {
1345            let mut fields = decoder.fields(&mut reader).unwrap();
1346            fields.next().unwrap().unwrap()
1347        };
1348
1349        assert_eq!(field.name(), "value");
1350        assert_eq!(field.value(), &Value::U64(42));
1351        assert_eq!(reader, wincode::serialize(&true).unwrap().as_slice());
1352        assert_eq!(
1353            PrimitiveTy::Bool.parse(&mut reader).unwrap(),
1354            Value::Bool(true)
1355        );
1356        assert!(reader.is_empty());
1357    }
1358
1359    #[test]
1360    fn enum_roundtrips_every_variant_shape() {
1361        let schema = EnumMessage::schema();
1362        let decoder = Decoder::new(&schema);
1363
1364        assert_enum_message(&decoder, &EnumMessage::Ping, Vec::new());
1365        assert_enum_message(
1366            &decoder,
1367            &EnumMessage::Coordinates(42, true),
1368            vec![
1369                (
1370                    "0",
1371                    Ty::PrimitiveTy(PrimitiveTy::U64),
1372                    Some(8),
1373                    Value::U64(42),
1374                ),
1375                (
1376                    "1",
1377                    Ty::PrimitiveTy(PrimitiveTy::Bool),
1378                    Some(1),
1379                    Value::Bool(true),
1380                ),
1381            ],
1382        );
1383        assert_enum_message(
1384            &decoder,
1385            &EnumMessage::Payload {
1386                text: "hello".into(),
1387                bytes: vec![1, 2, 3, 4],
1388            },
1389            vec![
1390                (
1391                    "text",
1392                    Ty::String,
1393                    None,
1394                    Value::String(Cow::Owned("hello".into())),
1395                ),
1396                (
1397                    "bytes",
1398                    Ty::Vec(PrimitiveTy::U8),
1399                    None,
1400                    Value::Bytes(Cow::Owned(vec![1, 2, 3, 4])),
1401                ),
1402            ],
1403        );
1404    }
1405
1406    #[test]
1407    fn enum_rejects_invalid_discriminant() {
1408        let schema = EnumMessage::schema();
1409        let decoder = Decoder::new(&schema);
1410        let payload = wincode::serialize(&u32::MAX).unwrap();
1411
1412        let error = match decoder.fields(payload.as_slice()) {
1413            Ok(_) => panic!("invalid discriminant unexpectedly parsed"),
1414            Err(error) => error,
1415        };
1416
1417        assert!(matches!(
1418            error,
1419            wincode::ReadError::InvalidTagEncoding(value) if value == u32::MAX as usize
1420        ));
1421    }
1422
1423    #[test]
1424    fn enum_reports_truncated_and_malformed_fields() {
1425        let schema = EnumMessage::schema();
1426        let decoder = Decoder::new(&schema);
1427
1428        let truncated_discriminant = [0u8; 3];
1429        assert!(decoder.fields(&truncated_discriminant[..]).is_err());
1430
1431        let mut truncated = wincode::serialize(&EnumMessage::Coordinates(42, true)).unwrap();
1432        truncated.pop();
1433        let truncated_result = decoder
1434            .fields(truncated.as_slice())
1435            .unwrap()
1436            .collect::<ReadResult<Vec<_>>>();
1437        assert!(truncated_result.is_err());
1438
1439        let mut malformed = wincode::serialize(&EnumMessage::Coordinates(42, true)).unwrap();
1440        *malformed.last_mut().unwrap() = 2;
1441        let malformed_result = decoder
1442            .fields(malformed.as_slice())
1443            .unwrap()
1444            .collect::<ReadResult<Vec<_>>>();
1445        assert!(matches!(
1446            malformed_result,
1447            Err(wincode::ReadError::InvalidBoolEncoding(2))
1448        ));
1449    }
1450
1451    #[test]
1452    fn string_and_bytes_borrow_from_the_input() {
1453        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1454        #[wincode_dynamic(internal)]
1455        struct Borrowable {
1456            text: String,
1457            bytes: Vec<u8>,
1458        }
1459
1460        let value = Borrowable {
1461            text: "borrow me".into(),
1462            bytes: vec![5, 6, 7, 8],
1463        };
1464        let payload = wincode::serialize(&value).unwrap();
1465        let schema = Borrowable::schema();
1466        let decoder = Decoder::new(&schema);
1467        let fields = decoder
1468            .fields(payload.as_slice())
1469            .unwrap()
1470            .collect::<ReadResult<Vec<_>>>()
1471            .unwrap();
1472
1473        assert_eq!(fields[0].name(), "text");
1474        assert_eq!(fields[1].name(), "bytes");
1475        match (fields[0].value(), fields[1].value()) {
1476            (Value::String(Cow::Borrowed(text)), Value::Bytes(Cow::Borrowed(bytes))) => {
1477                assert_eq!(*text, "borrow me");
1478                assert_eq!(*bytes, [5, 6, 7, 8]);
1479            }
1480            fields => panic!("expected borrowed string and bytes, got {fields:?}"),
1481        }
1482    }
1483
1484    #[test]
1485    fn dynamic_values_own_payloads_from_an_owned_reader() {
1486        use wincode::io::Cursor;
1487
1488        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1489        #[wincode_dynamic(internal)]
1490        struct Owned {
1491            text: String,
1492            bytes: Vec<u8>,
1493            values: Vec<u64>,
1494        }
1495
1496        let payload = wincode::serialize(&Owned {
1497            text: "owned".into(),
1498            bytes: vec![1, 2, 3],
1499            values: vec![10, 20, 30],
1500        })
1501        .unwrap();
1502        let schema = Owned::schema();
1503        let decoder = Decoder::new(&schema);
1504        let mut fields = decoder.fields(Cursor::new(payload)).unwrap();
1505
1506        let text = fields.next().unwrap().unwrap().into_value();
1507        assert!(matches!(
1508            text,
1509            Value::String(Cow::Owned(ref text)) if text == "owned"
1510        ));
1511
1512        let bytes = fields.next().unwrap().unwrap().into_value();
1513        assert!(matches!(
1514            bytes,
1515            Value::Bytes(Cow::Owned(ref bytes)) if bytes == &[1, 2, 3]
1516        ));
1517
1518        let values = fields.next().unwrap().unwrap().into_value();
1519        let Value::Vec(values) = values else {
1520            panic!("expected a lazy vector");
1521        };
1522        assert!(!values.has_borrowed_payload());
1523        assert_eq!(
1524            values
1525                .try_into_iter_as::<u64>()
1526                .unwrap()
1527                .collect::<ReadResult<Vec<_>>>()
1528                .unwrap(),
1529            [10, 20, 30]
1530        );
1531        assert!(fields.next().is_none());
1532    }
1533
1534    #[test]
1535    fn generic_enum_schema_and_roundtrip() {
1536        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1537        #[wincode_dynamic(internal)]
1538        enum Generic<T> {
1539            Empty,
1540            Item(T),
1541        }
1542
1543        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1544        #[wincode_dynamic(internal)]
1545        struct GenericSkip<T: Default> {
1546            #[wincode(skip)]
1547            skipped: T,
1548            value: u64,
1549        }
1550
1551        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1552        #[wincode_dynamic(internal)]
1553        enum GenericSkipEnum<T: Default> {
1554            Skipped(#[wincode(skip)] T),
1555            Value(u64),
1556        }
1557
1558        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1559        #[wincode_dynamic(internal)]
1560        struct GenericWith<T> {
1561            #[wincode(with = "wincode::containers::Vec<_, wincode::len::BincodeLen>")]
1562            values: Vec<T>,
1563        }
1564
1565        #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1566        #[wincode_dynamic(internal)]
1567        enum GenericWithEnum<T> {
1568            Values(
1569                #[wincode(with = "wincode::containers::Vec<_, wincode::len::BincodeLen>")] Vec<T>,
1570            ),
1571            Empty,
1572        }
1573
1574        assert_eq!(Generic::<u64>::SERIALIZED_SIZE, SerializedSize::Static(12));
1575        assert_eq!(
1576            Generic::<String>::SERIALIZED_SIZE,
1577            SerializedSize::Dynamic(4)
1578        );
1579        assert_eq!(
1580            GenericSkip::<u64>::SERIALIZED_SIZE,
1581            SerializedSize::Static(8)
1582        );
1583        assert_eq!(
1584            GenericSkipEnum::<u64>::SERIALIZED_SIZE,
1585            SerializedSize::Static(12)
1586        );
1587        assert_eq!(
1588            GenericWith::<u64>::SERIALIZED_SIZE,
1589            SerializedSize::Dynamic(0)
1590        );
1591        assert_eq!(
1592            GenericWithEnum::<u64>::SERIALIZED_SIZE,
1593            SerializedSize::Dynamic(4)
1594        );
1595
1596        let skipped = GenericSkip {
1597            skipped: 0u64,
1598            value: 1,
1599        };
1600        assert_eq!(skipped.skipped, 0);
1601        assert_eq!(wincode::serialize(&skipped).unwrap().len(), 8);
1602
1603        let skipped = GenericSkipEnum::Skipped(0u64);
1604        assert!(matches!(skipped, GenericSkipEnum::Skipped(0)));
1605        let value = GenericSkipEnum::<u64>::Value(1);
1606        assert_eq!(wincode::serialize(&value).unwrap().len(), 12);
1607
1608        let adapted = GenericWith {
1609            values: vec![1u64, 2],
1610        };
1611        assert!(!wincode::serialize(&adapted).unwrap().is_empty());
1612        let adapted = GenericWithEnum::Values(vec![1u64, 2]);
1613        assert!(!wincode::serialize(&adapted).unwrap().is_empty());
1614        assert!(matches!(
1615            GenericWithEnum::<u64>::Empty,
1616            GenericWithEnum::Empty
1617        ));
1618
1619        let schema = Generic::<u64>::schema();
1620        let decoder = Decoder::new(&schema);
1621        let payload = wincode::serialize(&Generic::Item(77u64)).unwrap();
1622        let fields = decoder
1623            .fields(payload.as_slice())
1624            .unwrap()
1625            .collect::<ReadResult<Vec<_>>>()
1626            .unwrap();
1627
1628        assert_eq!(fields.len(), 1);
1629        assert_field(
1630            &fields[0],
1631            "0",
1632            Ty::PrimitiveTy(PrimitiveTy::U64),
1633            Some(8),
1634            &Value::U64(77),
1635        );
1636
1637        let empty_payload = wincode::serialize(&Generic::<u64>::Empty).unwrap();
1638        assert_eq!(decoder.fields(empty_payload.as_slice()).unwrap().count(), 0);
1639    }
1640
1641    proptest! {
1642        #![proptest_config(proptest_cfg())]
1643
1644        #[test]
1645        fn arbitrary_struct_fields_match(message in any::<StructMessage>()) {
1646            let payload = wincode::serialize(&message).unwrap();
1647            let schema = StructMessage::schema();
1648            let decoder = Decoder::new(&schema);
1649            let fields = decoder
1650                .fields(payload.as_slice())
1651                .unwrap()
1652                .collect::<ReadResult<Vec<_>>>()
1653                .unwrap();
1654            let mut fields = fields.into_iter().map(|field| field.value);
1655
1656            prop_assert_eq!(fields.next(), Some(Value::U64(message.a)));
1657            prop_assert_eq!(fields.next(), Some(Value::Bool(message.b)));
1658
1659            let Some(Value::Vec(values)) = fields.next() else {
1660                return Err(TestCaseError::fail("expected vals to be a lazy vector"));
1661            };
1662            prop_assert_eq!(values.len(), message.vals.len());
1663            prop_assert_eq!(values.ty(), PrimitiveTy::U64);
1664            let values = values
1665                .try_into_iter_as::<u64>()
1666                .unwrap()
1667                .collect::<ReadResult<Vec<_>>>()
1668                .unwrap();
1669            prop_assert_eq!(values.as_slice(), message.vals.as_slice());
1670
1671            prop_assert_eq!(
1672                fields.next(),
1673                Some(Value::String(Cow::Borrowed(message.str.as_str())))
1674            );
1675            prop_assert_eq!(
1676                fields.next(),
1677                Some(Value::Bytes(Cow::Borrowed(message.bytes.as_slice())))
1678            );
1679
1680            let Some(Value::Vec(values)) = fields.next() else {
1681                return Err(TestCaseError::fail("expected ar to be a lazy vector"));
1682            };
1683            prop_assert_eq!(
1684                values
1685                    .try_into_iter_as::<u64>()
1686                    .unwrap()
1687                    .collect::<ReadResult<Vec<_>>>()
1688                    .unwrap(),
1689                message.ar
1690            );
1691            prop_assert_eq!(
1692                fields.next(),
1693                Some(Value::Bytes(Cow::Borrowed(message.ar_bytes.as_slice())))
1694            );
1695            prop_assert!(fields.next().is_none());
1696        }
1697
1698        #[test]
1699        fn arbitrary_enum_fields_match(message in any::<EnumMessage>()) {
1700            let payload = wincode::serialize(&message).unwrap();
1701            let schema = EnumMessage::schema();
1702            let decoder = Decoder::new(&schema);
1703            let actual = decoder
1704                .fields(payload.as_slice())
1705                .unwrap()
1706                .collect::<ReadResult<Vec<_>>>()
1707                .unwrap()
1708                .into_iter()
1709                .map(|field| field.value)
1710                .collect::<Vec<_>>();
1711            let expected = match &message {
1712                EnumMessage::Ping => Vec::new(),
1713                EnumMessage::Coordinates(x, y) => vec![Value::U64(*x), Value::Bool(*y)],
1714                EnumMessage::Payload { text, bytes } => vec![
1715                    Value::String(Cow::Borrowed(text.as_str())),
1716                    Value::Bytes(Cow::Borrowed(bytes.as_slice())),
1717                ],
1718            };
1719
1720            prop_assert_eq!(actual, expected);
1721        }
1722
1723        #[test]
1724        fn arbitrary_truncated_struct_is_rejected(
1725            message in any::<StructMessage>(),
1726            cut_seed in any::<usize>(),
1727        ) {
1728            let mut payload = wincode::serialize(&message).unwrap();
1729            let cut = cut_seed % payload.len();
1730            payload.truncate(cut);
1731
1732            let schema = StructMessage::schema();
1733            let decoder = Decoder::new(&schema);
1734            let result = decoder
1735                .fields(payload.as_slice())
1736                .and_then(|fields| fields.collect::<ReadResult<Vec<_>>>());
1737            prop_assert!(result.is_err());
1738        }
1739    }
1740
1741    macro_rules! primitive_vector_property {
1742        ($name:ident, $ty:ty, $variant:path, $strategy:expr) => {
1743            proptest! {
1744                #![proptest_config(proptest_cfg())]
1745
1746                #[test]
1747                fn $name(values in proptest::collection::vec($strategy, 0..64)) {
1748                    #[derive(SchemaDynamic, SchemaRead, SchemaWrite)]
1749                    #[wincode_dynamic(internal)]
1750                    struct Message {
1751                        values: Vec<$ty>,
1752                    }
1753
1754                    let message = Message {
1755                        values: values.clone(),
1756                    };
1757                    let payload = wincode::serialize(&message).unwrap();
1758                    let schema = Message::schema();
1759                    let decoder = Decoder::new(&schema);
1760                    let value = decoder
1761                        .fields(payload.as_slice())
1762                        .unwrap()
1763                        .next()
1764                        .unwrap()
1765                        .unwrap();
1766                    prop_assert_eq!(value.name(), "values");
1767                    prop_assert!(
1768                        matches!(value.ty(), Ty::Vec { .. }),
1769                        "field type was not a vector"
1770                    );
1771                    prop_assert_eq!(value.size(), None);
1772                    let Value::Vec(lazy) = value.value else {
1773                        return Err(TestCaseError::fail("expected a lazy vector"));
1774                    };
1775
1776                    prop_assert_eq!(lazy.len(), values.len());
1777                    prop_assert_eq!(lazy.is_empty(), values.is_empty());
1778                    prop_assert!(lazy.has_borrowed_payload());
1779                    prop_assert_eq!(
1780                        lazy.clone().into_dyn_vec().unwrap(),
1781                        values.iter().copied().map($variant).collect::<Vec<_>>()
1782                    );
1783                    prop_assert_eq!(
1784                        lazy
1785                            .try_into_iter_as::<$ty>()
1786                            .unwrap()
1787                            .collect::<ReadResult<Vec<_>>>()
1788                            .unwrap(),
1789                        values
1790                    );
1791                }
1792            }
1793        };
1794    }
1795
1796    primitive_vector_property!(arbitrary_u16_vector, u16, PrimitiveValue::U16, any::<u16>());
1797    primitive_vector_property!(arbitrary_u32_vector, u32, PrimitiveValue::U32, any::<u32>());
1798    primitive_vector_property!(arbitrary_u64_vector, u64, PrimitiveValue::U64, any::<u64>());
1799    primitive_vector_property!(arbitrary_i8_vector, i8, PrimitiveValue::I8, any::<i8>());
1800    primitive_vector_property!(arbitrary_i16_vector, i16, PrimitiveValue::I16, any::<i16>());
1801    primitive_vector_property!(arbitrary_i32_vector, i32, PrimitiveValue::I32, any::<i32>());
1802    primitive_vector_property!(arbitrary_i64_vector, i64, PrimitiveValue::I64, any::<i64>());
1803    primitive_vector_property!(
1804        arbitrary_bool_vector,
1805        bool,
1806        PrimitiveValue::Bool,
1807        any::<bool>()
1808    );
1809    primitive_vector_property!(
1810        arbitrary_f32_vector,
1811        f32,
1812        PrimitiveValue::F32,
1813        -1.0e20f32..1.0e20f32
1814    );
1815    primitive_vector_property!(
1816        arbitrary_f64_vector,
1817        f64,
1818        PrimitiveValue::F64,
1819        -1.0e100f64..1.0e100f64
1820    );
1821}