use std::{convert::Infallible, ffi::c_void, marker::PhantomData, ptr};
use nom::{
bytes::complete::{tag, take},
combinator::{map, map_res, verify},
number::{complete::u32, complete::u64, Endianness},
sequence::{delimited, pair, preceded, terminated},
IResult,
};
use super::{
CanonicalFixedSizedPod, ChoiceValue, FixedSizedPod, Object, PropertyFlags, Value, ValueArray,
};
use crate::{
pod::Property,
utils::{Choice, ChoiceEnum, ChoiceFlags, Fd, Fraction, Id, Rectangle},
};
pub trait PodDeserialize<'de> {
fn deserialize(
deserializer: PodDeserializer<'de>,
) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
Self: Sized;
}
impl<'de> PodDeserialize<'de> for &'de str {
fn deserialize(
deserializer: PodDeserializer<'de>,
) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
Self: Sized,
{
deserializer.deserialize_str(StringVisitor)
}
}
impl<'de> PodDeserialize<'de> for String {
fn deserialize(
deserializer: PodDeserializer<'de>,
) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
Self: Sized,
{
deserializer
.deserialize_str(StringVisitor)
.map(|(s, success)| (s.to_owned(), success))
}
}
impl<'de> PodDeserialize<'de> for &'de [u8] {
fn deserialize(
deserializer: PodDeserializer<'de>,
) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
Self: Sized,
{
deserializer.deserialize_bytes(BytesVisitor)
}
}
impl<'de> PodDeserialize<'de> for Vec<u8> {
fn deserialize(
deserializer: PodDeserializer<'de>,
) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
Self: Sized,
{
deserializer
.deserialize_bytes(BytesVisitor)
.map(|(b, success)| (b.to_owned(), success))
}
}
impl<'de, P: FixedSizedPod + CanonicalFixedSizedPod + std::marker::Copy> PodDeserialize<'de>
for Vec<P>
{
fn deserialize(
deserializer: PodDeserializer<'de>,
) -> Result<(Self, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
Self: Sized,
{
deserializer.deserialize_array::<_, P>(VecVisitor::<P>::default())
}
}
pub struct DeserializeSuccess<'de>(PodDeserializer<'de>);
pub struct PodDeserializer<'de> {
input: &'de [u8],
}
impl<'de> PodDeserializer<'de> {
pub fn deserialize_from<P: PodDeserialize<'de>>(
input: &'de [u8],
) -> Result<(&'de [u8], P), DeserializeError<&'de [u8]>> {
let deserializer = Self { input };
P::deserialize(deserializer).map(|(res, success)| (success.0.input, res))
}
pub unsafe fn deserialize_ptr<P: PodDeserialize<'de>>(
ptr: ptr::NonNull<spa_sys::spa_pod>,
) -> Result<P, DeserializeError<&'de [u8]>> {
let len = ptr.as_ref().size;
let pod = ptr.as_ptr() as *const _ as *const u8;
let slice = std::slice::from_raw_parts(pod, len as usize + 8);
let res = PodDeserializer::deserialize_from(slice)?;
Ok(res.1)
}
fn parse<T, F>(&mut self, mut f: F) -> Result<T, nom::Err<nom::error::Error<&'de [u8]>>>
where
F: FnMut(&'de [u8]) -> IResult<&'de [u8], T>,
{
f(self.input).map(|(input, result)| {
self.input = input;
result
})
}
fn peek<T, F>(&self, mut f: F) -> Result<T, nom::Err<nom::error::Error<&'de [u8]>>>
where
F: FnMut(&'de [u8]) -> IResult<&'de [u8], T>,
{
f(self.input).map(|(_input, result)| result)
}
fn calc_padding_needed(size: u32) -> u32 {
(8 - (size % 8)) % 8
}
pub(super) fn header<'b>(type_: u32) -> impl FnMut(&'b [u8]) -> IResult<&'b [u8], u32> {
terminated(u32(Endianness::Native), tag(type_.to_ne_bytes()))
}
pub(super) fn type_<'b>() -> impl FnMut(&'b [u8]) -> IResult<&'b [u8], u32> {
preceded(u32(Endianness::Native), u32(Endianness::Native))
}
fn deserialize_fixed_sized_pod<P: FixedSizedPod>(
mut self,
) -> Result<(P, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
let padding = Self::calc_padding_needed(P::CanonicalType::SIZE);
self.parse(delimited(
Self::header(P::CanonicalType::TYPE),
map(P::CanonicalType::deserialize_body, |res| {
P::from_canonical_type(&res)
}),
take(padding),
))
.map(|res| (res, DeserializeSuccess(self)))
.map_err(|err| err.into())
}
pub fn deserialize_none<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod::<()>().unwrap();
Ok((visitor.visit_none()?, res.1))
}
pub fn deserialize_bool<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_bool(res.0)?, res.1))
}
pub fn deserialize_int<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_int(res.0)?, res.1))
}
pub fn deserialize_long<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_long(res.0)?, res.1))
}
pub fn deserialize_float<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_float(res.0)?, res.1))
}
pub fn deserialize_double<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_double(res.0)?, res.1))
}
pub fn deserialize_str<V>(
mut self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let len = self.parse(Self::header(spa_sys::SPA_TYPE_String))?;
let padding = Self::calc_padding_needed(len);
let res = self.parse(terminated(
map_res(terminated(take(len - 1), tag([b'\0'])), std::str::from_utf8),
take(padding),
))?;
Ok((visitor.visit_string(res)?, DeserializeSuccess(self)))
}
pub fn deserialize_bytes<V>(
mut self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let len = self.parse(Self::header(spa_sys::SPA_TYPE_Bytes))?;
let padding = Self::calc_padding_needed(len);
let res = self.parse(terminated(take(len), take(padding)))?;
Ok((visitor.visit_bytes(res)?, DeserializeSuccess(self)))
}
pub fn new_array_deserializer<E>(
mut self,
) -> Result<(ArrayPodDeserializer<'de, E>, u32), DeserializeError<&'de [u8]>>
where
E: FixedSizedPod,
{
let len = self.parse(Self::header(spa_sys::SPA_TYPE_Array))?;
self.parse(verify(Self::header(E::CanonicalType::TYPE), |len| {
*len == E::CanonicalType::SIZE
}))?;
let num_elems = if E::CanonicalType::SIZE != 0 {
(len - 8) / E::CanonicalType::SIZE
} else {
0
};
Ok((
ArrayPodDeserializer {
deserializer: self,
length: num_elems,
deserialized: 0,
_phantom: PhantomData,
},
num_elems,
))
}
fn new_struct_deserializer(
mut self,
) -> Result<StructPodDeserializer<'de>, DeserializeError<&'de [u8]>> {
let len = self.parse(Self::header(spa_sys::SPA_TYPE_Struct))?;
Ok(StructPodDeserializer {
deserializer: Some(self),
remaining: len,
})
}
fn new_object_deserializer(
mut self,
) -> Result<ObjectPodDeserializer<'de>, DeserializeError<&'de [u8]>> {
let len = self.parse(Self::header(spa_sys::SPA_TYPE_Object))?;
let (object_type, object_id) =
self.parse(pair(u32(Endianness::Native), u32(Endianness::Native)))?;
Ok(ObjectPodDeserializer {
deserializer: Some(self),
remaining: len - 8,
object_type,
object_id,
})
}
pub fn deserialize_rectangle<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_rectangle(res.0)?, res.1))
}
pub fn deserialize_fraction<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_fraction(res.0)?, res.1))
}
pub fn deserialize_id<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_id(res.0)?, res.1))
}
pub fn deserialize_fd<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let res = self.deserialize_fixed_sized_pod()?;
Ok((visitor.visit_fd(res.0)?, res.1))
}
pub fn deserialize_struct<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let mut struct_deserializer = self.new_struct_deserializer()?;
let res = visitor.visit_struct(&mut struct_deserializer)?;
let success = struct_deserializer.end()?;
Ok((res, success))
}
fn deserialize_array_vec<T>(
self,
) -> Result<(Vec<T>, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
T: CanonicalFixedSizedPod + FixedSizedPod + std::marker::Copy,
{
let mut array_deserializer: ArrayPodDeserializer<'de, T> = self.new_array_deserializer()?.0;
let mut elements = Vec::with_capacity(array_deserializer.length as usize);
for _ in 0..array_deserializer.length {
elements.push(array_deserializer.deserialize_element()?);
}
let success = array_deserializer.end()?;
Ok((elements, success))
}
pub fn deserialize_array<V, T>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de, ArrayElem = T>,
T: CanonicalFixedSizedPod + FixedSizedPod + std::marker::Copy,
{
let (elements, success) = self.deserialize_array_vec::<T>()?;
let res = visitor.visit_array(elements)?;
Ok((res, success))
}
pub fn deserialize_object<V>(
self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let mut obj_deserializer = self.new_object_deserializer()?;
let res = visitor.visit_object(&mut obj_deserializer)?;
let success = obj_deserializer.end()?;
Ok((res, success))
}
fn deserialize_choice_values<E>(
self,
num_values: u32,
) -> Result<(Vec<E>, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
E: CanonicalFixedSizedPod + FixedSizedPod,
{
let mut array_deserializer = ArrayPodDeserializer {
deserializer: self,
length: num_values,
deserialized: 0,
_phantom: PhantomData,
};
let mut elements = Vec::new();
for _ in 0..num_values {
elements.push(array_deserializer.deserialize_element()?);
}
let success = array_deserializer.end()?;
Ok((elements, success))
}
pub fn deserialize_choice<V>(
mut self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let len = self.parse(Self::header(spa_sys::SPA_TYPE_Choice))?;
let (choice_type, flags) =
self.parse(pair(u32(Endianness::Native), u32(Endianness::Native)))?;
let (child_size, child_type) =
self.parse(pair(u32(Endianness::Native), u32(Endianness::Native)))?;
let num_values = (len - 16) / child_size;
fn create_choice<'de, E>(
choice_type: u32,
values: Vec<E>,
flags: u32,
) -> Result<Choice<E>, DeserializeError<&'de [u8]>>
where
E: CanonicalFixedSizedPod + FixedSizedPod + Copy,
{
let flags = ChoiceFlags::from_bits_retain(flags);
match choice_type {
spa_sys::SPA_CHOICE_None => {
if values.is_empty() {
Err(DeserializeError::MissingChoiceValues)
} else {
Ok(Choice(ChoiceFlags::empty(), ChoiceEnum::None(values[0])))
}
}
spa_sys::SPA_CHOICE_Range => {
if values.len() < 3 {
Err(DeserializeError::MissingChoiceValues)
} else {
Ok(Choice(
flags,
ChoiceEnum::Range {
default: values[0],
min: values[1],
max: values[2],
},
))
}
}
spa_sys::SPA_CHOICE_Step => {
if values.len() < 4 {
Err(DeserializeError::MissingChoiceValues)
} else {
Ok(Choice(
flags,
ChoiceEnum::Step {
default: values[0],
min: values[1],
max: values[2],
step: values[3],
},
))
}
}
spa_sys::SPA_CHOICE_Enum => {
if values.is_empty() {
Err(DeserializeError::MissingChoiceValues)
} else {
Ok(Choice(
flags,
ChoiceEnum::Enum {
default: values[0],
alternatives: values[1..].to_vec(),
},
))
}
}
spa_sys::SPA_CHOICE_Flags => {
if values.is_empty() {
Err(DeserializeError::MissingChoiceValues)
} else {
Ok(Choice(
flags,
ChoiceEnum::Flags {
default: values[0],
flags: values[1..].to_vec(),
},
))
}
}
_ => Err(DeserializeError::InvalidChoiceType),
}
}
match child_type {
spa_sys::SPA_TYPE_Bool => {
let (values, success) = self.deserialize_choice_values::<bool>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_bool(choice)?, success))
}
spa_sys::SPA_TYPE_Int => {
let (values, success) = self.deserialize_choice_values::<i32>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_i32(choice)?, success))
}
spa_sys::SPA_TYPE_Long => {
let (values, success) = self.deserialize_choice_values::<i64>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_i64(choice)?, success))
}
spa_sys::SPA_TYPE_Float => {
let (values, success) = self.deserialize_choice_values::<f32>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_f32(choice)?, success))
}
spa_sys::SPA_TYPE_Double => {
let (values, success) = self.deserialize_choice_values::<f64>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_f64(choice)?, success))
}
spa_sys::SPA_TYPE_Id => {
let (values, success) = self.deserialize_choice_values::<Id>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_id(choice)?, success))
}
spa_sys::SPA_TYPE_Rectangle => {
let (values, success) = self.deserialize_choice_values::<Rectangle>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_rectangle(choice)?, success))
}
spa_sys::SPA_TYPE_Fraction => {
let (values, success) = self.deserialize_choice_values::<Fraction>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_fraction(choice)?, success))
}
spa_sys::SPA_TYPE_Fd => {
let (values, success) = self.deserialize_choice_values::<Fd>(num_values)?;
let choice = create_choice(choice_type, values, flags)?;
Ok((visitor.visit_choice_fd(choice)?, success))
}
_ => Err(DeserializeError::InvalidType),
}
}
pub fn deserialize_pointer<V>(
mut self,
visitor: V,
) -> Result<(V::Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>>
where
V: Visitor<'de>,
{
let len = self.parse(Self::header(spa_sys::SPA_TYPE_Pointer))?;
let (type_, _padding) =
self.parse(pair(u32(Endianness::Native), u32(Endianness::Native)))?;
let ptr_size = len - 8;
let res = match ptr_size {
8 => {
let ptr = self.parse(u64(Endianness::Native))?;
visitor.visit_pointer(type_, ptr as *const c_void)?
}
4 => {
let ptr = self.parse(u32(Endianness::Native))?;
visitor.visit_pointer(type_, ptr as *const c_void)?
}
_ => panic!("unsupported pointer size {}", ptr_size),
};
Ok((res, DeserializeSuccess(self)))
}
pub fn deserialize_any(
self,
) -> Result<(Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
let type_ = self.peek(Self::type_())?;
match type_ {
spa_sys::SPA_TYPE_None => self.deserialize_none(ValueVisitor),
spa_sys::SPA_TYPE_Bool => self.deserialize_bool(ValueVisitor),
spa_sys::SPA_TYPE_Id => self.deserialize_id(ValueVisitor),
spa_sys::SPA_TYPE_Int => self.deserialize_int(ValueVisitor),
spa_sys::SPA_TYPE_Long => self.deserialize_long(ValueVisitor),
spa_sys::SPA_TYPE_Float => self.deserialize_float(ValueVisitor),
spa_sys::SPA_TYPE_Double => self.deserialize_double(ValueVisitor),
spa_sys::SPA_TYPE_String => self.deserialize_str(ValueVisitor),
spa_sys::SPA_TYPE_Bytes => self.deserialize_bytes(ValueVisitor),
spa_sys::SPA_TYPE_Rectangle => self.deserialize_rectangle(ValueVisitor),
spa_sys::SPA_TYPE_Fraction => self.deserialize_fraction(ValueVisitor),
spa_sys::SPA_TYPE_Fd => self.deserialize_fd(ValueVisitor),
spa_sys::SPA_TYPE_Struct => self.deserialize_struct(ValueVisitor),
spa_sys::SPA_TYPE_Array => self.deserialize_array_any(),
spa_sys::SPA_TYPE_Object => self.deserialize_object(ValueVisitor),
spa_sys::SPA_TYPE_Choice => self.deserialize_choice(ValueVisitor),
spa_sys::SPA_TYPE_Pointer => self.deserialize_pointer(ValueVisitor),
_ => Err(DeserializeError::InvalidType),
}
}
fn deserialize_array_any(
self,
) -> Result<(Value, DeserializeSuccess<'de>), DeserializeError<&'de [u8]>> {
let child_type = self.peek(preceded(Self::type_(), Self::type_()))?;
let (array, success) = match child_type {
spa_sys::SPA_TYPE_None => {
let (elements, success) = self.deserialize_array_vec::<()>()?;
let array = ValueArrayNoneVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Bool => {
let (elements, success) = self.deserialize_array_vec::<bool>()?;
let array = ValueArrayBoolVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Id => {
let (elements, success) = self.deserialize_array_vec::<Id>()?;
let array = ValueArrayIdVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Int => {
let (elements, success) = self.deserialize_array_vec::<i32>()?;
let array = ValueArrayIntVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Long => {
let (elements, success) = self.deserialize_array_vec::<i64>()?;
let array = ValueArrayLongVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Float => {
let (elements, success) = self.deserialize_array_vec::<f32>()?;
let array = ValueArrayFloatVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Double => {
let (elements, success) = self.deserialize_array_vec::<f64>()?;
let array = ValueArrayDoubleVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Rectangle => {
let (elements, success) = self.deserialize_array_vec::<Rectangle>()?;
let array = ValueArrayRectangleVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Fraction => {
let (elements, success) = self.deserialize_array_vec::<Fraction>()?;
let array = ValueArrayFractionVisitor.visit_array(elements)?;
(array, success)
}
spa_sys::SPA_TYPE_Fd => {
let (elements, success) = self.deserialize_array_vec::<Fd>()?;
let array = ValueArrayFdVisitor.visit_array(elements)?;
(array, success)
}
_ => return Err(DeserializeError::InvalidType),
};
Ok((Value::ValueArray(array), success))
}
pub fn deserialize_any_from(
input: &'de [u8],
) -> Result<(&'de [u8], Value), DeserializeError<&'de [u8]>> {
Self::deserialize_from(input)
}
}
pub struct ArrayPodDeserializer<'de, E: FixedSizedPod> {
deserializer: PodDeserializer<'de>,
length: u32,
deserialized: u32,
_phantom: PhantomData<E>,
}
impl<'de, E: FixedSizedPod> ArrayPodDeserializer<'de, E> {
pub fn deserialize_element(&mut self) -> Result<E, DeserializeError<&'de [u8]>> {
if !self.deserialized < self.length {
panic!("No elements left in the pod to deserialize");
}
let result = self
.deserializer
.parse(E::CanonicalType::deserialize_body)
.map(|res| E::from_canonical_type(&res))
.map_err(|err| err.into());
self.deserialized += 1;
result
}
pub fn end(mut self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
assert!(
self.length == self.deserialized,
"Not all fields were deserialized from the array pod"
);
let bytes_read = self.deserialized * E::CanonicalType::SIZE;
let padding = if bytes_read % 8 == 0 {
0
} else {
8 - (bytes_read as usize % 8)
};
self.deserializer.parse(take(padding))?;
Ok(DeserializeSuccess(self.deserializer))
}
}
pub struct StructPodDeserializer<'de> {
deserializer: Option<PodDeserializer<'de>>,
remaining: u32,
}
impl<'de> StructPodDeserializer<'de> {
pub fn deserialize_field<P: PodDeserialize<'de>>(
&mut self,
) -> Result<Option<P>, DeserializeError<&'de [u8]>> {
if self.remaining == 0 {
Ok(None)
} else {
let deserializer = self
.deserializer
.take()
.expect("StructPodDeserializer does not contain a deserializer");
let remaining_input_len = deserializer.input.len();
let (res, success) = P::deserialize(deserializer)?;
self.remaining -= remaining_input_len as u32 - success.0.input.len() as u32;
self.deserializer = Some(success.0);
Ok(Some(res))
}
}
pub fn end(self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
assert!(
self.remaining == 0,
"Not all fields have been deserialized from the struct"
);
Ok(DeserializeSuccess(self.deserializer.expect(
"StructPodDeserializer does not contain a deserializer",
)))
}
}
pub struct ObjectPodDeserializer<'de> {
deserializer: Option<PodDeserializer<'de>>,
remaining: u32,
object_type: u32,
object_id: u32,
}
impl<'de> ObjectPodDeserializer<'de> {
#[allow(clippy::type_complexity)]
pub fn deserialize_property<P: PodDeserialize<'de>>(
&mut self,
) -> Result<Option<(P, u32, PropertyFlags)>, DeserializeError<&'de [u8]>> {
if self.remaining == 0 {
Ok(None)
} else {
let mut deserializer = self
.deserializer
.take()
.expect("ObjectPodDeserializer does not contain a deserializer");
let remaining_input_len = deserializer.input.len();
let key = deserializer.parse(u32(Endianness::Native))?;
let flags = deserializer.parse(u32(Endianness::Native))?;
let flags = PropertyFlags::from_bits_retain(flags);
let (res, success) = P::deserialize(deserializer)?;
self.remaining -= remaining_input_len as u32 - success.0.input.len() as u32;
self.deserializer = Some(success.0);
Ok(Some((res, key, flags)))
}
}
pub fn deserialize_property_key<P: PodDeserialize<'de>>(
&mut self,
key: u32,
) -> Result<(P, PropertyFlags), DeserializeError<&'de [u8]>> {
let (prop, k, flags) = self
.deserialize_property()?
.ok_or(DeserializeError::PropertyMissing)?;
if k != key {
Err(DeserializeError::PropertyWrongKey(k))
} else {
Ok((prop, flags))
}
}
pub fn end(self) -> Result<DeserializeSuccess<'de>, DeserializeError<&'de [u8]>> {
assert!(
self.remaining == 0,
"Not all properties have been deserialized from the object"
);
Ok(DeserializeSuccess(self.deserializer.expect(
"ObjectPodDeserializer does not contain a deserializer",
)))
}
}
#[derive(Debug, PartialEq)]
pub enum DeserializeError<I> {
Nom(nom::Err<nom::error::Error<I>>),
UnsupportedType,
InvalidType,
PropertyMissing,
PropertyWrongKey(u32),
InvalidChoiceType,
MissingChoiceValues,
}
impl<I> From<nom::Err<nom::error::Error<I>>> for DeserializeError<I> {
fn from(err: nom::Err<nom::error::Error<I>>) -> Self {
DeserializeError::Nom(err)
}
}
pub trait Visitor<'de>: Sized {
type Value;
type ArrayElem;
fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_bool(&self, _v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_int(&self, _v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_long(&self, _v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_float(&self, _v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_double(&self, _v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_string(&self, _v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_bytes(&self, _v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_rectangle(&self, _v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_fraction(&self, _v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_id(&self, _v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_fd(&self, _v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_struct(
&self,
_struct_deserializer: &mut StructPodDeserializer<'de>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_array(
&self,
_elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_object(
&self,
_object_deserializer: &mut ObjectPodDeserializer<'de>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_bool(
&self,
_choice: Choice<bool>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_i32(
&self,
_choice: Choice<i32>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_i64(
&self,
_choice: Choice<i64>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_f32(
&self,
_choice: Choice<f32>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_f64(
&self,
_choice: Choice<f64>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_id(
&self,
_choice: Choice<Id>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_rectangle(
&self,
_choice: Choice<Rectangle>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_fraction(
&self,
_choice: Choice<Fraction>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_choice_fd(
&self,
_choice: Choice<Fd>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
fn visit_pointer(
&self,
_type: u32,
_pointer: *const c_void,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Err(DeserializeError::UnsupportedType)
}
}
pub struct NoneVisitor;
impl<'de> Visitor<'de> for NoneVisitor {
type Value = ();
type ArrayElem = Infallible;
fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(())
}
}
pub struct BoolVisitor;
impl<'de> Visitor<'de> for BoolVisitor {
type Value = bool;
type ArrayElem = Infallible;
fn visit_bool(&self, v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct IntVisitor;
impl<'de> Visitor<'de> for IntVisitor {
type Value = i32;
type ArrayElem = Infallible;
fn visit_int(&self, v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct LongVisitor;
impl<'de> Visitor<'de> for LongVisitor {
type Value = i64;
type ArrayElem = Infallible;
fn visit_long(&self, v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct FloatVisitor;
impl<'de> Visitor<'de> for FloatVisitor {
type Value = f32;
type ArrayElem = Infallible;
fn visit_float(&self, v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct DoubleVisitor;
impl<'de> Visitor<'de> for DoubleVisitor {
type Value = f64;
type ArrayElem = Infallible;
fn visit_double(&self, v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct StringVisitor;
impl<'de> Visitor<'de> for StringVisitor {
type Value = &'de str;
type ArrayElem = Infallible;
fn visit_string(&self, v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct BytesVisitor;
impl<'de> Visitor<'de> for BytesVisitor {
type Value = &'de [u8];
type ArrayElem = Infallible;
fn visit_bytes(&self, v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct RectangleVisitor;
impl<'de> Visitor<'de> for RectangleVisitor {
type Value = Rectangle;
type ArrayElem = Infallible;
fn visit_rectangle(&self, v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct FractionVisitor;
impl<'de> Visitor<'de> for FractionVisitor {
type Value = Fraction;
type ArrayElem = Infallible;
fn visit_fraction(&self, v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct IdVisitor;
impl<'de> Visitor<'de> for IdVisitor {
type Value = Id;
type ArrayElem = Infallible;
fn visit_id(&self, v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct FdVisitor;
impl<'de> Visitor<'de> for FdVisitor {
type Value = Fd;
type ArrayElem = Infallible;
fn visit_fd(&self, v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(v)
}
}
pub struct VecVisitor<E: FixedSizedPod> {
_phantom: PhantomData<E>,
}
impl<E: FixedSizedPod> Default for VecVisitor<E> {
fn default() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<'de, E: CanonicalFixedSizedPod + std::marker::Copy> Visitor<'de> for VecVisitor<E> {
type Value = Vec<E>;
type ArrayElem = E;
fn visit_array(&self, elements: Vec<E>) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(elements)
}
}
pub struct ValueVisitor;
impl<'de> Visitor<'de> for ValueVisitor {
type Value = Value;
type ArrayElem = std::convert::Infallible;
fn visit_none(&self) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::None)
}
fn visit_bool(&self, v: bool) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Bool(v))
}
fn visit_int(&self, v: i32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Int(v))
}
fn visit_long(&self, v: i64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Long(v))
}
fn visit_float(&self, v: f32) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Float(v))
}
fn visit_double(&self, v: f64) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Double(v))
}
fn visit_string(&self, v: &'de str) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::String(v.to_string()))
}
fn visit_bytes(&self, v: &'de [u8]) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Bytes(v.to_vec()))
}
fn visit_rectangle(&self, v: Rectangle) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Rectangle(v))
}
fn visit_fraction(&self, v: Fraction) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Fraction(v))
}
fn visit_id(&self, v: Id) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Id(v))
}
fn visit_fd(&self, v: Fd) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Fd(v))
}
fn visit_struct(
&self,
struct_deserializer: &mut StructPodDeserializer<'de>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
let mut res = Vec::new();
while let Some(value) = struct_deserializer.deserialize_field()? {
res.push(value);
}
Ok(Value::Struct(res))
}
fn visit_object(
&self,
object_deserializer: &mut ObjectPodDeserializer<'de>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
let mut properties = Vec::new();
while let Some((value, key, flags)) = object_deserializer.deserialize_property()? {
let prop = Property { key, flags, value };
properties.push(prop);
}
let object = Object {
type_: object_deserializer.object_type,
id: object_deserializer.object_id,
properties,
};
Ok(Value::Object(object))
}
fn visit_choice_bool(
&self,
choice: Choice<bool>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Bool(choice)))
}
fn visit_choice_i32(
&self,
choice: Choice<i32>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Int(choice)))
}
fn visit_choice_i64(
&self,
choice: Choice<i64>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Long(choice)))
}
fn visit_choice_f32(
&self,
choice: Choice<f32>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Float(choice)))
}
fn visit_choice_f64(
&self,
choice: Choice<f64>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Double(choice)))
}
fn visit_choice_id(
&self,
choice: Choice<Id>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Id(choice)))
}
fn visit_choice_rectangle(
&self,
choice: Choice<Rectangle>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Rectangle(choice)))
}
fn visit_choice_fraction(
&self,
choice: Choice<Fraction>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Fraction(choice)))
}
fn visit_choice_fd(
&self,
choice: Choice<Fd>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Choice(ChoiceValue::Fd(choice)))
}
fn visit_pointer(
&self,
type_: u32,
pointer: *const c_void,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(Value::Pointer(type_, pointer))
}
}
struct ValueArrayNoneVisitor;
impl<'de> Visitor<'de> for ValueArrayNoneVisitor {
type Value = ValueArray;
type ArrayElem = ();
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::None(elements))
}
}
struct ValueArrayBoolVisitor;
impl<'de> Visitor<'de> for ValueArrayBoolVisitor {
type Value = ValueArray;
type ArrayElem = bool;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Bool(elements))
}
}
struct ValueArrayIdVisitor;
impl<'de> Visitor<'de> for ValueArrayIdVisitor {
type Value = ValueArray;
type ArrayElem = Id;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Id(elements))
}
}
struct ValueArrayIntVisitor;
impl<'de> Visitor<'de> for ValueArrayIntVisitor {
type Value = ValueArray;
type ArrayElem = i32;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Int(elements))
}
}
struct ValueArrayLongVisitor;
impl<'de> Visitor<'de> for ValueArrayLongVisitor {
type Value = ValueArray;
type ArrayElem = i64;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Long(elements))
}
}
struct ValueArrayFloatVisitor;
impl<'de> Visitor<'de> for ValueArrayFloatVisitor {
type Value = ValueArray;
type ArrayElem = f32;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Float(elements))
}
}
struct ValueArrayDoubleVisitor;
impl<'de> Visitor<'de> for ValueArrayDoubleVisitor {
type Value = ValueArray;
type ArrayElem = f64;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Double(elements))
}
}
struct ValueArrayRectangleVisitor;
impl<'de> Visitor<'de> for ValueArrayRectangleVisitor {
type Value = ValueArray;
type ArrayElem = Rectangle;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Rectangle(elements))
}
}
struct ValueArrayFractionVisitor;
impl<'de> Visitor<'de> for ValueArrayFractionVisitor {
type Value = ValueArray;
type ArrayElem = Fraction;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Fraction(elements))
}
}
struct ValueArrayFdVisitor;
impl<'de> Visitor<'de> for ValueArrayFdVisitor {
type Value = ValueArray;
type ArrayElem = Fd;
fn visit_array(
&self,
elements: Vec<Self::ArrayElem>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(ValueArray::Fd(elements))
}
}
pub struct ChoiceBoolVisitor;
impl<'de> Visitor<'de> for ChoiceBoolVisitor {
type Value = Choice<bool>;
type ArrayElem = Infallible;
fn visit_choice_bool(
&self,
choice: Choice<bool>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceIntVisitor;
impl<'de> Visitor<'de> for ChoiceIntVisitor {
type Value = Choice<i32>;
type ArrayElem = Infallible;
fn visit_choice_i32(
&self,
choice: Choice<i32>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceLongVisitor;
impl<'de> Visitor<'de> for ChoiceLongVisitor {
type Value = Choice<i64>;
type ArrayElem = Infallible;
fn visit_choice_i64(
&self,
choice: Choice<i64>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceFloatVisitor;
impl<'de> Visitor<'de> for ChoiceFloatVisitor {
type Value = Choice<f32>;
type ArrayElem = Infallible;
fn visit_choice_f32(
&self,
choice: Choice<f32>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceDoubleVisitor;
impl<'de> Visitor<'de> for ChoiceDoubleVisitor {
type Value = Choice<f64>;
type ArrayElem = Infallible;
fn visit_choice_f64(
&self,
choice: Choice<f64>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceIdVisitor;
impl<'de> Visitor<'de> for ChoiceIdVisitor {
type Value = Choice<Id>;
type ArrayElem = Infallible;
fn visit_choice_id(
&self,
choice: Choice<Id>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceRectangleVisitor;
impl<'de> Visitor<'de> for ChoiceRectangleVisitor {
type Value = Choice<Rectangle>;
type ArrayElem = Infallible;
fn visit_choice_rectangle(
&self,
choice: Choice<Rectangle>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceFractionVisitor;
impl<'de> Visitor<'de> for ChoiceFractionVisitor {
type Value = Choice<Fraction>;
type ArrayElem = Infallible;
fn visit_choice_fraction(
&self,
choice: Choice<Fraction>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct ChoiceFdVisitor;
impl<'de> Visitor<'de> for ChoiceFdVisitor {
type Value = Choice<Fd>;
type ArrayElem = Infallible;
fn visit_choice_fd(
&self,
choice: Choice<Fd>,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok(choice)
}
}
pub struct PointerVisitor<T> {
_phantom: PhantomData<T>,
}
impl<T> Default for PointerVisitor<T> {
fn default() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl<'de, T> Visitor<'de> for PointerVisitor<T> {
type Value = (u32, *const T);
type ArrayElem = Infallible;
fn visit_pointer(
&self,
type_: u32,
pointer: *const c_void,
) -> Result<Self::Value, DeserializeError<&'de [u8]>> {
Ok((type_, pointer as *const T))
}
}