libspa/pod/
deserialize.rs

1//! This module deals with deserializing raw SPA pods into rust types.
2//!
3//! A raw pod can be deserialized into any implementor of the [`PodDeserialize`] trait
4//! by using [`PodDeserializer::deserialize_from`].
5//!
6//! The crate provides a number of implementors of this trait either directly,
7//! or through [`FixedSizedPod`](`super::FixedSizedPod`).
8//!
9//! You can also implement the [`PodDeserialize`] trait on another type yourself. See the traits documentation for more
10//! information on how to do that.
11
12use std::{convert::Infallible, ffi::c_void, marker::PhantomData, ptr};
13
14use nom::{
15    bytes::complete::{tag, take},
16    combinator::{map, map_res, verify},
17    number::{complete::u32, complete::u64, Endianness},
18    sequence::{delimited, pair, preceded, terminated},
19    IResult, Parser,
20};
21
22use super::{
23    CanonicalFixedSizedPod, ChoiceValue, FixedSizedPod, Object, PropertyFlags, Value, ValueArray,
24};
25use crate::{
26    pod::Property,
27    utils::{Choice, ChoiceEnum, ChoiceFlags, Fd, Fraction, Id, Rectangle},
28};
29
30/// Implementors of this trait can be deserialized from the raw SPA Pod format using a [`PodDeserializer`]-
31///
32/// Their [`deserialize`](`PodDeserialize::deserialize`) method should invoke exactly one of the `deserialize_*()` methods
33/// of the provided [`PodDeserializer`] that fits the type that should be deserialized.
34///
35/// If you want to deserialize from a pod that always has the same size, implement [`super::FixedSizedPod`] instead
36/// and this trait will be implemented for you automatically.
37///
38/// # Examples
39/// Deserialize a `String` pod without copying:
40/// ```rust
41/// use std::io;
42/// use libspa::pod::deserialize::{PodDeserialize, PodDeserializer, DeserializeError, DeserializeSuccess, StringVisitor};
43///
44/// struct ContainsStr<'s>(&'s str);
45///
46/// impl<'de> PodDeserialize<'de> for ContainsStr<'de> {
47///     fn deserialize(
48///         deserializer: PodDeserializer<'de>,
49///     ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
50///     where
51///         Self: Sized,
52///     {
53///         deserializer.deserialize_str(StringVisitor).map(|(s, success)| (ContainsStr(s), success))
54///     }
55/// }
56/// ```
57/// `Bytes` pods are created in the same way, but with the `serialize_bytes` method.
58///
59/// Deserialize an `Array` pod with `Int` elements:
60/// ```rust
61/// use std::io;
62/// use std::io::Cursor;
63/// use libspa::pod::deserialize::{PodDeserialize, PodDeserializer, DeserializeError, DeserializeSuccess, Visitor};
64/// use libspa::pod::serialize::PodSerializer;
65///
66/// struct Numbers(Vec<i32>);
67///
68/// impl<'de> PodDeserialize<'de> for Numbers {
69///     fn deserialize(
70///         deserializer: PodDeserializer<'de>,
71///     ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
72///     where
73///         Self: Sized,
74///     {
75///         struct NumbersVisitor;
76///
77///         impl<'de> Visitor<'de> for NumbersVisitor {
78///             type Value = Numbers;
79///             type ArrayElem = i32;
80///
81///             fn visit_array(
82///                 &self,
83///                 elements: Vec<Self::ArrayElem>,
84///             ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
85///                 Ok(Numbers(elements))
86///             }
87///         }
88///
89///         deserializer.deserialize_array(NumbersVisitor)
90///     }
91/// }
92/// ```
93///
94/// Make a struct deserialize from a `Struct` pod:
95/// ```rust
96/// use std::{convert::TryInto, io};
97/// use libspa::pod::deserialize::{PodDeserialize, PodDeserializer, DeserializeError, DeserializeSuccess, Visitor, StructPodDeserializer};
98///
99/// struct Animal {
100///     name: String,
101///     feet: u8,
102///     can_fly: bool,
103/// }
104///
105/// impl<'de> PodDeserialize<'de> for Animal {
106///     fn deserialize(
107///         deserializer: PodDeserializer<'de>,
108///     ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
109///     where
110///         Self: Sized,
111///     {
112///     struct AnimalVisitor;
113///
114///     impl<'de> Visitor<'de> for AnimalVisitor {
115///         type Value = Animal;
116///         type ArrayElem = std::convert::Infallible;
117///
118///         fn visit_struct(
119///             &self,
120///             struct_deserializer: &mut StructPodDeserializer<'de>,
121///         ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
122///             Ok(Animal {
123///                 name: struct_deserializer
124///                     .deserialize_field()?
125///                     .expect("Input has too few fields"),
126///                 feet: struct_deserializer
127///                     .deserialize_field::<i32>()?
128///                     .expect("Input has too few fields")
129///                     .try_into()
130///                     .expect("Animal is a millipede, has too many feet for a u8."),
131///                 can_fly: struct_deserializer
132///                     .deserialize_field()?
133///                     .expect("Input has too few fields"),
134///             })
135///         }
136///     }
137///
138///     deserializer.deserialize_struct(AnimalVisitor)
139///    }
140/// }
141/// ```
142pub trait PodDeserialize<'de> {
143    /// Deserialize the type by using the provided [`PodDeserializer`]
144    fn deserialize(
145        deserializer: PodDeserializer<'de>,
146    ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
147    where
148        Self: Sized;
149}
150
151// Deserialize a `String` pod. Returned `&str` is zero-copy (is a slice of the input).
152impl<'de> PodDeserialize<'de> for &'de str {
153    fn deserialize(
154        deserializer: PodDeserializer<'de>,
155    ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
156    where
157        Self: Sized,
158    {
159        deserializer.deserialize_str(StringVisitor)
160    }
161}
162
163// Deserialize a `String` pod. The returned string is an owned copy.
164impl<'de> PodDeserialize<'de> for String {
165    fn deserialize(
166        deserializer: PodDeserializer<'de>,
167    ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
168    where
169        Self: Sized,
170    {
171        deserializer
172            .deserialize_str(StringVisitor)
173            .map(|(s, success)| (s.to_owned(), success))
174    }
175}
176
177// Deserialize a `Bytes` pod. Returned `&[u8]` is zero-copy (is a slice of the input).
178impl<'de> PodDeserialize<'de> for &'de [u8] {
179    fn deserialize(
180        deserializer: PodDeserializer<'de>,
181    ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
182    where
183        Self: Sized,
184    {
185        deserializer.deserialize_bytes(BytesVisitor)
186    }
187}
188
189// Deserialize a `Bytes` pod. The returned bytes array is an owned copy.
190impl<'de> PodDeserialize<'de> for Vec<u8> {
191    fn deserialize(
192        deserializer: PodDeserializer<'de>,
193    ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
194    where
195        Self: Sized,
196    {
197        deserializer
198            .deserialize_bytes(BytesVisitor)
199            .map(|(b, success)| (b.to_owned(), success))
200    }
201}
202
203// Deserialize an `Array` type pod.
204impl<'de, P: FixedSizedPod + CanonicalFixedSizedPod + std::marker::Copy> PodDeserialize<'de>
205    for Vec<P>
206{
207    fn deserialize(
208        deserializer: PodDeserializer<'de>,
209    ) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
210    where
211        Self: Sized,
212    {
213        deserializer.deserialize_array::<_, P>(VecVisitor::<P>::default())
214    }
215}
216
217/// This struct is returned by [`PodDeserialize`] implementors on deserialization success.
218///
219/// Because this can only be constructed by the [`PodDeserializer`], [`PodDeserialize`] implementors are forced
220/// to finish deserialization of their pod instead of stopping after deserializing only part of a pod.
221pub struct DeserializeSuccess<'de>(PodDeserializer<'de>);
222
223/// This struct is responsible for deserializing a raw pod into a [`PodDeserialize`] implementor.
224pub struct PodDeserializer<'de> {
225    input: &'de [u8],
226}
227
228impl<'de> PodDeserializer<'de> {
229    /// Deserialize a [`PodDeserialize`] implementor from a raw pod.
230    ///
231    /// Deserialization will only succeed if the raw pod matches the kind of pod expected by the [`PodDeserialize`]
232    /// implementor.
233    ///
234    /// # Returns
235    ///
236    /// The remaining input and the type on success,
237    /// or an error that specifies where parsing failed.
238    pub fn deserialize_from<P: PodDeserialize<'de>>(
239        input: &'de [u8],
240    ) -> Result<(&'de [u8], P), DeserializeError<&'de [u8]>> {
241        let deserializer = Self { input };
242        P::deserialize(deserializer).map(|(res, success)| (success.0.input, res))
243    }
244
245    /// Deserialize a `spa_sys::spa_pod` pointer.
246    ///
247    /// # Safety
248    ///
249    /// - The provided pointer must point to a valid, well-aligned `spa_pod` struct.
250    /// - The pod pointed to must be kept valid for the entire lifetime of the deserialized object if
251    //    it has been created using zero-copy deserialization.
252    pub unsafe fn deserialize_ptr<P: PodDeserialize<'de>>(
253        ptr: ptr::NonNull<spa_sys::spa_pod>,
254    ) -> Result<P, DeserializeError<&'de [u8]>> {
255        let len = ptr.as_ref().size;
256        let pod = ptr.as_ptr() as *const _ as *const u8;
257        let slice = std::slice::from_raw_parts(pod, len as usize + 8);
258        let res = PodDeserializer::deserialize_from(slice)?;
259        Ok(res.1)
260    }
261
262    /// Execute the provide parse function, returning the parsed value or an error.
263    fn parse<T, F>(&mut self, mut f: F) -> Result<T, nom::Err<nom::error::Error<&'de [u8]>>>
264    where
265        F: FnMut(&'de [u8]) -> IResult<&'de [u8], T>,
266    {
267        f(self.input).map(|(input, result)| {
268            self.input = input;
269            result
270        })
271    }
272
273    /// Variant of [`Self::parse`] not consuming the parsed data
274    fn peek<T, F>(&self, mut f: F) -> Result<T, nom::Err<nom::error::Error<&'de [u8]>>>
275    where
276        F: FnMut(&'de [u8]) -> IResult<&'de [u8], T>,
277    {
278        f(self.input).map(|(_input, result)| result)
279    }
280
281    /// Returns the amount of padding needed to align a pod with the provided size to 8 bytes.
282    ///
283    /// In other words, this returns the difference between the provided size and the next multiple of 8.
284    fn calc_padding_needed(size: u32) -> u32 {
285        (8 - (size % 8)) % 8
286    }
287
288    /// Parse the size from the header and ensure it has the correct type.
289    pub(super) fn header<'b>(type_: u32) -> impl FnMut(&'b [u8]) -> IResult<&'b [u8], u32> {
290        let bytes = type_.to_ne_bytes();
291        move |input| terminated(u32(Endianness::Native), tag(&bytes[..])).parse(input)
292    }
293
294    /// Parse and return the type from the header
295    pub(super) fn type_<'b>() -> impl FnMut(&'b [u8]) -> IResult<&'b [u8], u32> {
296        move |input| preceded(u32(Endianness::Native), u32(Endianness::Native)).parse(input)
297    }
298
299    /// Deserialize any fixed size pod.
300    ///
301    /// Deserialization will only succeed if the [`FixedSizedPod::CanonicalType`] of the requested type matches the type
302    /// of the pod.
303    fn deserialize_fixed_sized_pod<P: FixedSizedPod>(
304        mut self,
305    ) -> Result<(P, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
306        let padding = Self::calc_padding_needed(P::CanonicalType::SIZE);
307
308        self.parse(move |input| {
309            delimited(
310                Self::header(P::CanonicalType::TYPE),
311                map(P::CanonicalType::deserialize_body, |res| {
312                    P::from_canonical_type(&res)
313                }),
314                take(padding),
315            )
316            .parse(input)
317        })
318        .map(|res| (res, DeserializeSuccess(self)))
319        .map_err(|err| err.into())
320    }
321
322    /// Deserialize a `none` pod.
323    pub fn deserialize_none<V>(
324        self,
325        visitor: V,
326    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
327    where
328        V: Visitor<'de>,
329    {
330        let res = self.deserialize_fixed_sized_pod::<()>().unwrap();
331        Ok((visitor.visit_none()?, res.1))
332    }
333
334    /// Deserialize a `boolean` pod.
335    pub fn deserialize_bool<V>(
336        self,
337        visitor: V,
338    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
339    where
340        V: Visitor<'de>,
341    {
342        let res = self.deserialize_fixed_sized_pod()?;
343        Ok((visitor.visit_bool(res.0)?, res.1))
344    }
345
346    /// Deserialize an `int` pod.
347    pub fn deserialize_int<V>(
348        self,
349        visitor: V,
350    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
351    where
352        V: Visitor<'de>,
353    {
354        let res = self.deserialize_fixed_sized_pod()?;
355        Ok((visitor.visit_int(res.0)?, res.1))
356    }
357
358    /// Deserialize a `long` pod.
359    pub fn deserialize_long<V>(
360        self,
361        visitor: V,
362    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
363    where
364        V: Visitor<'de>,
365    {
366        let res = self.deserialize_fixed_sized_pod()?;
367        Ok((visitor.visit_long(res.0)?, res.1))
368    }
369
370    /// Deserialize a `float` pod.
371    pub fn deserialize_float<V>(
372        self,
373        visitor: V,
374    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
375    where
376        V: Visitor<'de>,
377    {
378        let res = self.deserialize_fixed_sized_pod()?;
379        Ok((visitor.visit_float(res.0)?, res.1))
380    }
381
382    /// Deserialize a `double` pod.
383    pub fn deserialize_double<V>(
384        self,
385        visitor: V,
386    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
387    where
388        V: Visitor<'de>,
389    {
390        let res = self.deserialize_fixed_sized_pod()?;
391        Ok((visitor.visit_double(res.0)?, res.1))
392    }
393
394    /// Deserialize a `String` pod.
395    pub fn deserialize_str<V>(
396        mut self,
397        visitor: V,
398    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
399    where
400        V: Visitor<'de>,
401    {
402        let len = self.parse(Self::header(spa_sys::SPA_TYPE_String))?;
403        let padding = Self::calc_padding_needed(len);
404
405        let res = self.parse(move |input| {
406            terminated(
407                map_res(
408                    terminated(take(len - 1), tag(&b"\0"[..])),
409                    std::str::from_utf8,
410                ),
411                take(padding),
412            )
413            .parse(input)
414        })?;
415
416        Ok((visitor.visit_string(res)?, DeserializeSuccess(self)))
417    }
418
419    /// Deserialize a `Bytes` pod.
420    pub fn deserialize_bytes<V>(
421        mut self,
422        visitor: V,
423    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
424    where
425        V: Visitor<'de>,
426    {
427        let len = self.parse(Self::header(spa_sys::SPA_TYPE_Bytes))?;
428        let padding = Self::calc_padding_needed(len);
429        let res = self.parse(move |input| terminated(take(len), take(padding)).parse(input))?;
430
431        Ok((visitor.visit_bytes(res)?, DeserializeSuccess(self)))
432    }
433
434    /// Start parsing an array pod containing elements of type `E`.
435    ///
436    /// # Returns
437    /// - The array deserializer and the number of elements in the array on success
438    /// - An error if the header could not be parsed
439    pub fn new_array_deserializer<E>(
440        mut self,
441    ) -> Result<(ArrayPodDeserializer<'de, E>, u32), DeserializeError<&'de [u8]>>
442    where
443        E: FixedSizedPod,
444    {
445        let len = self.parse(Self::header(spa_sys::SPA_TYPE_Array))?;
446        self.parse(move |input| {
447            verify(Self::header(E::CanonicalType::TYPE), |len| {
448                *len == E::CanonicalType::SIZE
449            })
450            .parse(input)
451        })?;
452
453        let num_elems = if E::CanonicalType::SIZE != 0 {
454            (len - 8) / E::CanonicalType::SIZE
455        } else {
456            0
457        };
458
459        Ok((
460            ArrayPodDeserializer {
461                deserializer: self,
462                length: num_elems,
463                deserialized: 0,
464                _phantom: PhantomData,
465            },
466            num_elems,
467        ))
468    }
469
470    /// Start parsing a struct pod.
471    ///
472    /// # Errors
473    /// Returns a parsing error if input does not start with a struct pod.
474    fn new_struct_deserializer(
475        mut self,
476    ) -> Result<StructPodDeserializer<'de>, DeserializeError<&'de [u8]>> {
477        let len = self.parse(Self::header(spa_sys::SPA_TYPE_Struct))?;
478
479        Ok(StructPodDeserializer {
480            deserializer: Some(self),
481            remaining: len,
482        })
483    }
484
485    /// Start parsing an object pod.
486    ///
487    /// # Errors
488    /// Returns a parsing error if input does not start with an object pod.
489    fn new_object_deserializer(
490        mut self,
491    ) -> Result<ObjectPodDeserializer<'de>, DeserializeError<&'de [u8]>> {
492        let len = self.parse(Self::header(spa_sys::SPA_TYPE_Object))?;
493        let (object_type, object_id) = self.parse(move |input| {
494            pair(u32(Endianness::Native), u32(Endianness::Native)).parse(input)
495        })?;
496
497        Ok(ObjectPodDeserializer {
498            deserializer: Some(self),
499            remaining: len - 8,
500            object_type,
501            object_id,
502        })
503    }
504
505    /// Deserialize a `Rectangle` pod.
506    pub fn deserialize_rectangle<V>(
507        self,
508        visitor: V,
509    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
510    where
511        V: Visitor<'de>,
512    {
513        let res = self.deserialize_fixed_sized_pod()?;
514        Ok((visitor.visit_rectangle(res.0)?, res.1))
515    }
516
517    /// Deserialize a `Fraction` pod.
518    pub fn deserialize_fraction<V>(
519        self,
520        visitor: V,
521    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
522    where
523        V: Visitor<'de>,
524    {
525        let res = self.deserialize_fixed_sized_pod()?;
526        Ok((visitor.visit_fraction(res.0)?, res.1))
527    }
528
529    /// Deserialize an `Id` pod.
530    pub fn deserialize_id<V>(
531        self,
532        visitor: V,
533    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
534    where
535        V: Visitor<'de>,
536    {
537        let res = self.deserialize_fixed_sized_pod()?;
538        Ok((visitor.visit_id(res.0)?, res.1))
539    }
540
541    /// Deserialize a `Fd` pod.
542    pub fn deserialize_fd<V>(
543        self,
544        visitor: V,
545    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
546    where
547        V: Visitor<'de>,
548    {
549        let res = self.deserialize_fixed_sized_pod()?;
550        Ok((visitor.visit_fd(res.0)?, res.1))
551    }
552
553    /// Deserialize a `Struct` pod.
554    pub fn deserialize_struct<V>(
555        self,
556        visitor: V,
557    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
558    where
559        V: Visitor<'de>,
560    {
561        let mut struct_deserializer = self.new_struct_deserializer()?;
562        let res = visitor.visit_struct(&mut struct_deserializer)?;
563        let success = struct_deserializer.end()?;
564        Ok((res, success))
565    }
566
567    fn deserialize_array_vec<T>(
568        self,
569    ) -> Result<(Vec<T>, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
570    where
571        T: CanonicalFixedSizedPod + FixedSizedPod + std::marker::Copy,
572    {
573        let mut array_deserializer: ArrayPodDeserializer<'de, T> = self.new_array_deserializer()?.0;
574        let mut elements = Vec::with_capacity(array_deserializer.length as usize);
575        for _ in 0..array_deserializer.length {
576            elements.push(array_deserializer.deserialize_element()?);
577        }
578        let success = array_deserializer.end()?;
579
580        Ok((elements, success))
581    }
582
583    /// Deserialize an `array` pod containing elements of type `T`.
584    pub fn deserialize_array<V, T>(
585        self,
586        visitor: V,
587    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
588    where
589        V: Visitor<'de, ArrayElem = T>,
590        T: CanonicalFixedSizedPod + FixedSizedPod + std::marker::Copy,
591    {
592        let (elements, success) = self.deserialize_array_vec::<T>()?;
593        let res = visitor.visit_array(elements)?;
594        Ok((res, success))
595    }
596
597    /// Deserialize an `Object` pod.
598    pub fn deserialize_object<V>(
599        self,
600        visitor: V,
601    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
602    where
603        V: Visitor<'de>,
604    {
605        let mut obj_deserializer = self.new_object_deserializer()?;
606        let res = visitor.visit_object(&mut obj_deserializer)?;
607        let success = obj_deserializer.end()?;
608        Ok((res, success))
609    }
610
611    fn deserialize_choice_values<E>(
612        self,
613        num_values: u32,
614    ) -> Result<(Vec<E>, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
615    where
616        E: CanonicalFixedSizedPod + FixedSizedPod,
617    {
618        // re-use the array deserializer as choice values are serialized the same way
619        let mut array_deserializer = ArrayPodDeserializer {
620            deserializer: self,
621            length: num_values,
622            deserialized: 0,
623            _phantom: PhantomData,
624        };
625
626        // C implementation documents that there might be more elements than required by the choice type,
627        // which should be ignored, so deserialize all the values.
628        let mut elements = Vec::new();
629        for _ in 0..num_values {
630            elements.push(array_deserializer.deserialize_element()?);
631        }
632        let success = array_deserializer.end()?;
633
634        Ok((elements, success))
635    }
636
637    /// Deserialize a `Choice` pod.
638    pub fn deserialize_choice<V>(
639        mut self,
640        visitor: V,
641    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
642    where
643        V: Visitor<'de>,
644    {
645        let len = self.parse(Self::header(spa_sys::SPA_TYPE_Choice))?;
646
647        let (choice_type, flags) = self.parse(move |input| {
648            pair(u32(Endianness::Native), u32(Endianness::Native)).parse(input)
649        })?;
650
651        let (child_size, child_type) = self.parse(move |input| {
652            pair(u32(Endianness::Native), u32(Endianness::Native)).parse(input)
653        })?;
654
655        let num_values = (len - 16) / child_size;
656
657        fn create_choice<'de, E>(
658            choice_type: u32,
659            values: Vec<E>,
660            flags: u32,
661        ) -> Result<Choice<E>, DeserializeError<&'de [u8]>>
662        where
663            E: CanonicalFixedSizedPod + FixedSizedPod + Copy,
664        {
665            let flags = ChoiceFlags::from_bits_retain(flags);
666
667            match choice_type {
668                spa_sys::SPA_CHOICE_None => {
669                    if values.is_empty() {
670                        Err(DeserializeError::MissingChoiceValues)
671                    } else {
672                        Ok(Choice(ChoiceFlags::empty(), ChoiceEnum::None(values[0])))
673                    }
674                }
675                spa_sys::SPA_CHOICE_Range => {
676                    if values.len() < 3 {
677                        Err(DeserializeError::MissingChoiceValues)
678                    } else {
679                        Ok(Choice(
680                            flags,
681                            ChoiceEnum::Range {
682                                default: values[0],
683                                min: values[1],
684                                max: values[2],
685                            },
686                        ))
687                    }
688                }
689                spa_sys::SPA_CHOICE_Step => {
690                    if values.len() < 4 {
691                        Err(DeserializeError::MissingChoiceValues)
692                    } else {
693                        Ok(Choice(
694                            flags,
695                            ChoiceEnum::Step {
696                                default: values[0],
697                                min: values[1],
698                                max: values[2],
699                                step: values[3],
700                            },
701                        ))
702                    }
703                }
704                spa_sys::SPA_CHOICE_Enum => {
705                    if values.is_empty() {
706                        Err(DeserializeError::MissingChoiceValues)
707                    } else {
708                        Ok(Choice(
709                            flags,
710                            ChoiceEnum::Enum {
711                                default: values[0],
712                                alternatives: values[1..].to_vec(),
713                            },
714                        ))
715                    }
716                }
717                spa_sys::SPA_CHOICE_Flags => {
718                    if values.is_empty() {
719                        Err(DeserializeError::MissingChoiceValues)
720                    } else {
721                        Ok(Choice(
722                            flags,
723                            ChoiceEnum::Flags {
724                                default: values[0],
725                                flags: values[1..].to_vec(),
726                            },
727                        ))
728                    }
729                }
730                _ => Err(DeserializeError::InvalidChoiceType),
731            }
732        }
733
734        match child_type {
735            spa_sys::SPA_TYPE_Bool => {
736                let (values, success) = self.deserialize_choice_values::<bool>(num_values)?;
737                let choice = create_choice(choice_type, values, flags)?;
738                Ok((visitor.visit_choice_bool(choice)?, success))
739            }
740            spa_sys::SPA_TYPE_Int => {
741                let (values, success) = self.deserialize_choice_values::<i32>(num_values)?;
742                let choice = create_choice(choice_type, values, flags)?;
743                Ok((visitor.visit_choice_i32(choice)?, success))
744            }
745            spa_sys::SPA_TYPE_Long => {
746                let (values, success) = self.deserialize_choice_values::<i64>(num_values)?;
747                let choice = create_choice(choice_type, values, flags)?;
748                Ok((visitor.visit_choice_i64(choice)?, success))
749            }
750            spa_sys::SPA_TYPE_Float => {
751                let (values, success) = self.deserialize_choice_values::<f32>(num_values)?;
752                let choice = create_choice(choice_type, values, flags)?;
753                Ok((visitor.visit_choice_f32(choice)?, success))
754            }
755            spa_sys::SPA_TYPE_Double => {
756                let (values, success) = self.deserialize_choice_values::<f64>(num_values)?;
757                let choice = create_choice(choice_type, values, flags)?;
758                Ok((visitor.visit_choice_f64(choice)?, success))
759            }
760            spa_sys::SPA_TYPE_Id => {
761                let (values, success) = self.deserialize_choice_values::<Id>(num_values)?;
762                let choice = create_choice(choice_type, values, flags)?;
763                Ok((visitor.visit_choice_id(choice)?, success))
764            }
765            spa_sys::SPA_TYPE_Rectangle => {
766                let (values, success) = self.deserialize_choice_values::<Rectangle>(num_values)?;
767                let choice = create_choice(choice_type, values, flags)?;
768                Ok((visitor.visit_choice_rectangle(choice)?, success))
769            }
770            spa_sys::SPA_TYPE_Fraction => {
771                let (values, success) = self.deserialize_choice_values::<Fraction>(num_values)?;
772                let choice = create_choice(choice_type, values, flags)?;
773                Ok((visitor.visit_choice_fraction(choice)?, success))
774            }
775            spa_sys::SPA_TYPE_Fd => {
776                let (values, success) = self.deserialize_choice_values::<Fd>(num_values)?;
777                let choice = create_choice(choice_type, values, flags)?;
778                Ok((visitor.visit_choice_fd(choice)?, success))
779            }
780            _ => Err(DeserializeError::InvalidType),
781        }
782    }
783
784    /// Deserialize a pointer pod.
785    pub fn deserialize_pointer<V>(
786        mut self,
787        visitor: V,
788    ) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
789    where
790        V: Visitor<'de>,
791    {
792        let len = self.parse(Self::header(spa_sys::SPA_TYPE_Pointer))?;
793        let (type_, _padding) = self.parse(move |input| {
794            pair(u32(Endianness::Native), u32(Endianness::Native)).parse(input)
795        })?;
796        let ptr_size = len - 8;
797
798        let res = match ptr_size {
799            8 => {
800                let ptr: u64 = self.parse(|input| u64(Endianness::Native).parse(input))?;
801                visitor.visit_pointer(type_, ptr as *const c_void)?
802            }
803            4 => {
804                let ptr: u32 = self.parse(|input| u32(Endianness::Native).parse(input))?;
805                visitor.visit_pointer(type_, ptr as *const c_void)?
806            }
807            _ => panic!("unsupported pointer size {ptr_size}"),
808        };
809
810        Ok((res, DeserializeSuccess(self)))
811    }
812
813    /// Deserialize any kind of pod using a visitor producing [`Value`].
814    pub fn deserialize_any(
815        self,
816    ) -> Result<(Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
817        let type_ = self.peek(Self::type_())?;
818
819        match type_ {
820            spa_sys::SPA_TYPE_None => self.deserialize_none(ValueVisitor),
821            spa_sys::SPA_TYPE_Bool => self.deserialize_bool(ValueVisitor),
822            spa_sys::SPA_TYPE_Id => self.deserialize_id(ValueVisitor),
823            spa_sys::SPA_TYPE_Int => self.deserialize_int(ValueVisitor),
824            spa_sys::SPA_TYPE_Long => self.deserialize_long(ValueVisitor),
825            spa_sys::SPA_TYPE_Float => self.deserialize_float(ValueVisitor),
826            spa_sys::SPA_TYPE_Double => self.deserialize_double(ValueVisitor),
827            spa_sys::SPA_TYPE_String => self.deserialize_str(ValueVisitor),
828            spa_sys::SPA_TYPE_Bytes => self.deserialize_bytes(ValueVisitor),
829            spa_sys::SPA_TYPE_Rectangle => self.deserialize_rectangle(ValueVisitor),
830            spa_sys::SPA_TYPE_Fraction => self.deserialize_fraction(ValueVisitor),
831            spa_sys::SPA_TYPE_Fd => self.deserialize_fd(ValueVisitor),
832            spa_sys::SPA_TYPE_Struct => self.deserialize_struct(ValueVisitor),
833            spa_sys::SPA_TYPE_Array => self.deserialize_array_any(),
834            spa_sys::SPA_TYPE_Object => self.deserialize_object(ValueVisitor),
835            spa_sys::SPA_TYPE_Choice => self.deserialize_choice(ValueVisitor),
836            spa_sys::SPA_TYPE_Pointer => self.deserialize_pointer(ValueVisitor),
837            _ => Err(DeserializeError::InvalidType),
838        }
839    }
840
841    fn deserialize_array_any(
842        self,
843    ) -> Result<(Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
844        let child_type =
845            self.peek(move |input| preceded(Self::type_(), Self::type_()).parse(input))?;
846
847        let (array, success) = match child_type {
848            spa_sys::SPA_TYPE_None => {
849                let (elements, success) = self.deserialize_array_vec::<()>()?;
850                let array = ValueArrayNoneVisitor.visit_array(elements)?;
851                (array, success)
852            }
853            spa_sys::SPA_TYPE_Bool => {
854                let (elements, success) = self.deserialize_array_vec::<bool>()?;
855                let array = ValueArrayBoolVisitor.visit_array(elements)?;
856                (array, success)
857            }
858            spa_sys::SPA_TYPE_Id => {
859                let (elements, success) = self.deserialize_array_vec::<Id>()?;
860                let array = ValueArrayIdVisitor.visit_array(elements)?;
861                (array, success)
862            }
863            spa_sys::SPA_TYPE_Int => {
864                let (elements, success) = self.deserialize_array_vec::<i32>()?;
865                let array = ValueArrayIntVisitor.visit_array(elements)?;
866                (array, success)
867            }
868            spa_sys::SPA_TYPE_Long => {
869                let (elements, success) = self.deserialize_array_vec::<i64>()?;
870                let array = ValueArrayLongVisitor.visit_array(elements)?;
871                (array, success)
872            }
873            spa_sys::SPA_TYPE_Float => {
874                let (elements, success) = self.deserialize_array_vec::<f32>()?;
875                let array = ValueArrayFloatVisitor.visit_array(elements)?;
876                (array, success)
877            }
878            spa_sys::SPA_TYPE_Double => {
879                let (elements, success) = self.deserialize_array_vec::<f64>()?;
880                let array = ValueArrayDoubleVisitor.visit_array(elements)?;
881                (array, success)
882            }
883            spa_sys::SPA_TYPE_Rectangle => {
884                let (elements, success) = self.deserialize_array_vec::<Rectangle>()?;
885                let array = ValueArrayRectangleVisitor.visit_array(elements)?;
886                (array, success)
887            }
888            spa_sys::SPA_TYPE_Fraction => {
889                let (elements, success) = self.deserialize_array_vec::<Fraction>()?;
890                let array = ValueArrayFractionVisitor.visit_array(elements)?;
891                (array, success)
892            }
893            spa_sys::SPA_TYPE_Fd => {
894                let (elements, success) = self.deserialize_array_vec::<Fd>()?;
895                let array = ValueArrayFdVisitor.visit_array(elements)?;
896                (array, success)
897            }
898            _ => return Err(DeserializeError::InvalidType),
899        };
900
901        Ok((Value::ValueArray(array), success))
902    }
903
904    /// Variant of [`Self::deserialize_from`] returning the parsed value as a [`Value`].
905    pub fn deserialize_any_from(
906        input: &'de [u8],
907    ) -> Result<(&'de [u8], Value), DeserializeError<&'de [u8]>> {
908        Self::deserialize_from(input)
909    }
910}
911
912/// This struct handles deserializing arrays.
913///
914/// It can be obtained by calling [`PodDeserializer::deserialize_array`].
915///
916/// The exact number of elements that was returned from that call must be deserialized
917/// using the [`deserialize_element`](`Self::deserialize_element`) function,
918/// followed by calling its [`end`](`Self::end`) function to finish deserialization of the array.
919pub struct ArrayPodDeserializer<'de, E: FixedSizedPod> {
920    deserializer: PodDeserializer<'de>,
921    // The total number of elements that must be deserialized from this array.
922    length: u32,
923    // The number of elements that have been deserialized so far.
924    deserialized: u32,
925    /// The struct has the type parameter E to ensure all deserialized elements are the same type,
926    /// but doesn't actually own any E, so we need the `PhantomData<E>` instead.
927    _phantom: PhantomData<E>,
928}
929
930impl<'de, E: FixedSizedPod> ArrayPodDeserializer<'de, E> {
931    /// Deserialize a single element.
932    ///
933    /// # Panics
934    /// Panics if there are no elements left to deserialize.
935    pub fn deserialize_element(&mut self) -> Result<E, DeserializeError<&'de [u8]>> {
936        if !self.deserialized < self.length {
937            panic!("No elements left in the pod to deserialize");
938        }
939
940        let result = self
941            .deserializer
942            .parse(E::CanonicalType::deserialize_body)
943            .map(|res| E::from_canonical_type(&res))
944            .map_err(|err| err.into());
945
946        self.deserialized += 1;
947        result
948    }
949
950    /// Finish deserializing the array.
951    ///
952    /// # Panics
953    /// Panics if not all elements of the array were deserialized.
954    pub fn end(mut self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
955        assert!(
956            self.length == self.deserialized,
957            "Not all fields were deserialized from the array pod"
958        );
959
960        // Deserialize remaining padding bytes.
961        let bytes_read = self.deserialized * E::CanonicalType::SIZE;
962        let padding = if bytes_read % 8 == 0 {
963            0
964        } else {
965            8 - (bytes_read as usize % 8)
966        };
967        self.deserializer.parse(take(padding))?;
968
969        Ok(DeserializeSuccess(self.deserializer))
970    }
971}
972
973/// This struct handles deserializing structs.
974///
975/// It can be obtained by calling [`PodDeserializer::deserialize_struct`].
976///
977/// Fields of the struct must be deserialized using its [`deserialize_field`](`Self::deserialize_field`)
978/// until it returns `None`.
979/// followed by calling its [`end`](`Self::end`) function to finish deserialization of the struct.
980pub struct StructPodDeserializer<'de> {
981    /// The deserializer is saved in an option, but can be expected to always be a `Some`
982    /// when `deserialize_field()` or `end()` is called.
983    ///
984    /// `deserialize_field()` `take()`s the deserializer, uses it to deserialize the field,
985    /// and then puts the deserializer back inside.
986    deserializer: Option<PodDeserializer<'de>>,
987    /// Remaining struct pod body length in bytes
988    remaining: u32,
989}
990
991impl<'de> StructPodDeserializer<'de> {
992    /// Deserialize a single field of the struct
993    ///
994    /// Returns `Some` when a field was successfully deserialized and `None` when all fields have been read.
995    pub fn deserialize_field<P: PodDeserialize<'de>>(
996        &mut self,
997    ) -> Result<Option<P>, DeserializeError<&'de [u8]>> {
998        if self.remaining == 0 {
999            Ok(None)
1000        } else {
1001            let deserializer = self
1002                .deserializer
1003                .take()
1004                .expect("StructPodDeserializer does not contain a deserializer");
1005
1006            // The amount of input bytes remaining before deserializing the element.
1007            let remaining_input_len = deserializer.input.len();
1008
1009            let (res, success) = P::deserialize(deserializer)?;
1010
1011            // The amount of bytes deserialized is the length of the remaining input
1012            // minus the length of the remaining input now.
1013            self.remaining -= remaining_input_len as u32 - success.0.input.len() as u32;
1014
1015            self.deserializer = Some(success.0);
1016
1017            Ok(Some(res))
1018        }
1019    }
1020
1021    /// Finish deserialization of the pod.
1022    ///
1023    /// # Panics
1024    /// Panics if not all fields of the pod have been deserialized.
1025    pub fn end(self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
1026        assert!(
1027            self.remaining == 0,
1028            "Not all fields have been deserialized from the struct"
1029        );
1030
1031        // No padding parsing needed: Last field will already end aligned.
1032
1033        Ok(DeserializeSuccess(self.deserializer.expect(
1034            "StructPodDeserializer does not contain a deserializer",
1035        )))
1036    }
1037}
1038
1039/// This struct handles deserializing objects.
1040///
1041/// It can be obtained by calling [`PodDeserializer::deserialize_object`].
1042///
1043/// Properties of the object must be deserialized using its [`deserialize_property`](`Self::deserialize_property`)
1044/// until it returns `None`.
1045/// followed by calling its [`end`](`Self::end`) function to finish deserialization of the object.
1046pub struct ObjectPodDeserializer<'de> {
1047    /// The deserializer is saved in an option, but can be expected to always be a `Some`
1048    /// when `deserialize_property()` or `end()` is called.
1049    ///
1050    /// `deserialize_property()` `take()`s the deserializer, uses it to deserialize the property,
1051    /// and then puts the deserializer back inside.
1052    deserializer: Option<PodDeserializer<'de>>,
1053    /// Remaining object pod body length in bytes
1054    remaining: u32,
1055    /// type of the object
1056    object_type: u32,
1057    /// id of the object
1058    object_id: u32,
1059}
1060
1061impl<'de> ObjectPodDeserializer<'de> {
1062    /// Deserialize a single property of the object.
1063    ///
1064    /// Returns `Some` when a property was successfully deserialized and `None` when all properties have been read.
1065    #[allow(clippy::type_complexity)]
1066    pub fn deserialize_property<P: PodDeserialize<'de>>(
1067        &mut self,
1068    ) -> Result<Option<(P, u32, PropertyFlags)>, DeserializeError<&'de [u8]>> {
1069        if self.remaining == 0 {
1070            Ok(None)
1071        } else {
1072            let mut deserializer = self
1073                .deserializer
1074                .take()
1075                .expect("ObjectPodDeserializer does not contain a deserializer");
1076
1077            // The amount of input bytes remaining before deserializing the element.
1078            let remaining_input_len = deserializer.input.len();
1079
1080            let key = deserializer.parse(u32(Endianness::Native))?;
1081            let flags = deserializer.parse(u32(Endianness::Native))?;
1082
1083            let flags = PropertyFlags::from_bits_retain(flags);
1084            let (res, success) = P::deserialize(deserializer)?;
1085
1086            // The amount of bytes deserialized is the length of the remaining input
1087            // minus the length of the remaining input now.
1088            self.remaining -= remaining_input_len as u32 - success.0.input.len() as u32;
1089
1090            self.deserializer = Some(success.0);
1091
1092            Ok(Some((res, key, flags)))
1093        }
1094    }
1095
1096    /// Variant of [`Self::deserialize_property`] ensuring the property has a given key.
1097    ///
1098    /// Returns [`DeserializeError::PropertyMissing`] if the property is missing
1099    /// and [`DeserializeError::PropertyWrongKey`] if the property does not have the
1100    /// expected key.
1101    pub fn deserialize_property_key<P: PodDeserialize<'de>>(
1102        &mut self,
1103        key: u32,
1104    ) -> Result<(P, PropertyFlags), DeserializeError<&'de [u8]>> {
1105        let (prop, k, flags) = self
1106            .deserialize_property()?
1107            .ok_or(DeserializeError::PropertyMissing)?;
1108
1109        if k != key {
1110            Err(DeserializeError::PropertyWrongKey(k))
1111        } else {
1112            Ok((prop, flags))
1113        }
1114    }
1115
1116    /// Finish deserialization of the pod.
1117    ///
1118    /// # Panics
1119    /// Panics if not all properties of the pod have been deserialized.
1120    pub fn end(self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
1121        assert!(
1122            self.remaining == 0,
1123            "Not all properties have been deserialized from the object"
1124        );
1125
1126        // No padding parsing needed: Last field will already end aligned.
1127
1128        Ok(DeserializeSuccess(self.deserializer.expect(
1129            "ObjectPodDeserializer does not contain a deserializer",
1130        )))
1131    }
1132}
1133#[derive(Debug, PartialEq)]
1134/// Represent an error raised when deserializing a pod
1135pub enum DeserializeError<I> {
1136    /// Parsing error
1137    Nom(nom::Err<nom::error::Error<I>>),
1138    /// The visitor does not support the type
1139    UnsupportedType,
1140    /// The type is either invalid or not yet supported
1141    InvalidType,
1142    /// The property is missing from the object
1143    PropertyMissing,
1144    /// The property does not have the expected key
1145    PropertyWrongKey(u32),
1146    /// Invalid choice type
1147    InvalidChoiceType,
1148    /// Values are missing in the choice pod
1149    MissingChoiceValues,
1150}
1151
1152impl<I> From<nom::Err<nom::error::Error<I>>> for DeserializeError<I> {
1153    fn from(err: nom::Err<nom::error::Error<I>>) -> Self {
1154        DeserializeError::Nom(err)
1155    }
1156}
1157
1158/// This trait represents a visitor is "driven" by the deserializer to construct an instance of your type.
1159pub trait Visitor<'de>: Sized {
1160    /// The value produced by this visitor
1161    type Value;
1162    /// The element type [`Visitor::visit_array`] is expecting as input.
1163    /// Only used for visitors implementing this method,
1164    /// [`std::convert::Infallible`] can be used as a default.
1165    type ArrayElem;
1166
1167    /// The input contains a `none`.
1168    fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1169        Err(DeserializeError::UnsupportedType)
1170    }
1171
1172    /// The input contains a `bool`.
1173    fn visit_bool(&self, _v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1174        Err(DeserializeError::UnsupportedType)
1175    }
1176
1177    /// The input contains an `i32`.
1178    fn visit_int(&self, _v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1179        Err(DeserializeError::UnsupportedType)
1180    }
1181
1182    /// The input contains an `i64`.
1183    fn visit_long(&self, _v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1184        Err(DeserializeError::UnsupportedType)
1185    }
1186
1187    /// The input contains an `f32`.
1188    fn visit_float(&self, _v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1189        Err(DeserializeError::UnsupportedType)
1190    }
1191
1192    /// The input contains an `f64`.
1193    fn visit_double(&self, _v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1194        Err(DeserializeError::UnsupportedType)
1195    }
1196
1197    /// The input contains a string.
1198    fn visit_string(&self, _v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1199        Err(DeserializeError::UnsupportedType)
1200    }
1201
1202    /// The input contains a bytes array.
1203    fn visit_bytes(&self, _v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1204        Err(DeserializeError::UnsupportedType)
1205    }
1206
1207    /// The input contains a [`Rectangle`].
1208    fn visit_rectangle(&self, _v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1209        Err(DeserializeError::UnsupportedType)
1210    }
1211
1212    /// The input contains a [`Fraction`].
1213    fn visit_fraction(&self, _v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1214        Err(DeserializeError::UnsupportedType)
1215    }
1216
1217    /// The input contains an [`Id`].
1218    fn visit_id(&self, _v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1219        Err(DeserializeError::UnsupportedType)
1220    }
1221
1222    /// The input contains an [`Fd`].
1223    fn visit_fd(&self, _v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1224        Err(DeserializeError::UnsupportedType)
1225    }
1226
1227    /// The input contains a structure.
1228    fn visit_struct(
1229        &self,
1230        _struct_deserializer: &mut StructPodDeserializer<'de>,
1231    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1232        Err(DeserializeError::UnsupportedType)
1233    }
1234
1235    /// The input contains an array.
1236    fn visit_array(
1237        &self,
1238        _elements: Vec<Self::ArrayElem>,
1239    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1240        Err(DeserializeError::UnsupportedType)
1241    }
1242
1243    /// The input contains an object.
1244    fn visit_object(
1245        &self,
1246        _object_deserializer: &mut ObjectPodDeserializer<'de>,
1247    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1248        Err(DeserializeError::UnsupportedType)
1249    }
1250
1251    /// The input contains an [`i32`] choice.
1252    fn visit_choice_bool(
1253        &self,
1254        _choice: Choice<bool>,
1255    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1256        Err(DeserializeError::UnsupportedType)
1257    }
1258
1259    /// The input contains an [`i32`] choice.
1260    fn visit_choice_i32(
1261        &self,
1262        _choice: Choice<i32>,
1263    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1264        Err(DeserializeError::UnsupportedType)
1265    }
1266
1267    /// The input contains an [`i64`] choice.
1268    fn visit_choice_i64(
1269        &self,
1270        _choice: Choice<i64>,
1271    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1272        Err(DeserializeError::UnsupportedType)
1273    }
1274
1275    /// The input contains a [`f32`] choice.
1276    fn visit_choice_f32(
1277        &self,
1278        _choice: Choice<f32>,
1279    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1280        Err(DeserializeError::UnsupportedType)
1281    }
1282
1283    /// The input contains a [`f64`] choice.
1284    fn visit_choice_f64(
1285        &self,
1286        _choice: Choice<f64>,
1287    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1288        Err(DeserializeError::UnsupportedType)
1289    }
1290
1291    /// The input contains a [`Id`] choice.
1292    fn visit_choice_id(
1293        &self,
1294        _choice: Choice<Id>,
1295    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1296        Err(DeserializeError::UnsupportedType)
1297    }
1298
1299    /// The input contains a [`Rectangle`] choice.
1300    fn visit_choice_rectangle(
1301        &self,
1302        _choice: Choice<Rectangle>,
1303    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1304        Err(DeserializeError::UnsupportedType)
1305    }
1306
1307    /// The input contains a [`Fraction`] choice.
1308    fn visit_choice_fraction(
1309        &self,
1310        _choice: Choice<Fraction>,
1311    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1312        Err(DeserializeError::UnsupportedType)
1313    }
1314
1315    /// The input contains a [`Fd`] choice.
1316    fn visit_choice_fd(
1317        &self,
1318        _choice: Choice<Fd>,
1319    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1320        Err(DeserializeError::UnsupportedType)
1321    }
1322
1323    /// The input contains a pointer.
1324    fn visit_pointer(
1325        &self,
1326        _type: u32,
1327        _pointer: *const c_void,
1328    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1329        Err(DeserializeError::UnsupportedType)
1330    }
1331}
1332
1333/// A visitor producing `()` for none values.
1334pub struct NoneVisitor;
1335
1336impl<'de> Visitor<'de> for NoneVisitor {
1337    type Value = ();
1338    type ArrayElem = Infallible;
1339
1340    fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1341        Ok(())
1342    }
1343}
1344
1345/// A visitor producing [`bool`] for boolean values.
1346pub struct BoolVisitor;
1347
1348impl<'de> Visitor<'de> for BoolVisitor {
1349    type Value = bool;
1350    type ArrayElem = Infallible;
1351
1352    fn visit_bool(&self, v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1353        Ok(v)
1354    }
1355}
1356
1357/// A visitor producing [`i32`] for integer values.
1358pub struct IntVisitor;
1359
1360impl<'de> Visitor<'de> for IntVisitor {
1361    type Value = i32;
1362    type ArrayElem = Infallible;
1363
1364    fn visit_int(&self, v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1365        Ok(v)
1366    }
1367}
1368
1369/// A visitor producing [`i64`] for long values.
1370pub struct LongVisitor;
1371
1372impl<'de> Visitor<'de> for LongVisitor {
1373    type Value = i64;
1374    type ArrayElem = Infallible;
1375
1376    fn visit_long(&self, v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1377        Ok(v)
1378    }
1379}
1380
1381/// A visitor producing [`f32`] for float values.
1382pub struct FloatVisitor;
1383
1384impl<'de> Visitor<'de> for FloatVisitor {
1385    type Value = f32;
1386    type ArrayElem = Infallible;
1387
1388    fn visit_float(&self, v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1389        Ok(v)
1390    }
1391}
1392
1393/// A visitor producing [`f64`] for double values.
1394pub struct DoubleVisitor;
1395
1396impl<'de> Visitor<'de> for DoubleVisitor {
1397    type Value = f64;
1398    type ArrayElem = Infallible;
1399
1400    fn visit_double(&self, v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1401        Ok(v)
1402    }
1403}
1404
1405/// A visitor producing [`&str`] for string values.
1406pub struct StringVisitor;
1407
1408impl<'de> Visitor<'de> for StringVisitor {
1409    type Value = &'de str;
1410    type ArrayElem = Infallible;
1411
1412    fn visit_string(&self, v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1413        Ok(v)
1414    }
1415}
1416
1417/// A visitor producing [`&[u8]`] for bytes values.
1418pub struct BytesVisitor;
1419
1420impl<'de> Visitor<'de> for BytesVisitor {
1421    type Value = &'de [u8];
1422    type ArrayElem = Infallible;
1423
1424    fn visit_bytes(&self, v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1425        Ok(v)
1426    }
1427}
1428
1429/// A visitor producing [`Rectangle`] for rectangle values.
1430pub struct RectangleVisitor;
1431
1432impl<'de> Visitor<'de> for RectangleVisitor {
1433    type Value = Rectangle;
1434    type ArrayElem = Infallible;
1435
1436    fn visit_rectangle(&self, v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1437        Ok(v)
1438    }
1439}
1440
1441/// A visitor producing [`Fraction`] for fraction values.
1442pub struct FractionVisitor;
1443
1444impl<'de> Visitor<'de> for FractionVisitor {
1445    type Value = Fraction;
1446    type ArrayElem = Infallible;
1447
1448    fn visit_fraction(&self, v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1449        Ok(v)
1450    }
1451}
1452
1453/// A visitor producing [`Id`] for ID values.
1454pub struct IdVisitor;
1455
1456impl<'de> Visitor<'de> for IdVisitor {
1457    type Value = Id;
1458    type ArrayElem = Infallible;
1459
1460    fn visit_id(&self, v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1461        Ok(v)
1462    }
1463}
1464
1465/// A visitor producing [`Fd`] for file descriptor values.
1466pub struct FdVisitor;
1467
1468impl<'de> Visitor<'de> for FdVisitor {
1469    type Value = Fd;
1470    type ArrayElem = Infallible;
1471
1472    fn visit_fd(&self, v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1473        Ok(v)
1474    }
1475}
1476
1477/// A visitor producing [`Vec`] for array values.
1478pub struct VecVisitor<E: FixedSizedPod> {
1479    _phantom: PhantomData<E>,
1480}
1481
1482impl<E: FixedSizedPod> Default for VecVisitor<E> {
1483    fn default() -> Self {
1484        Self {
1485            _phantom: PhantomData,
1486        }
1487    }
1488}
1489
1490impl<'de, E: CanonicalFixedSizedPod + std::marker::Copy> Visitor<'de> for VecVisitor<E> {
1491    type Value = Vec<E>;
1492    type ArrayElem = E;
1493
1494    fn visit_array(&self, elements: Vec<E>) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1495        Ok(elements)
1496    }
1497}
1498
1499/// A visitor producing [`Value`] for all type of values.
1500pub struct ValueVisitor;
1501
1502impl<'de> Visitor<'de> for ValueVisitor {
1503    type Value = Value;
1504    type ArrayElem = std::convert::Infallible;
1505
1506    fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1507        Ok(Value::None)
1508    }
1509
1510    fn visit_bool(&self, v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1511        Ok(Value::Bool(v))
1512    }
1513
1514    fn visit_int(&self, v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1515        Ok(Value::Int(v))
1516    }
1517
1518    fn visit_long(&self, v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1519        Ok(Value::Long(v))
1520    }
1521
1522    fn visit_float(&self, v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1523        Ok(Value::Float(v))
1524    }
1525
1526    fn visit_double(&self, v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1527        Ok(Value::Double(v))
1528    }
1529
1530    fn visit_string(&self, v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1531        Ok(Value::String(v.to_string()))
1532    }
1533
1534    fn visit_bytes(&self, v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1535        Ok(Value::Bytes(v.to_vec()))
1536    }
1537
1538    fn visit_rectangle(&self, v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1539        Ok(Value::Rectangle(v))
1540    }
1541
1542    fn visit_fraction(&self, v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1543        Ok(Value::Fraction(v))
1544    }
1545
1546    fn visit_id(&self, v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1547        Ok(Value::Id(v))
1548    }
1549
1550    fn visit_fd(&self, v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1551        Ok(Value::Fd(v))
1552    }
1553
1554    fn visit_struct(
1555        &self,
1556        struct_deserializer: &mut StructPodDeserializer<'de>,
1557    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1558        let mut res = Vec::new();
1559
1560        while let Some(value) = struct_deserializer.deserialize_field()? {
1561            res.push(value);
1562        }
1563
1564        Ok(Value::Struct(res))
1565    }
1566
1567    fn visit_object(
1568        &self,
1569        object_deserializer: &mut ObjectPodDeserializer<'de>,
1570    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1571        let mut properties = Vec::new();
1572
1573        while let Some((value, key, flags)) = object_deserializer.deserialize_property()? {
1574            let prop = Property { key, flags, value };
1575            properties.push(prop);
1576        }
1577
1578        let object = Object {
1579            type_: object_deserializer.object_type,
1580            id: object_deserializer.object_id,
1581            properties,
1582        };
1583
1584        Ok(Value::Object(object))
1585    }
1586
1587    fn visit_choice_bool(
1588        &self,
1589        choice: Choice<bool>,
1590    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1591        Ok(Value::Choice(ChoiceValue::Bool(choice)))
1592    }
1593
1594    fn visit_choice_i32(
1595        &self,
1596        choice: Choice<i32>,
1597    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1598        Ok(Value::Choice(ChoiceValue::Int(choice)))
1599    }
1600
1601    fn visit_choice_i64(
1602        &self,
1603        choice: Choice<i64>,
1604    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1605        Ok(Value::Choice(ChoiceValue::Long(choice)))
1606    }
1607
1608    fn visit_choice_f32(
1609        &self,
1610        choice: Choice<f32>,
1611    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1612        Ok(Value::Choice(ChoiceValue::Float(choice)))
1613    }
1614
1615    fn visit_choice_f64(
1616        &self,
1617        choice: Choice<f64>,
1618    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1619        Ok(Value::Choice(ChoiceValue::Double(choice)))
1620    }
1621
1622    fn visit_choice_id(
1623        &self,
1624        choice: Choice<Id>,
1625    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1626        Ok(Value::Choice(ChoiceValue::Id(choice)))
1627    }
1628
1629    fn visit_choice_rectangle(
1630        &self,
1631        choice: Choice<Rectangle>,
1632    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1633        Ok(Value::Choice(ChoiceValue::Rectangle(choice)))
1634    }
1635
1636    fn visit_choice_fraction(
1637        &self,
1638        choice: Choice<Fraction>,
1639    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1640        Ok(Value::Choice(ChoiceValue::Fraction(choice)))
1641    }
1642
1643    fn visit_choice_fd(
1644        &self,
1645        choice: Choice<Fd>,
1646    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1647        Ok(Value::Choice(ChoiceValue::Fd(choice)))
1648    }
1649
1650    fn visit_pointer(
1651        &self,
1652        type_: u32,
1653        pointer: *const c_void,
1654    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1655        Ok(Value::Pointer(type_, pointer))
1656    }
1657}
1658
1659struct ValueArrayNoneVisitor;
1660
1661impl<'de> Visitor<'de> for ValueArrayNoneVisitor {
1662    type Value = ValueArray;
1663    type ArrayElem = ();
1664
1665    fn visit_array(
1666        &self,
1667        elements: Vec<Self::ArrayElem>,
1668    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1669        Ok(ValueArray::None(elements))
1670    }
1671}
1672
1673struct ValueArrayBoolVisitor;
1674
1675impl<'de> Visitor<'de> for ValueArrayBoolVisitor {
1676    type Value = ValueArray;
1677    type ArrayElem = bool;
1678
1679    fn visit_array(
1680        &self,
1681        elements: Vec<Self::ArrayElem>,
1682    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1683        Ok(ValueArray::Bool(elements))
1684    }
1685}
1686
1687struct ValueArrayIdVisitor;
1688
1689impl<'de> Visitor<'de> for ValueArrayIdVisitor {
1690    type Value = ValueArray;
1691    type ArrayElem = Id;
1692
1693    fn visit_array(
1694        &self,
1695        elements: Vec<Self::ArrayElem>,
1696    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1697        Ok(ValueArray::Id(elements))
1698    }
1699}
1700
1701struct ValueArrayIntVisitor;
1702
1703impl<'de> Visitor<'de> for ValueArrayIntVisitor {
1704    type Value = ValueArray;
1705    type ArrayElem = i32;
1706
1707    fn visit_array(
1708        &self,
1709        elements: Vec<Self::ArrayElem>,
1710    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1711        Ok(ValueArray::Int(elements))
1712    }
1713}
1714
1715struct ValueArrayLongVisitor;
1716
1717impl<'de> Visitor<'de> for ValueArrayLongVisitor {
1718    type Value = ValueArray;
1719    type ArrayElem = i64;
1720
1721    fn visit_array(
1722        &self,
1723        elements: Vec<Self::ArrayElem>,
1724    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1725        Ok(ValueArray::Long(elements))
1726    }
1727}
1728
1729struct ValueArrayFloatVisitor;
1730
1731impl<'de> Visitor<'de> for ValueArrayFloatVisitor {
1732    type Value = ValueArray;
1733    type ArrayElem = f32;
1734
1735    fn visit_array(
1736        &self,
1737        elements: Vec<Self::ArrayElem>,
1738    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1739        Ok(ValueArray::Float(elements))
1740    }
1741}
1742
1743struct ValueArrayDoubleVisitor;
1744
1745impl<'de> Visitor<'de> for ValueArrayDoubleVisitor {
1746    type Value = ValueArray;
1747    type ArrayElem = f64;
1748
1749    fn visit_array(
1750        &self,
1751        elements: Vec<Self::ArrayElem>,
1752    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1753        Ok(ValueArray::Double(elements))
1754    }
1755}
1756
1757struct ValueArrayRectangleVisitor;
1758
1759impl<'de> Visitor<'de> for ValueArrayRectangleVisitor {
1760    type Value = ValueArray;
1761    type ArrayElem = Rectangle;
1762
1763    fn visit_array(
1764        &self,
1765        elements: Vec<Self::ArrayElem>,
1766    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1767        Ok(ValueArray::Rectangle(elements))
1768    }
1769}
1770
1771struct ValueArrayFractionVisitor;
1772
1773impl<'de> Visitor<'de> for ValueArrayFractionVisitor {
1774    type Value = ValueArray;
1775    type ArrayElem = Fraction;
1776
1777    fn visit_array(
1778        &self,
1779        elements: Vec<Self::ArrayElem>,
1780    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1781        Ok(ValueArray::Fraction(elements))
1782    }
1783}
1784
1785struct ValueArrayFdVisitor;
1786
1787impl<'de> Visitor<'de> for ValueArrayFdVisitor {
1788    type Value = ValueArray;
1789    type ArrayElem = Fd;
1790
1791    fn visit_array(
1792        &self,
1793        elements: Vec<Self::ArrayElem>,
1794    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1795        Ok(ValueArray::Fd(elements))
1796    }
1797}
1798
1799/// A visitor producing [`Choice`] for boolean choice values.
1800pub struct ChoiceBoolVisitor;
1801
1802impl<'de> Visitor<'de> for ChoiceBoolVisitor {
1803    type Value = Choice<bool>;
1804    type ArrayElem = Infallible;
1805
1806    fn visit_choice_bool(
1807        &self,
1808        choice: Choice<bool>,
1809    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1810        Ok(choice)
1811    }
1812}
1813
1814/// A visitor producing [`Choice`] for integer choice values.
1815pub struct ChoiceIntVisitor;
1816
1817impl<'de> Visitor<'de> for ChoiceIntVisitor {
1818    type Value = Choice<i32>;
1819    type ArrayElem = Infallible;
1820
1821    fn visit_choice_i32(
1822        &self,
1823        choice: Choice<i32>,
1824    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1825        Ok(choice)
1826    }
1827}
1828
1829/// A visitor producing [`Choice`] for long integer choice values.
1830pub struct ChoiceLongVisitor;
1831
1832impl<'de> Visitor<'de> for ChoiceLongVisitor {
1833    type Value = Choice<i64>;
1834    type ArrayElem = Infallible;
1835
1836    fn visit_choice_i64(
1837        &self,
1838        choice: Choice<i64>,
1839    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1840        Ok(choice)
1841    }
1842}
1843
1844/// A visitor producing [`Choice`] for floating choice values.
1845pub struct ChoiceFloatVisitor;
1846
1847impl<'de> Visitor<'de> for ChoiceFloatVisitor {
1848    type Value = Choice<f32>;
1849    type ArrayElem = Infallible;
1850
1851    fn visit_choice_f32(
1852        &self,
1853        choice: Choice<f32>,
1854    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1855        Ok(choice)
1856    }
1857}
1858
1859/// A visitor producing [`Choice`] for double floating choice values.
1860pub struct ChoiceDoubleVisitor;
1861
1862impl<'de> Visitor<'de> for ChoiceDoubleVisitor {
1863    type Value = Choice<f64>;
1864    type ArrayElem = Infallible;
1865
1866    fn visit_choice_f64(
1867        &self,
1868        choice: Choice<f64>,
1869    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1870        Ok(choice)
1871    }
1872}
1873
1874/// A visitor producing [`Choice`] for id choice values.
1875pub struct ChoiceIdVisitor;
1876
1877impl<'de> Visitor<'de> for ChoiceIdVisitor {
1878    type Value = Choice<Id>;
1879    type ArrayElem = Infallible;
1880
1881    fn visit_choice_id(
1882        &self,
1883        choice: Choice<Id>,
1884    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1885        Ok(choice)
1886    }
1887}
1888
1889/// A visitor producing [`Choice`] for rectangle choice values.
1890pub struct ChoiceRectangleVisitor;
1891
1892impl<'de> Visitor<'de> for ChoiceRectangleVisitor {
1893    type Value = Choice<Rectangle>;
1894    type ArrayElem = Infallible;
1895
1896    fn visit_choice_rectangle(
1897        &self,
1898        choice: Choice<Rectangle>,
1899    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1900        Ok(choice)
1901    }
1902}
1903/// A visitor producing [`Choice`] for fraction choice values.
1904pub struct ChoiceFractionVisitor;
1905
1906impl<'de> Visitor<'de> for ChoiceFractionVisitor {
1907    type Value = Choice<Fraction>;
1908    type ArrayElem = Infallible;
1909
1910    fn visit_choice_fraction(
1911        &self,
1912        choice: Choice<Fraction>,
1913    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1914        Ok(choice)
1915    }
1916}
1917
1918/// A visitor producing [`Choice`] for fd choice values.
1919pub struct ChoiceFdVisitor;
1920
1921impl<'de> Visitor<'de> for ChoiceFdVisitor {
1922    type Value = Choice<Fd>;
1923    type ArrayElem = Infallible;
1924
1925    fn visit_choice_fd(
1926        &self,
1927        choice: Choice<Fd>,
1928    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1929        Ok(choice)
1930    }
1931}
1932
1933/// A visitor producing pointers for fd pointer values.
1934pub struct PointerVisitor<T> {
1935    _phantom: PhantomData<T>,
1936}
1937
1938impl<T> Default for PointerVisitor<T> {
1939    fn default() -> Self {
1940        Self {
1941            _phantom: PhantomData,
1942        }
1943    }
1944}
1945
1946impl<'de, T> Visitor<'de> for PointerVisitor<T> {
1947    type Value = (u32, *const T);
1948    type ArrayElem = Infallible;
1949
1950    fn visit_pointer(
1951        &self,
1952        type_: u32,
1953        pointer: *const c_void,
1954    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1955        Ok((type_, pointer as *const T))
1956    }
1957}