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, _padding) =
805                    self.parse(|input| pair(u32(Endianness::Native), take(4usize)).parse(input))?;
806                visitor.visit_pointer(type_, ptr as *const c_void)?
807            }
808            _ => panic!("unsupported pointer size {ptr_size}"),
809        };
810
811        Ok((res, DeserializeSuccess(self)))
812    }
813
814    /// Deserialize any kind of pod using a visitor producing [`Value`].
815    pub fn deserialize_any(
816        self,
817    ) -> Result<(Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
818        let type_ = self.peek(Self::type_())?;
819
820        match type_ {
821            spa_sys::SPA_TYPE_None => self.deserialize_none(ValueVisitor),
822            spa_sys::SPA_TYPE_Bool => self.deserialize_bool(ValueVisitor),
823            spa_sys::SPA_TYPE_Id => self.deserialize_id(ValueVisitor),
824            spa_sys::SPA_TYPE_Int => self.deserialize_int(ValueVisitor),
825            spa_sys::SPA_TYPE_Long => self.deserialize_long(ValueVisitor),
826            spa_sys::SPA_TYPE_Float => self.deserialize_float(ValueVisitor),
827            spa_sys::SPA_TYPE_Double => self.deserialize_double(ValueVisitor),
828            spa_sys::SPA_TYPE_String => self.deserialize_str(ValueVisitor),
829            spa_sys::SPA_TYPE_Bytes => self.deserialize_bytes(ValueVisitor),
830            spa_sys::SPA_TYPE_Rectangle => self.deserialize_rectangle(ValueVisitor),
831            spa_sys::SPA_TYPE_Fraction => self.deserialize_fraction(ValueVisitor),
832            spa_sys::SPA_TYPE_Fd => self.deserialize_fd(ValueVisitor),
833            spa_sys::SPA_TYPE_Struct => self.deserialize_struct(ValueVisitor),
834            spa_sys::SPA_TYPE_Array => self.deserialize_array_any(),
835            spa_sys::SPA_TYPE_Object => self.deserialize_object(ValueVisitor),
836            spa_sys::SPA_TYPE_Choice => self.deserialize_choice(ValueVisitor),
837            spa_sys::SPA_TYPE_Pointer => self.deserialize_pointer(ValueVisitor),
838            _ => Err(DeserializeError::InvalidType),
839        }
840    }
841
842    fn deserialize_array_any(
843        self,
844    ) -> Result<(Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
845        let child_type =
846            self.peek(move |input| preceded(Self::type_(), Self::type_()).parse(input))?;
847
848        let (array, success) = match child_type {
849            spa_sys::SPA_TYPE_None => {
850                let (elements, success) = self.deserialize_array_vec::<()>()?;
851                let array = ValueArrayNoneVisitor.visit_array(elements)?;
852                (array, success)
853            }
854            spa_sys::SPA_TYPE_Bool => {
855                let (elements, success) = self.deserialize_array_vec::<bool>()?;
856                let array = ValueArrayBoolVisitor.visit_array(elements)?;
857                (array, success)
858            }
859            spa_sys::SPA_TYPE_Id => {
860                let (elements, success) = self.deserialize_array_vec::<Id>()?;
861                let array = ValueArrayIdVisitor.visit_array(elements)?;
862                (array, success)
863            }
864            spa_sys::SPA_TYPE_Int => {
865                let (elements, success) = self.deserialize_array_vec::<i32>()?;
866                let array = ValueArrayIntVisitor.visit_array(elements)?;
867                (array, success)
868            }
869            spa_sys::SPA_TYPE_Long => {
870                let (elements, success) = self.deserialize_array_vec::<i64>()?;
871                let array = ValueArrayLongVisitor.visit_array(elements)?;
872                (array, success)
873            }
874            spa_sys::SPA_TYPE_Float => {
875                let (elements, success) = self.deserialize_array_vec::<f32>()?;
876                let array = ValueArrayFloatVisitor.visit_array(elements)?;
877                (array, success)
878            }
879            spa_sys::SPA_TYPE_Double => {
880                let (elements, success) = self.deserialize_array_vec::<f64>()?;
881                let array = ValueArrayDoubleVisitor.visit_array(elements)?;
882                (array, success)
883            }
884            spa_sys::SPA_TYPE_Rectangle => {
885                let (elements, success) = self.deserialize_array_vec::<Rectangle>()?;
886                let array = ValueArrayRectangleVisitor.visit_array(elements)?;
887                (array, success)
888            }
889            spa_sys::SPA_TYPE_Fraction => {
890                let (elements, success) = self.deserialize_array_vec::<Fraction>()?;
891                let array = ValueArrayFractionVisitor.visit_array(elements)?;
892                (array, success)
893            }
894            spa_sys::SPA_TYPE_Fd => {
895                let (elements, success) = self.deserialize_array_vec::<Fd>()?;
896                let array = ValueArrayFdVisitor.visit_array(elements)?;
897                (array, success)
898            }
899            _ => return Err(DeserializeError::InvalidType),
900        };
901
902        Ok((Value::ValueArray(array), success))
903    }
904
905    /// Variant of [`Self::deserialize_from`] returning the parsed value as a [`Value`].
906    pub fn deserialize_any_from(
907        input: &'de [u8],
908    ) -> Result<(&'de [u8], Value), DeserializeError<&'de [u8]>> {
909        Self::deserialize_from(input)
910    }
911}
912
913/// This struct handles deserializing arrays.
914///
915/// It can be obtained by calling [`PodDeserializer::deserialize_array`].
916///
917/// The exact number of elements that was returned from that call must be deserialized
918/// using the [`deserialize_element`](`Self::deserialize_element`) function,
919/// followed by calling its [`end`](`Self::end`) function to finish deserialization of the array.
920pub struct ArrayPodDeserializer<'de, E: FixedSizedPod> {
921    deserializer: PodDeserializer<'de>,
922    // The total number of elements that must be deserialized from this array.
923    length: u32,
924    // The number of elements that have been deserialized so far.
925    deserialized: u32,
926    /// The struct has the type parameter E to ensure all deserialized elements are the same type,
927    /// but doesn't actually own any E, so we need the `PhantomData<E>` instead.
928    _phantom: PhantomData<E>,
929}
930
931impl<'de, E: FixedSizedPod> ArrayPodDeserializer<'de, E> {
932    /// Deserialize a single element.
933    ///
934    /// # Panics
935    /// Panics if there are no elements left to deserialize.
936    pub fn deserialize_element(&mut self) -> Result<E, DeserializeError<&'de [u8]>> {
937        if !self.deserialized < self.length {
938            panic!("No elements left in the pod to deserialize");
939        }
940
941        let result = self
942            .deserializer
943            .parse(E::CanonicalType::deserialize_body)
944            .map(|res| E::from_canonical_type(&res))
945            .map_err(|err| err.into());
946
947        self.deserialized += 1;
948        result
949    }
950
951    /// Finish deserializing the array.
952    ///
953    /// # Panics
954    /// Panics if not all elements of the array were deserialized.
955    pub fn end(mut self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
956        assert!(
957            self.length == self.deserialized,
958            "Not all fields were deserialized from the array pod"
959        );
960
961        // Deserialize remaining padding bytes.
962        let bytes_read = self.deserialized * E::CanonicalType::SIZE;
963        let padding = if bytes_read % 8 == 0 {
964            0
965        } else {
966            8 - (bytes_read as usize % 8)
967        };
968        self.deserializer.parse(take(padding))?;
969
970        Ok(DeserializeSuccess(self.deserializer))
971    }
972}
973
974/// This struct handles deserializing structs.
975///
976/// It can be obtained by calling [`PodDeserializer::deserialize_struct`].
977///
978/// Fields of the struct must be deserialized using its [`deserialize_field`](`Self::deserialize_field`)
979/// until it returns `None`.
980/// followed by calling its [`end`](`Self::end`) function to finish deserialization of the struct.
981pub struct StructPodDeserializer<'de> {
982    /// The deserializer is saved in an option, but can be expected to always be a `Some`
983    /// when `deserialize_field()` or `end()` is called.
984    ///
985    /// `deserialize_field()` `take()`s the deserializer, uses it to deserialize the field,
986    /// and then puts the deserializer back inside.
987    deserializer: Option<PodDeserializer<'de>>,
988    /// Remaining struct pod body length in bytes
989    remaining: u32,
990}
991
992impl<'de> StructPodDeserializer<'de> {
993    /// Deserialize a single field of the struct
994    ///
995    /// Returns `Some` when a field was successfully deserialized and `None` when all fields have been read.
996    pub fn deserialize_field<P: PodDeserialize<'de>>(
997        &mut self,
998    ) -> Result<Option<P>, DeserializeError<&'de [u8]>> {
999        if self.remaining == 0 {
1000            Ok(None)
1001        } else {
1002            let deserializer = self
1003                .deserializer
1004                .take()
1005                .expect("StructPodDeserializer does not contain a deserializer");
1006
1007            // The amount of input bytes remaining before deserializing the element.
1008            let remaining_input_len = deserializer.input.len();
1009
1010            let (res, success) = P::deserialize(deserializer)?;
1011
1012            // The amount of bytes deserialized is the length of the remaining input
1013            // minus the length of the remaining input now.
1014            self.remaining -= remaining_input_len as u32 - success.0.input.len() as u32;
1015
1016            self.deserializer = Some(success.0);
1017
1018            Ok(Some(res))
1019        }
1020    }
1021
1022    /// Finish deserialization of the pod.
1023    ///
1024    /// # Panics
1025    /// Panics if not all fields of the pod have been deserialized.
1026    pub fn end(self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
1027        assert!(
1028            self.remaining == 0,
1029            "Not all fields have been deserialized from the struct"
1030        );
1031
1032        // No padding parsing needed: Last field will already end aligned.
1033
1034        Ok(DeserializeSuccess(self.deserializer.expect(
1035            "StructPodDeserializer does not contain a deserializer",
1036        )))
1037    }
1038}
1039
1040/// This struct handles deserializing objects.
1041///
1042/// It can be obtained by calling [`PodDeserializer::deserialize_object`].
1043///
1044/// Properties of the object must be deserialized using its [`deserialize_property`](`Self::deserialize_property`)
1045/// until it returns `None`.
1046/// followed by calling its [`end`](`Self::end`) function to finish deserialization of the object.
1047pub struct ObjectPodDeserializer<'de> {
1048    /// The deserializer is saved in an option, but can be expected to always be a `Some`
1049    /// when `deserialize_property()` or `end()` is called.
1050    ///
1051    /// `deserialize_property()` `take()`s the deserializer, uses it to deserialize the property,
1052    /// and then puts the deserializer back inside.
1053    deserializer: Option<PodDeserializer<'de>>,
1054    /// Remaining object pod body length in bytes
1055    remaining: u32,
1056    /// type of the object
1057    object_type: u32,
1058    /// id of the object
1059    object_id: u32,
1060}
1061
1062impl<'de> ObjectPodDeserializer<'de> {
1063    /// Deserialize a single property of the object.
1064    ///
1065    /// Returns `Some` when a property was successfully deserialized and `None` when all properties have been read.
1066    #[allow(clippy::type_complexity)]
1067    pub fn deserialize_property<P: PodDeserialize<'de>>(
1068        &mut self,
1069    ) -> Result<Option<(P, u32, PropertyFlags)>, DeserializeError<&'de [u8]>> {
1070        if self.remaining == 0 {
1071            Ok(None)
1072        } else {
1073            let mut deserializer = self
1074                .deserializer
1075                .take()
1076                .expect("ObjectPodDeserializer does not contain a deserializer");
1077
1078            // The amount of input bytes remaining before deserializing the element.
1079            let remaining_input_len = deserializer.input.len();
1080
1081            let key = deserializer.parse(u32(Endianness::Native))?;
1082            let flags = deserializer.parse(u32(Endianness::Native))?;
1083
1084            let flags = PropertyFlags::from_bits_retain(flags);
1085            let (res, success) = P::deserialize(deserializer)?;
1086
1087            // The amount of bytes deserialized is the length of the remaining input
1088            // minus the length of the remaining input now.
1089            self.remaining -= remaining_input_len as u32 - success.0.input.len() as u32;
1090
1091            self.deserializer = Some(success.0);
1092
1093            Ok(Some((res, key, flags)))
1094        }
1095    }
1096
1097    /// Variant of [`Self::deserialize_property`] ensuring the property has a given key.
1098    ///
1099    /// Returns [`DeserializeError::PropertyMissing`] if the property is missing
1100    /// and [`DeserializeError::PropertyWrongKey`] if the property does not have the
1101    /// expected key.
1102    pub fn deserialize_property_key<P: PodDeserialize<'de>>(
1103        &mut self,
1104        key: u32,
1105    ) -> Result<(P, PropertyFlags), DeserializeError<&'de [u8]>> {
1106        let (prop, k, flags) = self
1107            .deserialize_property()?
1108            .ok_or(DeserializeError::PropertyMissing)?;
1109
1110        if k != key {
1111            Err(DeserializeError::PropertyWrongKey(k))
1112        } else {
1113            Ok((prop, flags))
1114        }
1115    }
1116
1117    /// Finish deserialization of the pod.
1118    ///
1119    /// # Panics
1120    /// Panics if not all properties of the pod have been deserialized.
1121    pub fn end(self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
1122        assert!(
1123            self.remaining == 0,
1124            "Not all properties have been deserialized from the object"
1125        );
1126
1127        // No padding parsing needed: Last field will already end aligned.
1128
1129        Ok(DeserializeSuccess(self.deserializer.expect(
1130            "ObjectPodDeserializer does not contain a deserializer",
1131        )))
1132    }
1133}
1134#[derive(Debug, PartialEq)]
1135/// Represent an error raised when deserializing a pod
1136pub enum DeserializeError<I> {
1137    /// Parsing error
1138    Nom(nom::Err<nom::error::Error<I>>),
1139    /// The visitor does not support the type
1140    UnsupportedType,
1141    /// The type is either invalid or not yet supported
1142    InvalidType,
1143    /// The property is missing from the object
1144    PropertyMissing,
1145    /// The property does not have the expected key
1146    PropertyWrongKey(u32),
1147    /// Invalid choice type
1148    InvalidChoiceType,
1149    /// Values are missing in the choice pod
1150    MissingChoiceValues,
1151}
1152
1153impl<I> From<nom::Err<nom::error::Error<I>>> for DeserializeError<I> {
1154    fn from(err: nom::Err<nom::error::Error<I>>) -> Self {
1155        DeserializeError::Nom(err)
1156    }
1157}
1158
1159/// This trait represents a visitor is "driven" by the deserializer to construct an instance of your type.
1160pub trait Visitor<'de>: Sized {
1161    /// The value produced by this visitor
1162    type Value;
1163    /// The element type [`Visitor::visit_array`] is expecting as input.
1164    /// Only used for visitors implementing this method,
1165    /// [`std::convert::Infallible`] can be used as a default.
1166    type ArrayElem;
1167
1168    /// The input contains a `none`.
1169    fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1170        Err(DeserializeError::UnsupportedType)
1171    }
1172
1173    /// The input contains a `bool`.
1174    fn visit_bool(&self, _v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1175        Err(DeserializeError::UnsupportedType)
1176    }
1177
1178    /// The input contains an `i32`.
1179    fn visit_int(&self, _v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1180        Err(DeserializeError::UnsupportedType)
1181    }
1182
1183    /// The input contains an `i64`.
1184    fn visit_long(&self, _v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1185        Err(DeserializeError::UnsupportedType)
1186    }
1187
1188    /// The input contains an `f32`.
1189    fn visit_float(&self, _v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1190        Err(DeserializeError::UnsupportedType)
1191    }
1192
1193    /// The input contains an `f64`.
1194    fn visit_double(&self, _v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1195        Err(DeserializeError::UnsupportedType)
1196    }
1197
1198    /// The input contains a string.
1199    fn visit_string(&self, _v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1200        Err(DeserializeError::UnsupportedType)
1201    }
1202
1203    /// The input contains a bytes array.
1204    fn visit_bytes(&self, _v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1205        Err(DeserializeError::UnsupportedType)
1206    }
1207
1208    /// The input contains a [`Rectangle`].
1209    fn visit_rectangle(&self, _v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1210        Err(DeserializeError::UnsupportedType)
1211    }
1212
1213    /// The input contains a [`Fraction`].
1214    fn visit_fraction(&self, _v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1215        Err(DeserializeError::UnsupportedType)
1216    }
1217
1218    /// The input contains an [`Id`].
1219    fn visit_id(&self, _v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1220        Err(DeserializeError::UnsupportedType)
1221    }
1222
1223    /// The input contains an [`Fd`].
1224    fn visit_fd(&self, _v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1225        Err(DeserializeError::UnsupportedType)
1226    }
1227
1228    /// The input contains a structure.
1229    fn visit_struct(
1230        &self,
1231        _struct_deserializer: &mut StructPodDeserializer<'de>,
1232    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1233        Err(DeserializeError::UnsupportedType)
1234    }
1235
1236    /// The input contains an array.
1237    fn visit_array(
1238        &self,
1239        _elements: Vec<Self::ArrayElem>,
1240    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1241        Err(DeserializeError::UnsupportedType)
1242    }
1243
1244    /// The input contains an object.
1245    fn visit_object(
1246        &self,
1247        _object_deserializer: &mut ObjectPodDeserializer<'de>,
1248    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1249        Err(DeserializeError::UnsupportedType)
1250    }
1251
1252    /// The input contains an [`i32`] choice.
1253    fn visit_choice_bool(
1254        &self,
1255        _choice: Choice<bool>,
1256    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1257        Err(DeserializeError::UnsupportedType)
1258    }
1259
1260    /// The input contains an [`i32`] choice.
1261    fn visit_choice_i32(
1262        &self,
1263        _choice: Choice<i32>,
1264    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1265        Err(DeserializeError::UnsupportedType)
1266    }
1267
1268    /// The input contains an [`i64`] choice.
1269    fn visit_choice_i64(
1270        &self,
1271        _choice: Choice<i64>,
1272    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1273        Err(DeserializeError::UnsupportedType)
1274    }
1275
1276    /// The input contains a [`f32`] choice.
1277    fn visit_choice_f32(
1278        &self,
1279        _choice: Choice<f32>,
1280    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1281        Err(DeserializeError::UnsupportedType)
1282    }
1283
1284    /// The input contains a [`f64`] choice.
1285    fn visit_choice_f64(
1286        &self,
1287        _choice: Choice<f64>,
1288    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1289        Err(DeserializeError::UnsupportedType)
1290    }
1291
1292    /// The input contains a [`Id`] choice.
1293    fn visit_choice_id(
1294        &self,
1295        _choice: Choice<Id>,
1296    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1297        Err(DeserializeError::UnsupportedType)
1298    }
1299
1300    /// The input contains a [`Rectangle`] choice.
1301    fn visit_choice_rectangle(
1302        &self,
1303        _choice: Choice<Rectangle>,
1304    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1305        Err(DeserializeError::UnsupportedType)
1306    }
1307
1308    /// The input contains a [`Fraction`] choice.
1309    fn visit_choice_fraction(
1310        &self,
1311        _choice: Choice<Fraction>,
1312    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1313        Err(DeserializeError::UnsupportedType)
1314    }
1315
1316    /// The input contains a [`Fd`] choice.
1317    fn visit_choice_fd(
1318        &self,
1319        _choice: Choice<Fd>,
1320    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1321        Err(DeserializeError::UnsupportedType)
1322    }
1323
1324    /// The input contains a pointer.
1325    fn visit_pointer(
1326        &self,
1327        _type: u32,
1328        _pointer: *const c_void,
1329    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1330        Err(DeserializeError::UnsupportedType)
1331    }
1332}
1333
1334/// A visitor producing `()` for none values.
1335pub struct NoneVisitor;
1336
1337impl<'de> Visitor<'de> for NoneVisitor {
1338    type Value = ();
1339    type ArrayElem = Infallible;
1340
1341    fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1342        Ok(())
1343    }
1344}
1345
1346/// A visitor producing [`bool`] for boolean values.
1347pub struct BoolVisitor;
1348
1349impl<'de> Visitor<'de> for BoolVisitor {
1350    type Value = bool;
1351    type ArrayElem = Infallible;
1352
1353    fn visit_bool(&self, v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1354        Ok(v)
1355    }
1356}
1357
1358/// A visitor producing [`i32`] for integer values.
1359pub struct IntVisitor;
1360
1361impl<'de> Visitor<'de> for IntVisitor {
1362    type Value = i32;
1363    type ArrayElem = Infallible;
1364
1365    fn visit_int(&self, v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1366        Ok(v)
1367    }
1368}
1369
1370/// A visitor producing [`i64`] for long values.
1371pub struct LongVisitor;
1372
1373impl<'de> Visitor<'de> for LongVisitor {
1374    type Value = i64;
1375    type ArrayElem = Infallible;
1376
1377    fn visit_long(&self, v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1378        Ok(v)
1379    }
1380}
1381
1382/// A visitor producing [`f32`] for float values.
1383pub struct FloatVisitor;
1384
1385impl<'de> Visitor<'de> for FloatVisitor {
1386    type Value = f32;
1387    type ArrayElem = Infallible;
1388
1389    fn visit_float(&self, v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1390        Ok(v)
1391    }
1392}
1393
1394/// A visitor producing [`f64`] for double values.
1395pub struct DoubleVisitor;
1396
1397impl<'de> Visitor<'de> for DoubleVisitor {
1398    type Value = f64;
1399    type ArrayElem = Infallible;
1400
1401    fn visit_double(&self, v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1402        Ok(v)
1403    }
1404}
1405
1406/// A visitor producing [`&str`] for string values.
1407pub struct StringVisitor;
1408
1409impl<'de> Visitor<'de> for StringVisitor {
1410    type Value = &'de str;
1411    type ArrayElem = Infallible;
1412
1413    fn visit_string(&self, v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1414        Ok(v)
1415    }
1416}
1417
1418/// A visitor producing [`&[u8]`] for bytes values.
1419pub struct BytesVisitor;
1420
1421impl<'de> Visitor<'de> for BytesVisitor {
1422    type Value = &'de [u8];
1423    type ArrayElem = Infallible;
1424
1425    fn visit_bytes(&self, v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1426        Ok(v)
1427    }
1428}
1429
1430/// A visitor producing [`Rectangle`] for rectangle values.
1431pub struct RectangleVisitor;
1432
1433impl<'de> Visitor<'de> for RectangleVisitor {
1434    type Value = Rectangle;
1435    type ArrayElem = Infallible;
1436
1437    fn visit_rectangle(&self, v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1438        Ok(v)
1439    }
1440}
1441
1442/// A visitor producing [`Fraction`] for fraction values.
1443pub struct FractionVisitor;
1444
1445impl<'de> Visitor<'de> for FractionVisitor {
1446    type Value = Fraction;
1447    type ArrayElem = Infallible;
1448
1449    fn visit_fraction(&self, v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1450        Ok(v)
1451    }
1452}
1453
1454/// A visitor producing [`Id`] for ID values.
1455pub struct IdVisitor;
1456
1457impl<'de> Visitor<'de> for IdVisitor {
1458    type Value = Id;
1459    type ArrayElem = Infallible;
1460
1461    fn visit_id(&self, v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1462        Ok(v)
1463    }
1464}
1465
1466/// A visitor producing [`Fd`] for file descriptor values.
1467pub struct FdVisitor;
1468
1469impl<'de> Visitor<'de> for FdVisitor {
1470    type Value = Fd;
1471    type ArrayElem = Infallible;
1472
1473    fn visit_fd(&self, v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1474        Ok(v)
1475    }
1476}
1477
1478/// A visitor producing [`Vec`] for array values.
1479pub struct VecVisitor<E: FixedSizedPod> {
1480    _phantom: PhantomData<E>,
1481}
1482
1483impl<E: FixedSizedPod> Default for VecVisitor<E> {
1484    fn default() -> Self {
1485        Self {
1486            _phantom: PhantomData,
1487        }
1488    }
1489}
1490
1491impl<'de, E: CanonicalFixedSizedPod + std::marker::Copy> Visitor<'de> for VecVisitor<E> {
1492    type Value = Vec<E>;
1493    type ArrayElem = E;
1494
1495    fn visit_array(&self, elements: Vec<E>) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1496        Ok(elements)
1497    }
1498}
1499
1500/// A visitor producing [`Value`] for all type of values.
1501pub struct ValueVisitor;
1502
1503impl<'de> Visitor<'de> for ValueVisitor {
1504    type Value = Value;
1505    type ArrayElem = std::convert::Infallible;
1506
1507    fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1508        Ok(Value::None)
1509    }
1510
1511    fn visit_bool(&self, v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1512        Ok(Value::Bool(v))
1513    }
1514
1515    fn visit_int(&self, v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1516        Ok(Value::Int(v))
1517    }
1518
1519    fn visit_long(&self, v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1520        Ok(Value::Long(v))
1521    }
1522
1523    fn visit_float(&self, v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1524        Ok(Value::Float(v))
1525    }
1526
1527    fn visit_double(&self, v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1528        Ok(Value::Double(v))
1529    }
1530
1531    fn visit_string(&self, v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1532        Ok(Value::String(v.to_string()))
1533    }
1534
1535    fn visit_bytes(&self, v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1536        Ok(Value::Bytes(v.to_vec()))
1537    }
1538
1539    fn visit_rectangle(&self, v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1540        Ok(Value::Rectangle(v))
1541    }
1542
1543    fn visit_fraction(&self, v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1544        Ok(Value::Fraction(v))
1545    }
1546
1547    fn visit_id(&self, v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1548        Ok(Value::Id(v))
1549    }
1550
1551    fn visit_fd(&self, v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1552        Ok(Value::Fd(v))
1553    }
1554
1555    fn visit_struct(
1556        &self,
1557        struct_deserializer: &mut StructPodDeserializer<'de>,
1558    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1559        let mut res = Vec::new();
1560
1561        while let Some(value) = struct_deserializer.deserialize_field()? {
1562            res.push(value);
1563        }
1564
1565        Ok(Value::Struct(res))
1566    }
1567
1568    fn visit_object(
1569        &self,
1570        object_deserializer: &mut ObjectPodDeserializer<'de>,
1571    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1572        let mut properties = Vec::new();
1573
1574        while let Some((value, key, flags)) = object_deserializer.deserialize_property()? {
1575            let prop = Property { key, flags, value };
1576            properties.push(prop);
1577        }
1578
1579        let object = Object {
1580            type_: object_deserializer.object_type,
1581            id: object_deserializer.object_id,
1582            properties,
1583        };
1584
1585        Ok(Value::Object(object))
1586    }
1587
1588    fn visit_choice_bool(
1589        &self,
1590        choice: Choice<bool>,
1591    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1592        Ok(Value::Choice(ChoiceValue::Bool(choice)))
1593    }
1594
1595    fn visit_choice_i32(
1596        &self,
1597        choice: Choice<i32>,
1598    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1599        Ok(Value::Choice(ChoiceValue::Int(choice)))
1600    }
1601
1602    fn visit_choice_i64(
1603        &self,
1604        choice: Choice<i64>,
1605    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1606        Ok(Value::Choice(ChoiceValue::Long(choice)))
1607    }
1608
1609    fn visit_choice_f32(
1610        &self,
1611        choice: Choice<f32>,
1612    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1613        Ok(Value::Choice(ChoiceValue::Float(choice)))
1614    }
1615
1616    fn visit_choice_f64(
1617        &self,
1618        choice: Choice<f64>,
1619    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1620        Ok(Value::Choice(ChoiceValue::Double(choice)))
1621    }
1622
1623    fn visit_choice_id(
1624        &self,
1625        choice: Choice<Id>,
1626    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1627        Ok(Value::Choice(ChoiceValue::Id(choice)))
1628    }
1629
1630    fn visit_choice_rectangle(
1631        &self,
1632        choice: Choice<Rectangle>,
1633    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1634        Ok(Value::Choice(ChoiceValue::Rectangle(choice)))
1635    }
1636
1637    fn visit_choice_fraction(
1638        &self,
1639        choice: Choice<Fraction>,
1640    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1641        Ok(Value::Choice(ChoiceValue::Fraction(choice)))
1642    }
1643
1644    fn visit_choice_fd(
1645        &self,
1646        choice: Choice<Fd>,
1647    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1648        Ok(Value::Choice(ChoiceValue::Fd(choice)))
1649    }
1650
1651    fn visit_pointer(
1652        &self,
1653        type_: u32,
1654        pointer: *const c_void,
1655    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1656        Ok(Value::Pointer(type_, pointer))
1657    }
1658}
1659
1660struct ValueArrayNoneVisitor;
1661
1662impl<'de> Visitor<'de> for ValueArrayNoneVisitor {
1663    type Value = ValueArray;
1664    type ArrayElem = ();
1665
1666    fn visit_array(
1667        &self,
1668        elements: Vec<Self::ArrayElem>,
1669    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1670        Ok(ValueArray::None(elements))
1671    }
1672}
1673
1674struct ValueArrayBoolVisitor;
1675
1676impl<'de> Visitor<'de> for ValueArrayBoolVisitor {
1677    type Value = ValueArray;
1678    type ArrayElem = bool;
1679
1680    fn visit_array(
1681        &self,
1682        elements: Vec<Self::ArrayElem>,
1683    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1684        Ok(ValueArray::Bool(elements))
1685    }
1686}
1687
1688struct ValueArrayIdVisitor;
1689
1690impl<'de> Visitor<'de> for ValueArrayIdVisitor {
1691    type Value = ValueArray;
1692    type ArrayElem = Id;
1693
1694    fn visit_array(
1695        &self,
1696        elements: Vec<Self::ArrayElem>,
1697    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1698        Ok(ValueArray::Id(elements))
1699    }
1700}
1701
1702struct ValueArrayIntVisitor;
1703
1704impl<'de> Visitor<'de> for ValueArrayIntVisitor {
1705    type Value = ValueArray;
1706    type ArrayElem = i32;
1707
1708    fn visit_array(
1709        &self,
1710        elements: Vec<Self::ArrayElem>,
1711    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1712        Ok(ValueArray::Int(elements))
1713    }
1714}
1715
1716struct ValueArrayLongVisitor;
1717
1718impl<'de> Visitor<'de> for ValueArrayLongVisitor {
1719    type Value = ValueArray;
1720    type ArrayElem = i64;
1721
1722    fn visit_array(
1723        &self,
1724        elements: Vec<Self::ArrayElem>,
1725    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1726        Ok(ValueArray::Long(elements))
1727    }
1728}
1729
1730struct ValueArrayFloatVisitor;
1731
1732impl<'de> Visitor<'de> for ValueArrayFloatVisitor {
1733    type Value = ValueArray;
1734    type ArrayElem = f32;
1735
1736    fn visit_array(
1737        &self,
1738        elements: Vec<Self::ArrayElem>,
1739    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1740        Ok(ValueArray::Float(elements))
1741    }
1742}
1743
1744struct ValueArrayDoubleVisitor;
1745
1746impl<'de> Visitor<'de> for ValueArrayDoubleVisitor {
1747    type Value = ValueArray;
1748    type ArrayElem = f64;
1749
1750    fn visit_array(
1751        &self,
1752        elements: Vec<Self::ArrayElem>,
1753    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1754        Ok(ValueArray::Double(elements))
1755    }
1756}
1757
1758struct ValueArrayRectangleVisitor;
1759
1760impl<'de> Visitor<'de> for ValueArrayRectangleVisitor {
1761    type Value = ValueArray;
1762    type ArrayElem = Rectangle;
1763
1764    fn visit_array(
1765        &self,
1766        elements: Vec<Self::ArrayElem>,
1767    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1768        Ok(ValueArray::Rectangle(elements))
1769    }
1770}
1771
1772struct ValueArrayFractionVisitor;
1773
1774impl<'de> Visitor<'de> for ValueArrayFractionVisitor {
1775    type Value = ValueArray;
1776    type ArrayElem = Fraction;
1777
1778    fn visit_array(
1779        &self,
1780        elements: Vec<Self::ArrayElem>,
1781    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1782        Ok(ValueArray::Fraction(elements))
1783    }
1784}
1785
1786struct ValueArrayFdVisitor;
1787
1788impl<'de> Visitor<'de> for ValueArrayFdVisitor {
1789    type Value = ValueArray;
1790    type ArrayElem = Fd;
1791
1792    fn visit_array(
1793        &self,
1794        elements: Vec<Self::ArrayElem>,
1795    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1796        Ok(ValueArray::Fd(elements))
1797    }
1798}
1799
1800/// A visitor producing [`Choice`] for boolean choice values.
1801pub struct ChoiceBoolVisitor;
1802
1803impl<'de> Visitor<'de> for ChoiceBoolVisitor {
1804    type Value = Choice<bool>;
1805    type ArrayElem = Infallible;
1806
1807    fn visit_choice_bool(
1808        &self,
1809        choice: Choice<bool>,
1810    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1811        Ok(choice)
1812    }
1813}
1814
1815/// A visitor producing [`Choice`] for integer choice values.
1816pub struct ChoiceIntVisitor;
1817
1818impl<'de> Visitor<'de> for ChoiceIntVisitor {
1819    type Value = Choice<i32>;
1820    type ArrayElem = Infallible;
1821
1822    fn visit_choice_i32(
1823        &self,
1824        choice: Choice<i32>,
1825    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1826        Ok(choice)
1827    }
1828}
1829
1830/// A visitor producing [`Choice`] for long integer choice values.
1831pub struct ChoiceLongVisitor;
1832
1833impl<'de> Visitor<'de> for ChoiceLongVisitor {
1834    type Value = Choice<i64>;
1835    type ArrayElem = Infallible;
1836
1837    fn visit_choice_i64(
1838        &self,
1839        choice: Choice<i64>,
1840    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1841        Ok(choice)
1842    }
1843}
1844
1845/// A visitor producing [`Choice`] for floating choice values.
1846pub struct ChoiceFloatVisitor;
1847
1848impl<'de> Visitor<'de> for ChoiceFloatVisitor {
1849    type Value = Choice<f32>;
1850    type ArrayElem = Infallible;
1851
1852    fn visit_choice_f32(
1853        &self,
1854        choice: Choice<f32>,
1855    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1856        Ok(choice)
1857    }
1858}
1859
1860/// A visitor producing [`Choice`] for double floating choice values.
1861pub struct ChoiceDoubleVisitor;
1862
1863impl<'de> Visitor<'de> for ChoiceDoubleVisitor {
1864    type Value = Choice<f64>;
1865    type ArrayElem = Infallible;
1866
1867    fn visit_choice_f64(
1868        &self,
1869        choice: Choice<f64>,
1870    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1871        Ok(choice)
1872    }
1873}
1874
1875/// A visitor producing [`Choice`] for id choice values.
1876pub struct ChoiceIdVisitor;
1877
1878impl<'de> Visitor<'de> for ChoiceIdVisitor {
1879    type Value = Choice<Id>;
1880    type ArrayElem = Infallible;
1881
1882    fn visit_choice_id(
1883        &self,
1884        choice: Choice<Id>,
1885    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1886        Ok(choice)
1887    }
1888}
1889
1890/// A visitor producing [`Choice`] for rectangle choice values.
1891pub struct ChoiceRectangleVisitor;
1892
1893impl<'de> Visitor<'de> for ChoiceRectangleVisitor {
1894    type Value = Choice<Rectangle>;
1895    type ArrayElem = Infallible;
1896
1897    fn visit_choice_rectangle(
1898        &self,
1899        choice: Choice<Rectangle>,
1900    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1901        Ok(choice)
1902    }
1903}
1904/// A visitor producing [`Choice`] for fraction choice values.
1905pub struct ChoiceFractionVisitor;
1906
1907impl<'de> Visitor<'de> for ChoiceFractionVisitor {
1908    type Value = Choice<Fraction>;
1909    type ArrayElem = Infallible;
1910
1911    fn visit_choice_fraction(
1912        &self,
1913        choice: Choice<Fraction>,
1914    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1915        Ok(choice)
1916    }
1917}
1918
1919/// A visitor producing [`Choice`] for fd choice values.
1920pub struct ChoiceFdVisitor;
1921
1922impl<'de> Visitor<'de> for ChoiceFdVisitor {
1923    type Value = Choice<Fd>;
1924    type ArrayElem = Infallible;
1925
1926    fn visit_choice_fd(
1927        &self,
1928        choice: Choice<Fd>,
1929    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1930        Ok(choice)
1931    }
1932}
1933
1934/// A visitor producing pointers for fd pointer values.
1935pub struct PointerVisitor<T> {
1936    _phantom: PhantomData<T>,
1937}
1938
1939impl<T> Default for PointerVisitor<T> {
1940    fn default() -> Self {
1941        Self {
1942            _phantom: PhantomData,
1943        }
1944    }
1945}
1946
1947impl<'de, T> Visitor<'de> for PointerVisitor<T> {
1948    type Value = (u32, *const T);
1949    type ArrayElem = Infallible;
1950
1951    fn visit_pointer(
1952        &self,
1953        type_: u32,
1954        pointer: *const c_void,
1955    ) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
1956        Ok((type_, pointer as *const T))
1957    }
1958}