Skip to main content

wincode_dynamic/
ty.rs

1use {
2    crate::{LazyVec, Value},
3    alloc::{borrow::Cow, string::String, vec::Vec},
4    wincode::{
5        ReadResult, SchemaRead, SchemaReadContext, SchemaWrite,
6        config::{Config, DefaultConfig},
7        context::Len,
8        error::read_length_encoding_overflow,
9        io::{BorrowKind, Reader},
10        len::SeqLen,
11    },
12};
13
14type DefaultLengthEncoding = <DefaultConfig as Config>::LengthEncoding;
15
16#[inline]
17fn read_byte_payload<'de>(byte_len: usize, reader: impl Reader<'de>) -> ReadResult<Cow<'de, [u8]>> {
18    if !reader.supports_borrow(BorrowKind::Backing) {
19        <DefaultLengthEncoding as SeqLen<DefaultConfig>>::prealloc_check::<u8>(byte_len)?;
20    }
21
22    <Cow<'de, [u8]> as SchemaReadContext<'de, DefaultConfig, Len>>::get_with_context(
23        Len(byte_len),
24        reader,
25    )
26}
27
28#[inline]
29fn read_primitive_payload<'de>(
30    ty: PrimitiveTy,
31    len: usize,
32    reader: impl Reader<'de>,
33) -> ReadResult<Value<'de>> {
34    let byte_len = len
35        .checked_mul(ty.size())
36        .ok_or_else(|| read_length_encoding_overflow("usize::MAX"))?;
37
38    read_byte_payload(byte_len, reader).map(|payload| {
39        // SAFETY: `byte_len` was checked as `len * ty.size()`, and
40        // `read_byte_payload` returned exactly `byte_len` bytes.
41        Value::Vec(unsafe { LazyVec::new_unchecked(ty, len, payload) })
42    })
43}
44
45/// A fixed-width primitive type supported by dynamic decoding.
46///
47/// Each variant identifies both the Rust value kind and its wincode wire
48/// representation under [`DefaultConfig`].
49#[derive(Clone, Copy, Debug, PartialEq, SchemaRead, SchemaWrite)]
50#[wincode(tag_encoding = "u8")]
51pub enum PrimitiveTy {
52    /// An unsigned 8-bit integer.
53    U8,
54    /// An unsigned 16-bit integer.
55    U16,
56    /// An unsigned 32-bit integer.
57    U32,
58    /// An unsigned 64-bit integer.
59    U64,
60    /// A signed 8-bit integer.
61    I8,
62    /// A signed 16-bit integer.
63    I16,
64    /// A signed 32-bit integer.
65    I32,
66    /// A signed 64-bit integer.
67    I64,
68    /// A 32-bit floating-point number.
69    F32,
70    /// A 64-bit floating-point number.
71    F64,
72    /// A Boolean value.
73    Bool,
74}
75
76impl PrimitiveTy {
77    #[inline]
78    pub(crate) fn parse_into_usize<'de>(self, reader: impl Reader<'de>) -> ReadResult<usize> {
79        <usize as SchemaReadContext<DefaultConfig, _>>::get_with_context(self, reader)
80    }
81
82    /// Parses a [`Value`] of this type from the given [`Reader`].
83    ///
84    /// Decoding uses wincode's [`DefaultConfig`].
85    ///
86    /// # Examples
87    ///
88    /// ```
89    /// use wincode_dynamic::{PrimitiveTy, Value};
90    ///
91    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
92    /// let encoded = wincode::serialize(&42u64)?;
93    /// let value = PrimitiveTy::U64.parse(&encoded[..])?;
94    ///
95    /// assert_eq!(value, Value::U64(42));
96    /// # Ok(())
97    /// # }
98    /// ```
99    #[inline]
100    pub fn parse<'de>(self, reader: impl Reader<'de>) -> ReadResult<Value<'de>> {
101        <Value as SchemaReadContext<DefaultConfig, _>>::get_with_context(self, reader)
102    }
103
104    /// Returns the complete encoded width of this primitive, in bytes.
105    ///
106    /// Primitive encodings have no length prefix, so this is also the complete
107    /// serialized size under wincode's [`DefaultConfig`].
108    #[inline]
109    pub const fn size(self) -> usize {
110        match self {
111            PrimitiveTy::U8 => 1,
112            PrimitiveTy::U16 => 2,
113            PrimitiveTy::U32 => 4,
114            PrimitiveTy::U64 => 8,
115            PrimitiveTy::I8 => 1,
116            PrimitiveTy::I16 => 2,
117            PrimitiveTy::I32 => 4,
118            PrimitiveTy::I64 => 8,
119            PrimitiveTy::F32 => 4,
120            PrimitiveTy::F64 => 8,
121            PrimitiveTy::Bool => 1,
122        }
123    }
124}
125
126/// A field type supported by runtime schemas and dynamic decoding.
127///
128/// `Ty` describes the wire representation of a field under wincode's
129/// [`DefaultConfig`]. It is generated from a Rust field type through [`DynTy`].
130#[derive(Clone, Copy, Debug, PartialEq, SchemaRead, SchemaWrite)]
131#[wincode(tag_encoding = "u8")]
132pub enum Ty {
133    /// A scalar primitive.
134    PrimitiveTy(PrimitiveTy),
135    /// A length-prefixed UTF-8 string.
136    String,
137    /// A length-prefixed sequence of primitive elements.
138    Vec(PrimitiveTy),
139    /// A fixed-length array of primitive elements.
140    Array {
141        /// The element type.
142        ty: PrimitiveTy,
143        /// The number of elements.
144        len: usize,
145    },
146}
147
148impl Ty {
149    /// Parses a [`Value`] of this type from the given [`Reader`].
150    ///
151    /// Decoding uses wincode's [`DefaultConfig`]. Strings and byte sequences
152    /// remain borrowed when the reader supports stable borrowing; other
153    /// primitive sequences are returned as a [`LazyVec`].
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use wincode_dynamic::{PrimitiveTy, Ty, Value};
159    /// # use std::borrow::Cow;
160    ///
161    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
162    /// let encoded = wincode::serialize("w1nc0d3")?;
163    /// let value = Ty::String.parse(&encoded[..])?;
164    ///
165    /// assert_eq!(value, Value::String(Cow::Borrowed("w1nc0d3")));
166    /// # Ok(())
167    /// # }
168    /// ```
169    #[inline]
170    pub fn parse<'de>(self, mut reader: impl Reader<'de>) -> ReadResult<Value<'de>> {
171        match self {
172            Ty::PrimitiveTy(ty) => {
173                <Value as SchemaReadContext<DefaultConfig, _>>::get_with_context(ty, reader)
174            }
175            Ty::String => {
176                <Cow<'de, str> as SchemaRead<'de, DefaultConfig>>::get(reader).map(Value::String)
177            }
178            Ty::Vec(PrimitiveTy::U8) => {
179                <Cow<[u8]> as SchemaRead<'de, DefaultConfig>>::get(reader).map(Value::Bytes)
180            }
181            Ty::Vec(ty) => {
182                let len = <DefaultLengthEncoding as SeqLen<DefaultConfig>>::read(reader.by_ref())?;
183                read_primitive_payload(ty, len, reader)
184            }
185            Ty::Array {
186                ty: PrimitiveTy::U8,
187                len,
188            } => read_byte_payload(len, reader).map(Value::Bytes),
189            Ty::Array { ty, len } => read_primitive_payload(ty, len, reader),
190        }
191    }
192
193    /// Returns the complete serialized size of this type when it is fixed.
194    ///
195    /// Primitive types and arrays have a fixed size under wincode's
196    /// [`DefaultConfig`]. Strings and vectors return `None` because their
197    /// complete size, including the length prefix, depends on the value.
198    #[inline]
199    pub const fn size(self) -> Option<usize> {
200        match self {
201            Ty::PrimitiveTy(ty) => Some(ty.size()),
202            Ty::String => None,
203            Ty::Vec(..) => None,
204            Ty::Array { ty, len } => Some(ty.size() * len),
205        }
206    }
207}
208
209/// Associates a supported Rust primitive with its runtime [`PrimitiveTy`].
210pub trait DynPrimitiveTy {
211    /// The runtime primitive type corresponding to `Self`.
212    const TYPE: PrimitiveTy;
213}
214
215impl<T> DynTy for T
216where
217    T: DynPrimitiveTy,
218{
219    const TYPE: Ty = Ty::PrimitiveTy(T::TYPE);
220}
221
222/// Associates a Rust field type with its runtime [`Ty`].
223pub trait DynTy {
224    /// The runtime type corresponding to `Self`.
225    const TYPE: Ty;
226}
227
228impl DynPrimitiveTy for u8 {
229    const TYPE: PrimitiveTy = PrimitiveTy::U8;
230}
231
232impl DynPrimitiveTy for u16 {
233    const TYPE: PrimitiveTy = PrimitiveTy::U16;
234}
235
236impl DynPrimitiveTy for u32 {
237    const TYPE: PrimitiveTy = PrimitiveTy::U32;
238}
239
240impl DynPrimitiveTy for u64 {
241    const TYPE: PrimitiveTy = PrimitiveTy::U64;
242}
243
244impl DynPrimitiveTy for i8 {
245    const TYPE: PrimitiveTy = PrimitiveTy::I8;
246}
247
248impl DynPrimitiveTy for i16 {
249    const TYPE: PrimitiveTy = PrimitiveTy::I16;
250}
251
252impl DynPrimitiveTy for i32 {
253    const TYPE: PrimitiveTy = PrimitiveTy::I32;
254}
255
256impl DynPrimitiveTy for i64 {
257    const TYPE: PrimitiveTy = PrimitiveTy::I64;
258}
259
260impl DynPrimitiveTy for f32 {
261    const TYPE: PrimitiveTy = PrimitiveTy::F32;
262}
263
264impl DynPrimitiveTy for f64 {
265    const TYPE: PrimitiveTy = PrimitiveTy::F64;
266}
267
268impl DynPrimitiveTy for bool {
269    const TYPE: PrimitiveTy = PrimitiveTy::Bool;
270}
271
272impl DynTy for String {
273    const TYPE: Ty = Ty::String;
274}
275
276impl<T> DynTy for Vec<T>
277where
278    T: DynPrimitiveTy,
279{
280    const TYPE: Ty = Ty::Vec(T::TYPE);
281}
282
283impl<const N: usize, T: DynPrimitiveTy> DynTy for [T; N] {
284    const TYPE: Ty = Ty::Array {
285        ty: T::TYPE,
286        len: N,
287    };
288}