rsomeip_bytes/
de.rs

1//! Deserialization according to the SOME/IP protocol.
2//!
3//! Provides the [`Deserialize`] trait for deserializing data, and several implementations of this
4//! trait for types of the standard library.
5
6use super::{Buf, Bytes, LengthField};
7
8/// Deserialize data from a SOME/IP byte stream.
9///
10/// This trait provides methods for deserializing data structures from a byte stream ([`Buf`])
11/// encoded in the SOME/IP on-wire format.
12///
13/// [`deserialize`] is used to deserialize statically sized types, while [`deserialize_len`] is
14/// used to deserialize dynamically sized types from the stream.
15///
16/// [`deserialize`]: Deserialize::deserialize
17/// [`deserialize_len`]: Deserialize::deserialize_len
18pub trait Deserialize {
19    /// Type of the data that will be deserialized.
20    type Output: Sized;
21
22    /// Deserializes an instance of [`Deserialize::Output`] from the buffer.
23    ///
24    /// # Errors
25    ///
26    /// This function will return an error if the deserialization process fails for any reason,
27    /// such as encountering unexpected data or running out of data in the buffer.
28    ///
29    /// # Examples
30    ///
31    /// ```rust
32    /// use rsomeip_bytes::{Bytes, Deserialize, DeserializeError};
33    /// let mut buffer = Bytes::copy_from_slice(&[1u8, 2u8]);
34    /// assert_eq!(u8::deserialize(&mut buffer), Ok(1u8));
35    /// assert_eq!(u8::deserialize(&mut buffer), Ok(2u8));
36    /// assert_eq!(u8::deserialize(&mut buffer), Err(DeserializeError::InsufficientData { expected: 1, available: 0 }));
37    /// ```
38    fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError>;
39
40    /// Deserializes an instance of [`Deserialize::Output`] from the buffer.
41    ///
42    /// This method specifies a length field which is used to indicate the size of the data to be
43    /// deserialized. This is necessary in case of dynamically sized data structures, like [`Vec`]
44    /// or [`String`].
45    ///
46    /// # Errors
47    ///
48    /// This function will return an error if the deserialization process fails for any reason,
49    /// such as encountering unexpected data, running out of data in the buffer, or exceeding the
50    /// specified length.
51    ///
52    /// # Examples
53    ///
54    /// ```rust
55    /// use rsomeip_bytes::{Bytes, Deserialize, DeserializeError, LengthField};
56    ///
57    /// let mut buffer = Bytes::copy_from_slice(&[2u8, 1u8, 2u8, 3u8]);
58    /// let vec: Vec<u8> = Vec::deserialize_len(LengthField::U8, &mut buffer).unwrap();
59    /// assert_eq!(&vec[..], &[1u8, 2u8][..]);
60    ///
61    /// assert_eq!(u8::deserialize(&mut buffer), Ok(3u8));
62    /// assert_eq!(u8::deserialize(&mut buffer), Err(DeserializeError::InsufficientData { expected: 1, available: 0 }));
63    /// ```
64    fn deserialize_len(
65        length: LengthField,
66        buffer: &mut impl Buf,
67    ) -> Result<Self::Output, DeserializeError> {
68        let length: usize = match length {
69            LengthField::U8 => u8::deserialize(buffer)?.into(),
70            LengthField::U16 => u16::deserialize(buffer)?.into(),
71            LengthField::U32 => u32::deserialize(buffer)?.try_into().map_err(|error| {
72                DeserializeError::Other(format!("invalid length field: {error}"))
73            })?,
74        };
75        let mut payload = buffer.take(length);
76        Self::deserialize(&mut payload)
77    }
78}
79
80macro_rules! deserialize_basic_type {
81    ($t:ty, $f:ident) => {
82        impl Deserialize for $t {
83            type Output = Self;
84
85            fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
86                if buffer.remaining() < size_of::<Self>() {
87                    return Err(DeserializeError::InsufficientData {
88                        expected: size_of::<$t>(),
89                        available: buffer.remaining(),
90                    });
91                }
92                Ok(buffer.$f())
93            }
94        }
95    };
96}
97
98deserialize_basic_type!(u8, get_u8);
99deserialize_basic_type!(u16, get_u16);
100deserialize_basic_type!(u32, get_u32);
101deserialize_basic_type!(u64, get_u64);
102deserialize_basic_type!(i8, get_i8);
103deserialize_basic_type!(i16, get_i16);
104deserialize_basic_type!(i32, get_i32);
105deserialize_basic_type!(i64, get_i64);
106deserialize_basic_type!(f32, get_f32);
107deserialize_basic_type!(f64, get_f64);
108
109impl Deserialize for bool {
110    type Output = Self;
111
112    fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
113        if buffer.remaining() < size_of::<Self>() {
114            return Err(DeserializeError::InsufficientData {
115                expected: 1,
116                available: buffer.remaining(),
117            });
118        }
119        Ok((buffer.get_u8() & 0x01) == 0x01)
120    }
121}
122
123impl<T, const N: usize> Deserialize for [T; N]
124where
125    T: Deserialize<Output = T> + Default,
126{
127    type Output = Self;
128
129    fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
130        Ok(std::array::from_fn(|_| {
131            T::deserialize(buffer).unwrap_or_default()
132        }))
133    }
134}
135
136impl<T> Deserialize for Vec<T>
137where
138    T: Deserialize<Output = T>,
139{
140    type Output = Self;
141
142    fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
143        let mut vec = vec![];
144        while buffer.has_remaining() {
145            vec.push(T::deserialize(buffer)?);
146        }
147        Ok(vec)
148    }
149}
150
151macro_rules! deserialize_tuple {
152    ( $( $name:ident )+ ) => {
153        impl<$($name: Deserialize<Output=$name>),+> Deserialize for ($($name,)+) {
154            type Output = Self;
155            fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
156                Ok((
157                    $($name::deserialize(buffer)?,)+
158                ))
159            }
160        }
161    };
162}
163
164deserialize_tuple! { A }
165deserialize_tuple! { A B }
166deserialize_tuple! { A B C }
167deserialize_tuple! { A B C D }
168deserialize_tuple! { A B C D E }
169deserialize_tuple! { A B C D E F }
170deserialize_tuple! { A B C D E F G }
171deserialize_tuple! { A B C D E F G H }
172deserialize_tuple! { A B C D E F G H I }
173deserialize_tuple! { A B C D E F G H I J }
174deserialize_tuple! { A B C D E F G H I J K }
175deserialize_tuple! { A B C D E F G H I J K L }
176
177impl Deserialize for String {
178    type Output = Self;
179
180    fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
181        /// Deserializes an UTF-8 encoded, null terminated string.
182        fn deserialize_utf8(buffer: &mut impl Buf) -> Result<String, DeserializeError> {
183            let bom = u8::deserialize(buffer)?;
184            if bom != 0xbf_u8 {
185                return Err(DeserializeError::Other(format!(
186                    "incorrect UTF-8 Byte Order Mark: 'EF BB BF' vs 'EF BB {bom:02X}'"
187                )));
188            }
189            let mut raw_string = Vec::<u8>::new();
190            loop {
191                let value = u8::deserialize(buffer)?;
192                if value == 0x00 {
193                    break;
194                }
195                raw_string.push(value);
196            }
197            String::from_utf8(raw_string)
198                .map_err(|error| DeserializeError::Other(format!("invalid UTF-8 string: {error}")))
199        }
200        /// Deserializes an UTF-16 encoded, null terminated string.
201        fn deserialize_utf16(
202            buffer: &mut impl Buf,
203            is_be: bool,
204        ) -> Result<String, DeserializeError> {
205            let mut raw_string = Vec::<u16>::new();
206            loop {
207                let value = if is_be {
208                    u16::deserialize(buffer)?
209                } else {
210                    u16::deserialize(buffer).map(u16::from_be)?
211                };
212                if value == 0x0000 {
213                    break;
214                }
215                raw_string.push(value);
216            }
217            String::from_utf16(&raw_string)
218                .map_err(|error| DeserializeError::Other(format!("invalid UTF-16 string: {error}")))
219        }
220        match u16::deserialize(buffer)? {
221            0xefbb => deserialize_utf8(buffer),
222            0xfeff => deserialize_utf16(buffer, true),
223            0xfffe => deserialize_utf16(buffer, false),
224            value => Err(DeserializeError::Other(format!(
225                "invalid Byte Order Mark: {value:04X}"
226            ))),
227        }
228    }
229}
230
231impl Deserialize for Bytes {
232    type Output = Self;
233
234    fn deserialize(buffer: &mut impl Buf) -> Result<Self::Output, DeserializeError> {
235        Ok(buffer.copy_to_bytes(buffer.remaining()))
236    }
237}
238
239/// Represents an error during the deserialization process.
240#[derive(Debug, PartialEq, Eq, thiserror::Error)]
241#[non_exhaustive]
242pub enum DeserializeError {
243    /// There is insufficient data in the buffer to deserialize the complete type.
244    #[error("insufficient data in buffer: {expected} vs {available}")]
245    InsufficientData {
246        /// Size of the expected data.
247        expected: usize,
248        /// Size of the available data.
249        available: usize,
250    },
251    /// Some other error has occurred.
252    #[error("{0}")]
253    Other(String),
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use bytes::Bytes;
260
261    macro_rules! test_deserialize_basic_type {
262        ($t:ty, $name:tt) => {
263            #[test]
264            #[allow(clippy::cast_precision_loss, clippy::cast_lossless)]
265            fn $name() {
266                let mut buffer = Bytes::from((1 as $t).to_be_bytes().to_vec());
267                assert_eq!(<$t>::deserialize(&mut buffer), Ok(1 as $t));
268                assert_eq!(
269                    <$t>::deserialize(&mut buffer),
270                    Err(DeserializeError::InsufficientData {
271                        expected: size_of::<$t>(),
272                        available: 0
273                    })
274                );
275            }
276        };
277    }
278
279    test_deserialize_basic_type!(u8, deserialize_u8);
280    test_deserialize_basic_type!(u16, deserialize_u16);
281    test_deserialize_basic_type!(u32, deserialize_u32);
282    test_deserialize_basic_type!(u64, deserialize_u64);
283    test_deserialize_basic_type!(i8, deserialize_i8);
284    test_deserialize_basic_type!(i16, deserialize_i16);
285    test_deserialize_basic_type!(i32, deserialize_i32);
286    test_deserialize_basic_type!(i64, deserialize_i64);
287    test_deserialize_basic_type!(f32, deserialize_f32);
288    test_deserialize_basic_type!(f64, deserialize_f64);
289
290    #[test]
291    fn deserialize_bool() {
292        let mut buffer = Bytes::copy_from_slice(&[0u8, 1u8]);
293        assert_eq!(bool::deserialize(&mut buffer), Ok(false));
294        assert_eq!(bool::deserialize(&mut buffer), Ok(true));
295        assert_eq!(
296            bool::deserialize(&mut buffer),
297            Err(DeserializeError::InsufficientData {
298                expected: 1,
299                available: 0
300            })
301        );
302    }
303
304    #[test]
305    fn deserialize_len() {
306        let mut buffer = Bytes::copy_from_slice(&[2u8, 1u8, 2u8, 3u8]);
307        let vec: Vec<u8> =
308            Vec::deserialize_len(LengthField::U8, &mut buffer).expect("should deserialize the vec");
309        assert_eq!(&vec[..], &[1u8, 2u8][..]);
310    }
311
312    #[test]
313    fn deserialize_array() {
314        let mut buffer = Bytes::copy_from_slice(&[1u8, 2u8]);
315        assert_eq!(<[u8; 2]>::deserialize(&mut buffer), Ok([1u8, 2u8]));
316        assert_eq!(<[u8; 2]>::deserialize(&mut buffer), Ok([0u8, 0u8]));
317    }
318
319    #[test]
320    fn deserialize_vec() {
321        let mut buffer = Bytes::copy_from_slice(&[1u8, 2u8]);
322        let vec: Vec<u8> = Vec::deserialize(&mut buffer).expect("should deserialize the vec");
323        assert_eq!(&vec[..], &[1u8, 2u8][..]);
324    }
325
326    #[test]
327    fn deserialize_malformed_vec() {
328        let mut buffer = Bytes::copy_from_slice(&[1u8, 2u8, 3u8]);
329        let error =
330            Vec::<u16>::deserialize(&mut buffer).expect_err("should not deserialize the vec");
331        assert_eq!(
332            error,
333            DeserializeError::InsufficientData {
334                expected: size_of::<u16>(),
335                available: 1
336            }
337        );
338    }
339
340    #[test]
341    fn deserialize_tuple() {
342        let mut buffer = Bytes::copy_from_slice(&[1u8, 2u8]);
343        assert_eq!(<(u8, u8)>::deserialize(&mut buffer), Ok((1u8, 2u8)));
344        assert_eq!(
345            <(u8, u8)>::deserialize(&mut buffer),
346            Err(DeserializeError::InsufficientData {
347                expected: size_of::<u8>(),
348                available: 0
349            })
350        );
351    }
352
353    #[test]
354    fn deserialize_bytes() {
355        let mut buffer = Bytes::copy_from_slice(&[2u8, 1u8, 2u8, 3u8, 4u8]);
356
357        let bytes = Bytes::deserialize_len(LengthField::U8, &mut buffer)
358            .expect("should deserialize the bytes");
359        assert_eq!(&bytes[..], &[1u8, 2u8][..]);
360
361        let bytes = Bytes::deserialize(&mut buffer).expect("should deserialize the bytes");
362        assert_eq!(&bytes[..], &[3u8, 4u8][..]);
363    }
364
365    #[test]
366    fn deserialize_utf8() {
367        let raw_string = [
368            0xef_u8, // Byte Order Mark
369            0xbb, 0xbf, 0x72, 0x75, 0x73, 0x74, // "rust"
370            0x00, // Delimiter
371        ];
372        let mut buffer = Bytes::copy_from_slice(&raw_string);
373        assert_eq!(String::deserialize(&mut buffer), Ok(String::from("rust")));
374    }
375
376    #[test]
377    fn deserialize_utf16_be() {
378        let raw_string = [
379            0xfe_u8, 0xff, // Big-Endian Byte Order Mark
380            0x95, 0x08, // "锈"
381            0x00, 0x00, // Delimiter
382        ];
383        let mut buffer = Bytes::copy_from_slice(&raw_string);
384        assert_eq!(String::deserialize(&mut buffer), Ok(String::from("锈")));
385    }
386
387    #[test]
388    fn deserialize_utf16_le() {
389        let raw_string = [
390            0xff_u8, 0xfe, // Little-Endian Byte Order Mark
391            0x08, 0x95, // "锈"
392            0x00, 0x00, // Delimiter
393        ];
394        let mut buffer = Bytes::copy_from_slice(&raw_string);
395        assert_eq!(String::deserialize(&mut buffer), Ok(String::from("锈")));
396    }
397}