• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 use crate::binder::{AsNative, FromIBinder, Stability, Strong};
18 use crate::error::{status_result, status_t, Result, Status, StatusCode};
19 use crate::parcel::BorrowedParcel;
20 use crate::proxy::SpIBinder;
21 use crate::sys;
22 
23 use std::convert::{TryFrom, TryInto};
24 use std::ffi::c_void;
25 use std::mem::{self, ManuallyDrop, MaybeUninit};
26 use std::os::raw::c_char;
27 use std::ptr;
28 use std::slice;
29 
30 /// Super-trait for Binder parcelables.
31 ///
32 /// This trait is equivalent `android::Parcelable` in C++,
33 /// and defines a common interface that all parcelables need
34 /// to implement.
35 pub trait Parcelable {
36     /// Internal serialization function for parcelables.
37     ///
38     /// This method is mainly for internal use.
39     /// `Serialize::serialize` and its variants are generally
40     /// preferred over this function, since the former also
41     /// prepend a header.
write_to_parcel(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>42     fn write_to_parcel(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
43 
44     /// Internal deserialization function for parcelables.
45     ///
46     /// This method is mainly for internal use.
47     /// `Deserialize::deserialize` and its variants are generally
48     /// preferred over this function, since the former also
49     /// parse the additional header.
read_from_parcel(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()>50     fn read_from_parcel(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()>;
51 }
52 
53 /// A struct whose instances can be written to a [`Parcel`].
54 // Might be able to hook this up as a serde backend in the future?
55 pub trait Serialize {
56     /// Serialize this instance into the given [`Parcel`].
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>57     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
58 }
59 
60 /// A struct whose instances can be restored from a [`Parcel`].
61 // Might be able to hook this up as a serde backend in the future?
62 pub trait Deserialize: Sized {
63     /// Deserialize an instance from the given [`Parcel`].
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>64     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>;
65 
66     /// Deserialize an instance from the given [`Parcel`] onto the
67     /// current object. This operation will overwrite the old value
68     /// partially or completely, depending on how much data is available.
deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()>69     fn deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
70         *self = Self::deserialize(parcel)?;
71         Ok(())
72     }
73 }
74 
75 /// Helper trait for types that can be serialized as arrays.
76 /// Defaults to calling Serialize::serialize() manually for every element,
77 /// but can be overridden for custom implementations like `writeByteArray`.
78 // Until specialization is stabilized in Rust, we need this to be a separate
79 // trait because it's the only way to have a default implementation for a method.
80 // We want the default implementation for most types, but an override for
81 // a few special ones like `readByteArray` for `u8`.
82 pub trait SerializeArray: Serialize + Sized {
83     /// Serialize an array of this type into the given parcel.
serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()>84     fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
85         let res = unsafe {
86             // Safety: Safe FFI, slice will always be a safe pointer to pass.
87             sys::AParcel_writeParcelableArray(
88                 parcel.as_native_mut(),
89                 slice.as_ptr() as *const c_void,
90                 slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
91                 Some(serialize_element::<Self>),
92             )
93         };
94         status_result(res)
95     }
96 }
97 
98 /// Callback to serialize an element of a generic parcelable array.
99 ///
100 /// Safety: We are relying on binder_ndk to not overrun our slice. As long as it
101 /// doesn't provide an index larger than the length of the original slice in
102 /// serialize_array, this operation is safe. The index provided is zero-based.
serialize_element<T: Serialize>( parcel: *mut sys::AParcel, array: *const c_void, index: usize, ) -> status_t103 unsafe extern "C" fn serialize_element<T: Serialize>(
104     parcel: *mut sys::AParcel,
105     array: *const c_void,
106     index: usize,
107 ) -> status_t {
108     let slice: &[T] = slice::from_raw_parts(array.cast(), index + 1);
109 
110     let mut parcel = match BorrowedParcel::from_raw(parcel) {
111         None => return StatusCode::UNEXPECTED_NULL as status_t,
112         Some(p) => p,
113     };
114 
115     slice[index].serialize(&mut parcel).err().unwrap_or(StatusCode::OK) as status_t
116 }
117 
118 /// Helper trait for types that can be deserialized as arrays.
119 /// Defaults to calling Deserialize::deserialize() manually for every element,
120 /// but can be overridden for custom implementations like `readByteArray`.
121 pub trait DeserializeArray: Deserialize {
122     /// Deserialize an array of type from the given parcel.
deserialize_array(parcel: &BorrowedParcel<'_>) -> Result<Option<Vec<Self>>>123     fn deserialize_array(parcel: &BorrowedParcel<'_>) -> Result<Option<Vec<Self>>> {
124         let mut vec: Option<Vec<MaybeUninit<Self>>> = None;
125         let res = unsafe {
126             // Safety: Safe FFI, vec is the correct opaque type expected by
127             // allocate_vec and deserialize_element.
128             sys::AParcel_readParcelableArray(
129                 parcel.as_native(),
130                 &mut vec as *mut _ as *mut c_void,
131                 Some(allocate_vec::<Self>),
132                 Some(deserialize_element::<Self>),
133             )
134         };
135         status_result(res)?;
136         let vec: Option<Vec<Self>> = unsafe {
137             // Safety: We are assuming that the NDK correctly initialized every
138             // element of the vector by now, so we know that all the
139             // MaybeUninits are now properly initialized. We can transmute from
140             // Vec<MaybeUninit<T>> to Vec<T> because MaybeUninit<T> has the same
141             // alignment and size as T, so the pointer to the vector allocation
142             // will be compatible.
143             mem::transmute(vec)
144         };
145         Ok(vec)
146     }
147 }
148 
149 /// Callback to deserialize a parcelable element.
150 ///
151 /// The opaque array data pointer must be a mutable pointer to an
152 /// `Option<Vec<MaybeUninit<T>>>` with at least enough elements for `index` to be valid
153 /// (zero-based).
deserialize_element<T: Deserialize>( parcel: *const sys::AParcel, array: *mut c_void, index: usize, ) -> status_t154 unsafe extern "C" fn deserialize_element<T: Deserialize>(
155     parcel: *const sys::AParcel,
156     array: *mut c_void,
157     index: usize,
158 ) -> status_t {
159     let vec = &mut *(array as *mut Option<Vec<MaybeUninit<T>>>);
160     let vec = match vec {
161         Some(v) => v,
162         None => return StatusCode::BAD_INDEX as status_t,
163     };
164 
165     let parcel = match BorrowedParcel::from_raw(parcel as *mut _) {
166         None => return StatusCode::UNEXPECTED_NULL as status_t,
167         Some(p) => p,
168     };
169     let element = match parcel.read() {
170         Ok(e) => e,
171         Err(code) => return code as status_t,
172     };
173     ptr::write(vec[index].as_mut_ptr(), element);
174     StatusCode::OK as status_t
175 }
176 
177 /// Flag that specifies that the following parcelable is present.
178 ///
179 /// This is the Rust equivalent of `Parcel::kNonNullParcelableFlag`
180 /// from `include/binder/Parcel.h` in C++.
181 pub const NON_NULL_PARCELABLE_FLAG: i32 = 1;
182 
183 /// Flag that specifies that the following parcelable is absent.
184 ///
185 /// This is the Rust equivalent of `Parcel::kNullParcelableFlag`
186 /// from `include/binder/Parcel.h` in C++.
187 pub const NULL_PARCELABLE_FLAG: i32 = 0;
188 
189 /// Helper trait for types that can be nullable when serialized.
190 // We really need this trait instead of implementing `Serialize for Option<T>`
191 // because of the Rust orphan rule which prevents us from doing
192 // `impl Serialize for Option<&dyn IFoo>` for AIDL interfaces.
193 // Instead we emit `impl SerializeOption for dyn IFoo` which is allowed.
194 // We also use it to provide a default implementation for AIDL-generated
195 // parcelables.
196 pub trait SerializeOption: Serialize {
197     /// Serialize an Option of this type into the given parcel.
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>198     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
199         if let Some(inner) = this {
200             parcel.write(&NON_NULL_PARCELABLE_FLAG)?;
201             parcel.write(inner)
202         } else {
203             parcel.write(&NULL_PARCELABLE_FLAG)
204         }
205     }
206 }
207 
208 /// Helper trait for types that can be nullable when deserialized.
209 pub trait DeserializeOption: Deserialize {
210     /// Deserialize an Option of this type from the given parcel.
deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>>211     fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
212         let null: i32 = parcel.read()?;
213         if null == NULL_PARCELABLE_FLAG {
214             Ok(None)
215         } else {
216             parcel.read().map(Some)
217         }
218     }
219 
220     /// Deserialize an Option of this type from the given parcel onto the
221     /// current object. This operation will overwrite the current value
222     /// partially or completely, depending on how much data is available.
deserialize_option_from(this: &mut Option<Self>, parcel: &BorrowedParcel<'_>) -> Result<()>223     fn deserialize_option_from(this: &mut Option<Self>, parcel: &BorrowedParcel<'_>) -> Result<()> {
224         *this = Self::deserialize_option(parcel)?;
225         Ok(())
226     }
227 }
228 
229 /// Callback to allocate a vector for parcel array read functions.
230 ///
231 /// This variant is for APIs which use an out buffer pointer.
232 ///
233 /// # Safety
234 ///
235 /// The opaque data pointer passed to the array read function must be a mutable
236 /// pointer to an `Option<Vec<MaybeUninit<T>>>`. `buffer` will be assigned a mutable pointer
237 /// to the allocated vector data if this function returns true.
allocate_vec_with_buffer<T>( data: *mut c_void, len: i32, buffer: *mut *mut T, ) -> bool238 unsafe extern "C" fn allocate_vec_with_buffer<T>(
239     data: *mut c_void,
240     len: i32,
241     buffer: *mut *mut T,
242 ) -> bool {
243     let res = allocate_vec::<T>(data, len);
244     let vec = &mut *(data as *mut Option<Vec<MaybeUninit<T>>>);
245     if let Some(new_vec) = vec {
246         *buffer = new_vec.as_mut_ptr() as *mut T;
247     }
248     res
249 }
250 
251 /// Callback to allocate a vector for parcel array read functions.
252 ///
253 /// # Safety
254 ///
255 /// The opaque data pointer passed to the array read function must be a mutable
256 /// pointer to an `Option<Vec<MaybeUninit<T>>>`.
allocate_vec<T>(data: *mut c_void, len: i32) -> bool257 unsafe extern "C" fn allocate_vec<T>(data: *mut c_void, len: i32) -> bool {
258     let vec = &mut *(data as *mut Option<Vec<MaybeUninit<T>>>);
259     if len < 0 {
260         *vec = None;
261         return true;
262     }
263     let mut new_vec: Vec<MaybeUninit<T>> = Vec::with_capacity(len as usize);
264 
265     // Safety: We are filling the vector with uninitialized data here, but this
266     // is safe because the vector contains MaybeUninit elements which can be
267     // uninitialized. We're putting off the actual unsafe bit, transmuting the
268     // vector to a Vec<T> until the contents are initialized.
269     new_vec.set_len(len as usize);
270 
271     ptr::write(vec, Some(new_vec));
272     true
273 }
274 
275 macro_rules! parcelable_primitives {
276     {
277         $(
278             impl $trait:ident for $ty:ty = $fn:path;
279         )*
280     } => {
281         $(impl_parcelable!{$trait, $ty, $fn})*
282     };
283 }
284 
285 /// Safety: All elements in the vector must be properly initialized.
vec_assume_init<T>(vec: Vec<MaybeUninit<T>>) -> Vec<T>286 unsafe fn vec_assume_init<T>(vec: Vec<MaybeUninit<T>>) -> Vec<T> {
287     // We can convert from Vec<MaybeUninit<T>> to Vec<T> because MaybeUninit<T>
288     // has the same alignment and size as T, so the pointer to the vector
289     // allocation will be compatible.
290     let mut vec = ManuallyDrop::new(vec);
291     Vec::from_raw_parts(vec.as_mut_ptr().cast(), vec.len(), vec.capacity())
292 }
293 
294 macro_rules! impl_parcelable {
295     {Serialize, $ty:ty, $write_fn:path} => {
296         impl Serialize for $ty {
297             fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
298                 unsafe {
299                     // Safety: `Parcel` always contains a valid pointer to an
300                     // `AParcel`, and any `$ty` literal value is safe to pass to
301                     // `$write_fn`.
302                     status_result($write_fn(parcel.as_native_mut(), *self))
303                 }
304             }
305         }
306     };
307 
308     {Deserialize, $ty:ty, $read_fn:path} => {
309         impl Deserialize for $ty {
310             fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
311                 let mut val = Self::default();
312                 unsafe {
313                     // Safety: `Parcel` always contains a valid pointer to an
314                     // `AParcel`. We pass a valid, mutable pointer to `val`, a
315                     // literal of type `$ty`, and `$read_fn` will write the
316                     // value read into `val` if successful
317                     status_result($read_fn(parcel.as_native(), &mut val))?
318                 };
319                 Ok(val)
320             }
321         }
322     };
323 
324     {SerializeArray, $ty:ty, $write_array_fn:path} => {
325         impl SerializeArray for $ty {
326             fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
327                 let status = unsafe {
328                     // Safety: `Parcel` always contains a valid pointer to an
329                     // `AParcel`. If the slice is > 0 length, `slice.as_ptr()`
330                     // will be a valid pointer to an array of elements of type
331                     // `$ty`. If the slice length is 0, `slice.as_ptr()` may be
332                     // dangling, but this is safe since the pointer is not
333                     // dereferenced if the length parameter is 0.
334                     $write_array_fn(
335                         parcel.as_native_mut(),
336                         slice.as_ptr(),
337                         slice
338                             .len()
339                             .try_into()
340                             .or(Err(StatusCode::BAD_VALUE))?,
341                     )
342                 };
343                 status_result(status)
344             }
345         }
346     };
347 
348     {DeserializeArray, $ty:ty, $read_array_fn:path} => {
349         impl DeserializeArray for $ty {
350             fn deserialize_array(parcel: &BorrowedParcel<'_>) -> Result<Option<Vec<Self>>> {
351                 let mut vec: Option<Vec<MaybeUninit<Self>>> = None;
352                 let status = unsafe {
353                     // Safety: `Parcel` always contains a valid pointer to an
354                     // `AParcel`. `allocate_vec<T>` expects the opaque pointer to
355                     // be of type `*mut Option<Vec<MaybeUninit<T>>>`, so `&mut vec` is
356                     // correct for it.
357                     $read_array_fn(
358                         parcel.as_native(),
359                         &mut vec as *mut _ as *mut c_void,
360                         Some(allocate_vec_with_buffer),
361                     )
362                 };
363                 status_result(status)?;
364                 let vec: Option<Vec<Self>> = unsafe {
365                     // Safety: We are assuming that the NDK correctly
366                     // initialized every element of the vector by now, so we
367                     // know that all the MaybeUninits are now properly
368                     // initialized.
369                     vec.map(|vec| vec_assume_init(vec))
370                 };
371                 Ok(vec)
372             }
373         }
374     };
375 }
376 
377 impl<T: DeserializeOption> DeserializeArray for Option<T> {}
378 impl<T: SerializeOption> SerializeArray for Option<T> {}
379 
380 parcelable_primitives! {
381     impl Serialize for bool = sys::AParcel_writeBool;
382     impl Deserialize for bool = sys::AParcel_readBool;
383 
384     // This is only safe because `Option<Vec<u8>>` is interchangeable with
385     // `Option<Vec<i8>>` (what the allocator function actually allocates.
386     impl DeserializeArray for u8 = sys::AParcel_readByteArray;
387 
388     impl Serialize for i8 = sys::AParcel_writeByte;
389     impl Deserialize for i8 = sys::AParcel_readByte;
390     impl SerializeArray for i8 = sys::AParcel_writeByteArray;
391     impl DeserializeArray for i8 = sys::AParcel_readByteArray;
392 
393     impl Serialize for u16 = sys::AParcel_writeChar;
394     impl Deserialize for u16 = sys::AParcel_readChar;
395     impl SerializeArray for u16 = sys::AParcel_writeCharArray;
396     impl DeserializeArray for u16 = sys::AParcel_readCharArray;
397 
398     // This is only safe because `Option<Vec<i16>>` is interchangeable with
399     // `Option<Vec<u16>>` (what the allocator function actually allocates.
400     impl DeserializeArray for i16 = sys::AParcel_readCharArray;
401 
402     impl Serialize for u32 = sys::AParcel_writeUint32;
403     impl Deserialize for u32 = sys::AParcel_readUint32;
404     impl SerializeArray for u32 = sys::AParcel_writeUint32Array;
405     impl DeserializeArray for u32 = sys::AParcel_readUint32Array;
406 
407     impl Serialize for i32 = sys::AParcel_writeInt32;
408     impl Deserialize for i32 = sys::AParcel_readInt32;
409     impl SerializeArray for i32 = sys::AParcel_writeInt32Array;
410     impl DeserializeArray for i32 = sys::AParcel_readInt32Array;
411 
412     impl Serialize for u64 = sys::AParcel_writeUint64;
413     impl Deserialize for u64 = sys::AParcel_readUint64;
414     impl SerializeArray for u64 = sys::AParcel_writeUint64Array;
415     impl DeserializeArray for u64 = sys::AParcel_readUint64Array;
416 
417     impl Serialize for i64 = sys::AParcel_writeInt64;
418     impl Deserialize for i64 = sys::AParcel_readInt64;
419     impl SerializeArray for i64 = sys::AParcel_writeInt64Array;
420     impl DeserializeArray for i64 = sys::AParcel_readInt64Array;
421 
422     impl Serialize for f32 = sys::AParcel_writeFloat;
423     impl Deserialize for f32 = sys::AParcel_readFloat;
424     impl SerializeArray for f32 = sys::AParcel_writeFloatArray;
425     impl DeserializeArray for f32 = sys::AParcel_readFloatArray;
426 
427     impl Serialize for f64 = sys::AParcel_writeDouble;
428     impl Deserialize for f64 = sys::AParcel_readDouble;
429     impl SerializeArray for f64 = sys::AParcel_writeDoubleArray;
430     impl DeserializeArray for f64 = sys::AParcel_readDoubleArray;
431 }
432 
433 impl SerializeArray for bool {}
434 impl DeserializeArray for bool {}
435 
436 impl Serialize for u8 {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>437     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
438         (*self as i8).serialize(parcel)
439     }
440 }
441 
442 impl Deserialize for u8 {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>443     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
444         i8::deserialize(parcel).map(|v| v as u8)
445     }
446 }
447 
448 impl SerializeArray for u8 {
serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()>449     fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
450         let status = unsafe {
451             // Safety: `Parcel` always contains a valid pointer to an
452             // `AParcel`. If the slice is > 0 length, `slice.as_ptr()` will be a
453             // valid pointer to an array of elements of type `$ty`. If the slice
454             // length is 0, `slice.as_ptr()` may be dangling, but this is safe
455             // since the pointer is not dereferenced if the length parameter is
456             // 0.
457             sys::AParcel_writeByteArray(
458                 parcel.as_native_mut(),
459                 slice.as_ptr() as *const i8,
460                 slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
461             )
462         };
463         status_result(status)
464     }
465 }
466 
467 impl Serialize for i16 {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>468     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
469         (*self as u16).serialize(parcel)
470     }
471 }
472 
473 impl Deserialize for i16 {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>474     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
475         u16::deserialize(parcel).map(|v| v as i16)
476     }
477 }
478 
479 impl SerializeArray for i16 {
serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()>480     fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
481         let status = unsafe {
482             // Safety: `Parcel` always contains a valid pointer to an
483             // `AParcel`. If the slice is > 0 length, `slice.as_ptr()` will be a
484             // valid pointer to an array of elements of type `$ty`. If the slice
485             // length is 0, `slice.as_ptr()` may be dangling, but this is safe
486             // since the pointer is not dereferenced if the length parameter is
487             // 0.
488             sys::AParcel_writeCharArray(
489                 parcel.as_native_mut(),
490                 slice.as_ptr() as *const u16,
491                 slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
492             )
493         };
494         status_result(status)
495     }
496 }
497 
498 impl SerializeOption for str {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>499     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
500         match this {
501             None => unsafe {
502                 // Safety: `Parcel` always contains a valid pointer to an
503                 // `AParcel`. If the string pointer is null,
504                 // `AParcel_writeString` requires that the length is -1 to
505                 // indicate that we want to serialize a null string.
506                 status_result(sys::AParcel_writeString(parcel.as_native_mut(), ptr::null(), -1))
507             },
508             Some(s) => unsafe {
509                 // Safety: `Parcel` always contains a valid pointer to an
510                 // `AParcel`. `AParcel_writeString` assumes that we pass a utf-8
511                 // string pointer of `length` bytes, which is what str in Rust
512                 // is. The docstring for `AParcel_writeString` says that the
513                 // string input should be null-terminated, but it doesn't
514                 // actually rely on that fact in the code. If this ever becomes
515                 // necessary, we will need to null-terminate the str buffer
516                 // before sending it.
517                 status_result(sys::AParcel_writeString(
518                     parcel.as_native_mut(),
519                     s.as_ptr() as *const c_char,
520                     s.as_bytes().len().try_into().or(Err(StatusCode::BAD_VALUE))?,
521                 ))
522             },
523         }
524     }
525 }
526 
527 impl Serialize for str {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>528     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
529         Some(self).serialize(parcel)
530     }
531 }
532 
533 impl SerializeArray for &str {}
534 
535 impl Serialize for String {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>536     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
537         Some(self.as_str()).serialize(parcel)
538     }
539 }
540 
541 impl SerializeArray for String {}
542 
543 impl SerializeOption for String {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>544     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
545         SerializeOption::serialize_option(this.map(String::as_str), parcel)
546     }
547 }
548 
549 impl Deserialize for Option<String> {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>550     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
551         let mut vec: Option<Vec<u8>> = None;
552         let status = unsafe {
553             // Safety: `Parcel` always contains a valid pointer to an `AParcel`.
554             // `Option<Vec<u8>>` is equivalent to the expected `Option<Vec<i8>>`
555             // for `allocate_vec`, so `vec` is safe to pass as the opaque data
556             // pointer on platforms where char is signed.
557             sys::AParcel_readString(
558                 parcel.as_native(),
559                 &mut vec as *mut _ as *mut c_void,
560                 Some(allocate_vec_with_buffer),
561             )
562         };
563 
564         status_result(status)?;
565         vec.map(|mut s| {
566             // The vector includes a null-terminator and we don't want the
567             // string to be null-terminated for Rust.
568             s.pop();
569             String::from_utf8(s).or(Err(StatusCode::BAD_VALUE))
570         })
571         .transpose()
572     }
573 }
574 
575 impl DeserializeArray for Option<String> {}
576 
577 impl Deserialize for String {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>578     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
579         Deserialize::deserialize(parcel).transpose().unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
580     }
581 }
582 
583 impl DeserializeArray for String {}
584 
585 impl<T: SerializeArray> Serialize for [T] {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>586     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
587         SerializeArray::serialize_array(self, parcel)
588     }
589 }
590 
591 impl<T: SerializeArray> Serialize for Vec<T> {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>592     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
593         SerializeArray::serialize_array(&self[..], parcel)
594     }
595 }
596 
597 impl<T: SerializeArray> SerializeOption for [T] {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>598     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
599         if let Some(v) = this {
600             SerializeArray::serialize_array(v, parcel)
601         } else {
602             parcel.write(&-1i32)
603         }
604     }
605 }
606 
607 impl<T: SerializeArray> SerializeOption for Vec<T> {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>608     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
609         SerializeOption::serialize_option(this.map(Vec::as_slice), parcel)
610     }
611 }
612 
613 impl<T: DeserializeArray> Deserialize for Vec<T> {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>614     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
615         DeserializeArray::deserialize_array(parcel)
616             .transpose()
617             .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
618     }
619 }
620 
621 impl<T: DeserializeArray> DeserializeOption for Vec<T> {
deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>>622     fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
623         DeserializeArray::deserialize_array(parcel)
624     }
625 }
626 
627 impl<T: SerializeArray, const N: usize> Serialize for [T; N] {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>628     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
629         // forwards to T::serialize_array.
630         SerializeArray::serialize_array(self, parcel)
631     }
632 }
633 
634 impl<T: SerializeArray, const N: usize> SerializeOption for [T; N] {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>635     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
636         SerializeOption::serialize_option(this.map(|arr| &arr[..]), parcel)
637     }
638 }
639 
640 impl<T: SerializeArray, const N: usize> SerializeArray for [T; N] {}
641 
642 impl<T: DeserializeArray, const N: usize> Deserialize for [T; N] {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>643     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
644         let vec = DeserializeArray::deserialize_array(parcel)
645             .transpose()
646             .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))?;
647         vec.try_into().or(Err(StatusCode::BAD_VALUE))
648     }
649 }
650 
651 impl<T: DeserializeArray, const N: usize> DeserializeOption for [T; N] {
deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>>652     fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
653         let vec = DeserializeArray::deserialize_array(parcel)?;
654         vec.map(|v| v.try_into().or(Err(StatusCode::BAD_VALUE))).transpose()
655     }
656 }
657 
658 impl<T: DeserializeArray, const N: usize> DeserializeArray for [T; N] {}
659 
660 impl Serialize for Stability {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>661     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
662         i32::from(*self).serialize(parcel)
663     }
664 }
665 
666 impl Deserialize for Stability {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>667     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
668         i32::deserialize(parcel).and_then(Stability::try_from)
669     }
670 }
671 
672 impl Serialize for Status {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>673     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
674         unsafe {
675             // Safety: `Parcel` always contains a valid pointer to an `AParcel`
676             // and `Status` always contains a valid pointer to an `AStatus`, so
677             // both parameters are valid and safe. This call does not take
678             // ownership of either of its parameters.
679             status_result(sys::AParcel_writeStatusHeader(parcel.as_native_mut(), self.as_native()))
680         }
681     }
682 }
683 
684 impl Deserialize for Status {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>685     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
686         let mut status_ptr = ptr::null_mut();
687         let ret_status = unsafe {
688             // Safety: `Parcel` always contains a valid pointer to an
689             // `AParcel`. We pass a mutable out pointer which will be
690             // assigned a valid `AStatus` pointer if the function returns
691             // status OK. This function passes ownership of the status
692             // pointer to the caller, if it was assigned.
693             sys::AParcel_readStatusHeader(parcel.as_native(), &mut status_ptr)
694         };
695         status_result(ret_status)?;
696         Ok(unsafe {
697             // Safety: At this point, the return status of the read call was ok,
698             // so we know that `status_ptr` is a valid, owned pointer to an
699             // `AStatus`, from which we can safely construct a `Status` object.
700             Status::from_ptr(status_ptr)
701         })
702     }
703 }
704 
705 impl<T: Serialize + FromIBinder + ?Sized> Serialize for Strong<T> {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>706     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
707         Serialize::serialize(&**self, parcel)
708     }
709 }
710 
711 impl<T: SerializeOption + FromIBinder + ?Sized> SerializeOption for Strong<T> {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>712     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
713         SerializeOption::serialize_option(this.map(|b| &**b), parcel)
714     }
715 }
716 
717 impl<T: Serialize + FromIBinder + ?Sized> SerializeArray for Strong<T> {}
718 
719 impl<T: FromIBinder + ?Sized> Deserialize for Strong<T> {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>720     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
721         let ibinder: SpIBinder = parcel.read()?;
722         FromIBinder::try_from(ibinder)
723     }
724 }
725 
726 impl<T: FromIBinder + ?Sized> DeserializeOption for Strong<T> {
deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>>727     fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
728         let ibinder: Option<SpIBinder> = parcel.read()?;
729         ibinder.map(FromIBinder::try_from).transpose()
730     }
731 }
732 
733 impl<T: FromIBinder + ?Sized> DeserializeArray for Strong<T> {}
734 
735 // We need these to support Option<&T> for all T
736 impl<T: Serialize + ?Sized> Serialize for &T {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>737     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
738         Serialize::serialize(*self, parcel)
739     }
740 }
741 
742 impl<T: SerializeOption + ?Sized> SerializeOption for &T {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>743     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
744         SerializeOption::serialize_option(this.copied(), parcel)
745     }
746 }
747 
748 impl<T: SerializeOption> Serialize for Option<T> {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>749     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
750         SerializeOption::serialize_option(self.as_ref(), parcel)
751     }
752 }
753 
754 impl<T: DeserializeOption> Deserialize for Option<T> {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>755     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
756         DeserializeOption::deserialize_option(parcel)
757     }
758 
deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()>759     fn deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
760         DeserializeOption::deserialize_option_from(self, parcel)
761     }
762 }
763 
764 /// Implement `Serialize` trait and friends for a parcelable
765 ///
766 /// This is an internal macro used by the AIDL compiler to implement
767 /// `Serialize`, `SerializeArray` and `SerializeOption` for
768 /// structured parcelables. The target type must implement the
769 /// `Parcelable` trait.
770 /// ```
771 #[macro_export]
772 macro_rules! impl_serialize_for_parcelable {
773     ($parcelable:ident) => {
774         $crate::impl_serialize_for_parcelable!($parcelable < >);
775     };
776     ($parcelable:ident < $( $param:ident ),* , >) => {
777         $crate::impl_serialize_for_parcelable!($parcelable < $($param),* >);
778     };
779     ($parcelable:ident < $( $param:ident ),* > ) => {
780         impl < $($param),* > $crate::binder_impl::Serialize for $parcelable < $($param),* > {
781             fn serialize(
782                 &self,
783                 parcel: &mut $crate::binder_impl::BorrowedParcel<'_>,
784             ) -> std::result::Result<(), $crate::StatusCode> {
785                 <Self as $crate::binder_impl::SerializeOption>::serialize_option(Some(self), parcel)
786             }
787         }
788 
789         impl < $($param),* > $crate::binder_impl::SerializeArray for $parcelable < $($param),* > {}
790 
791         impl < $($param),* > $crate::binder_impl::SerializeOption for $parcelable < $($param),* > {
792             fn serialize_option(
793                 this: Option<&Self>,
794                 parcel: &mut $crate::binder_impl::BorrowedParcel<'_>,
795             ) -> std::result::Result<(), $crate::StatusCode> {
796                 if let Some(this) = this {
797                     use $crate::Parcelable;
798                     parcel.write(&$crate::binder_impl::NON_NULL_PARCELABLE_FLAG)?;
799                     this.write_to_parcel(parcel)
800                 } else {
801                     parcel.write(&$crate::binder_impl::NULL_PARCELABLE_FLAG)
802                 }
803             }
804         }
805     };
806 }
807 
808 /// Implement `Deserialize` trait and friends for a parcelable
809 ///
810 /// This is an internal macro used by the AIDL compiler to implement
811 /// `Deserialize`, `DeserializeArray` and `DeserializeOption` for
812 /// structured parcelables. The target type must implement the
813 /// `Parcelable` trait.
814 #[macro_export]
815 macro_rules! impl_deserialize_for_parcelable {
816     ($parcelable:ident) => {
817         $crate::impl_deserialize_for_parcelable!($parcelable < >);
818     };
819     ($parcelable:ident < $( $param:ident ),* , >) => {
820         $crate::impl_deserialize_for_parcelable!($parcelable < $($param),* >);
821     };
822     ($parcelable:ident < $( $param:ident ),* > ) => {
823         impl < $($param: Default),* > $crate::binder_impl::Deserialize for $parcelable < $($param),* > {
824             fn deserialize(
825                 parcel: &$crate::binder_impl::BorrowedParcel<'_>,
826             ) -> std::result::Result<Self, $crate::StatusCode> {
827                 $crate::binder_impl::DeserializeOption::deserialize_option(parcel)
828                     .transpose()
829                     .unwrap_or(Err($crate::StatusCode::UNEXPECTED_NULL))
830             }
831             fn deserialize_from(
832                 &mut self,
833                 parcel: &$crate::binder_impl::BorrowedParcel<'_>,
834             ) -> std::result::Result<(), $crate::StatusCode> {
835                 let status: i32 = parcel.read()?;
836                 if status == $crate::binder_impl::NULL_PARCELABLE_FLAG {
837                     Err($crate::StatusCode::UNEXPECTED_NULL)
838                 } else {
839                     use $crate::Parcelable;
840                     self.read_from_parcel(parcel)
841                 }
842             }
843         }
844 
845         impl < $($param: Default),* > $crate::binder_impl::DeserializeArray for $parcelable < $($param),* > {}
846 
847         impl < $($param: Default),* > $crate::binder_impl::DeserializeOption for $parcelable < $($param),* > {
848             fn deserialize_option(
849                 parcel: &$crate::binder_impl::BorrowedParcel<'_>,
850             ) -> std::result::Result<Option<Self>, $crate::StatusCode> {
851                 let mut result = None;
852                 Self::deserialize_option_from(&mut result, parcel)?;
853                 Ok(result)
854             }
855             fn deserialize_option_from(
856                 this: &mut Option<Self>,
857                 parcel: &$crate::binder_impl::BorrowedParcel<'_>,
858             ) -> std::result::Result<(), $crate::StatusCode> {
859                 let status: i32 = parcel.read()?;
860                 if status == $crate::binder_impl::NULL_PARCELABLE_FLAG {
861                     *this = None;
862                     Ok(())
863                 } else {
864                     use $crate::Parcelable;
865                     this.get_or_insert_with(Self::default).read_from_parcel(parcel)
866                 }
867             }
868         }
869     };
870 }
871 
872 impl<T: Serialize> Serialize for Box<T> {
serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>873     fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
874         Serialize::serialize(&**self, parcel)
875     }
876 }
877 
878 impl<T: Deserialize> Deserialize for Box<T> {
deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>879     fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
880         Deserialize::deserialize(parcel).map(Box::new)
881     }
882 }
883 
884 impl<T: SerializeOption> SerializeOption for Box<T> {
serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()>885     fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
886         SerializeOption::serialize_option(this.map(|inner| &**inner), parcel)
887     }
888 }
889 
890 impl<T: DeserializeOption> DeserializeOption for Box<T> {
deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>>891     fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
892         DeserializeOption::deserialize_option(parcel).map(|t| t.map(Box::new))
893     }
894 }
895 
896 #[cfg(test)]
897 mod tests {
898     use super::*;
899     use crate::parcel::Parcel;
900 
901     #[test]
test_custom_parcelable()902     fn test_custom_parcelable() {
903         struct Custom(u32, bool, String, Vec<String>);
904 
905         impl Serialize for Custom {
906             fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
907                 self.0.serialize(parcel)?;
908                 self.1.serialize(parcel)?;
909                 self.2.serialize(parcel)?;
910                 self.3.serialize(parcel)
911             }
912         }
913 
914         impl Deserialize for Custom {
915             fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
916                 Ok(Custom(
917                     parcel.read()?,
918                     parcel.read()?,
919                     parcel.read()?,
920                     parcel.read::<Option<Vec<String>>>()?.unwrap(),
921                 ))
922             }
923         }
924 
925         let string8 = "Custom Parcelable".to_string();
926 
927         let s1 = "str1".to_string();
928         let s2 = "str2".to_string();
929         let s3 = "str3".to_string();
930 
931         let strs = vec![s1, s2, s3];
932 
933         let custom = Custom(123_456_789, true, string8, strs);
934 
935         let mut parcel = Parcel::new();
936         let start = parcel.get_data_position();
937 
938         assert!(custom.serialize(&mut parcel.borrowed()).is_ok());
939 
940         unsafe {
941             assert!(parcel.set_data_position(start).is_ok());
942         }
943 
944         let custom2 = Custom::deserialize(parcel.borrowed_ref()).unwrap();
945 
946         assert_eq!(custom2.0, 123_456_789);
947         assert!(custom2.1);
948         assert_eq!(custom2.2, custom.2);
949         assert_eq!(custom2.3, custom.3);
950     }
951 
952     #[test]
953     #[allow(clippy::excessive_precision)]
test_slice_parcelables()954     fn test_slice_parcelables() {
955         let bools = [true, false, false, true];
956 
957         let mut parcel = Parcel::new();
958         let start = parcel.get_data_position();
959 
960         assert!(bools.serialize(&mut parcel.borrowed()).is_ok());
961 
962         unsafe {
963             assert!(parcel.set_data_position(start).is_ok());
964         }
965 
966         assert_eq!(parcel.read::<u32>().unwrap(), 4);
967         assert_eq!(parcel.read::<u32>().unwrap(), 1);
968         assert_eq!(parcel.read::<u32>().unwrap(), 0);
969         assert_eq!(parcel.read::<u32>().unwrap(), 0);
970         assert_eq!(parcel.read::<u32>().unwrap(), 1);
971         unsafe {
972             assert!(parcel.set_data_position(start).is_ok());
973         }
974 
975         let vec = Vec::<bool>::deserialize(parcel.borrowed_ref()).unwrap();
976 
977         assert_eq!(vec, [true, false, false, true]);
978 
979         let u8s = [101u8, 255, 42, 117];
980 
981         let mut parcel = Parcel::new();
982         let start = parcel.get_data_position();
983 
984         assert!(parcel.write(&u8s[..]).is_ok());
985 
986         unsafe {
987             assert!(parcel.set_data_position(start).is_ok());
988         }
989 
990         assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
991         assert_eq!(parcel.read::<u32>().unwrap(), 0x752aff65); // bytes
992         unsafe {
993             assert!(parcel.set_data_position(start).is_ok());
994         }
995 
996         let vec = Vec::<u8>::deserialize(parcel.borrowed_ref()).unwrap();
997         assert_eq!(vec, [101, 255, 42, 117]);
998 
999         let i8s = [-128i8, 127, 42, -117];
1000 
1001         unsafe {
1002             assert!(parcel.set_data_position(start).is_ok());
1003         }
1004 
1005         assert!(parcel.write(&i8s[..]).is_ok());
1006 
1007         unsafe {
1008             assert!(parcel.set_data_position(start).is_ok());
1009         }
1010 
1011         assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1012         assert_eq!(parcel.read::<u32>().unwrap(), 0x8b2a7f80); // bytes
1013         unsafe {
1014             assert!(parcel.set_data_position(start).is_ok());
1015         }
1016 
1017         let vec = Vec::<u8>::deserialize(parcel.borrowed_ref()).unwrap();
1018         assert_eq!(vec, [-128i8 as u8, 127, 42, -117i8 as u8]);
1019 
1020         let u16s = [u16::max_value(), 12_345, 42, 117];
1021 
1022         unsafe {
1023             assert!(parcel.set_data_position(start).is_ok());
1024         }
1025         assert!(u16s.serialize(&mut parcel.borrowed()).is_ok());
1026         unsafe {
1027             assert!(parcel.set_data_position(start).is_ok());
1028         }
1029 
1030         assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1031         assert_eq!(parcel.read::<u32>().unwrap(), 0xffff); // u16::max_value()
1032         assert_eq!(parcel.read::<u32>().unwrap(), 12345); // 12,345
1033         assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1034         assert_eq!(parcel.read::<u32>().unwrap(), 117); // 117
1035         unsafe {
1036             assert!(parcel.set_data_position(start).is_ok());
1037         }
1038 
1039         let vec = Vec::<u16>::deserialize(parcel.borrowed_ref()).unwrap();
1040 
1041         assert_eq!(vec, [u16::max_value(), 12_345, 42, 117]);
1042 
1043         let i16s = [i16::max_value(), i16::min_value(), 42, -117];
1044 
1045         unsafe {
1046             assert!(parcel.set_data_position(start).is_ok());
1047         }
1048         assert!(i16s.serialize(&mut parcel.borrowed()).is_ok());
1049         unsafe {
1050             assert!(parcel.set_data_position(start).is_ok());
1051         }
1052 
1053         assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1054         assert_eq!(parcel.read::<u32>().unwrap(), 0x7fff); // i16::max_value()
1055         assert_eq!(parcel.read::<u32>().unwrap(), 0x8000); // i16::min_value()
1056         assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1057         assert_eq!(parcel.read::<u32>().unwrap(), 0xff8b); // -117
1058         unsafe {
1059             assert!(parcel.set_data_position(start).is_ok());
1060         }
1061 
1062         let vec = Vec::<i16>::deserialize(parcel.borrowed_ref()).unwrap();
1063 
1064         assert_eq!(vec, [i16::max_value(), i16::min_value(), 42, -117]);
1065 
1066         let u32s = [u32::max_value(), 12_345, 42, 117];
1067 
1068         unsafe {
1069             assert!(parcel.set_data_position(start).is_ok());
1070         }
1071         assert!(u32s.serialize(&mut parcel.borrowed()).is_ok());
1072         unsafe {
1073             assert!(parcel.set_data_position(start).is_ok());
1074         }
1075 
1076         assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1077         assert_eq!(parcel.read::<u32>().unwrap(), 0xffffffff); // u32::max_value()
1078         assert_eq!(parcel.read::<u32>().unwrap(), 12345); // 12,345
1079         assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1080         assert_eq!(parcel.read::<u32>().unwrap(), 117); // 117
1081         unsafe {
1082             assert!(parcel.set_data_position(start).is_ok());
1083         }
1084 
1085         let vec = Vec::<u32>::deserialize(parcel.borrowed_ref()).unwrap();
1086 
1087         assert_eq!(vec, [u32::max_value(), 12_345, 42, 117]);
1088 
1089         let i32s = [i32::max_value(), i32::min_value(), 42, -117];
1090 
1091         unsafe {
1092             assert!(parcel.set_data_position(start).is_ok());
1093         }
1094         assert!(i32s.serialize(&mut parcel.borrowed()).is_ok());
1095         unsafe {
1096             assert!(parcel.set_data_position(start).is_ok());
1097         }
1098 
1099         assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1100         assert_eq!(parcel.read::<u32>().unwrap(), 0x7fffffff); // i32::max_value()
1101         assert_eq!(parcel.read::<u32>().unwrap(), 0x80000000); // i32::min_value()
1102         assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1103         assert_eq!(parcel.read::<u32>().unwrap(), 0xffffff8b); // -117
1104         unsafe {
1105             assert!(parcel.set_data_position(start).is_ok());
1106         }
1107 
1108         let vec = Vec::<i32>::deserialize(parcel.borrowed_ref()).unwrap();
1109 
1110         assert_eq!(vec, [i32::max_value(), i32::min_value(), 42, -117]);
1111 
1112         let u64s = [u64::max_value(), 12_345, 42, 117];
1113 
1114         unsafe {
1115             assert!(parcel.set_data_position(start).is_ok());
1116         }
1117         assert!(u64s.serialize(&mut parcel.borrowed()).is_ok());
1118         unsafe {
1119             assert!(parcel.set_data_position(start).is_ok());
1120         }
1121 
1122         let vec = Vec::<u64>::deserialize(parcel.borrowed_ref()).unwrap();
1123 
1124         assert_eq!(vec, [u64::max_value(), 12_345, 42, 117]);
1125 
1126         let i64s = [i64::max_value(), i64::min_value(), 42, -117];
1127 
1128         unsafe {
1129             assert!(parcel.set_data_position(start).is_ok());
1130         }
1131         assert!(i64s.serialize(&mut parcel.borrowed()).is_ok());
1132         unsafe {
1133             assert!(parcel.set_data_position(start).is_ok());
1134         }
1135 
1136         let vec = Vec::<i64>::deserialize(parcel.borrowed_ref()).unwrap();
1137 
1138         assert_eq!(vec, [i64::max_value(), i64::min_value(), 42, -117]);
1139 
1140         let f32s = [std::f32::NAN, std::f32::INFINITY, 1.23456789, std::f32::EPSILON];
1141 
1142         unsafe {
1143             assert!(parcel.set_data_position(start).is_ok());
1144         }
1145         assert!(f32s.serialize(&mut parcel.borrowed()).is_ok());
1146         unsafe {
1147             assert!(parcel.set_data_position(start).is_ok());
1148         }
1149 
1150         let vec = Vec::<f32>::deserialize(parcel.borrowed_ref()).unwrap();
1151 
1152         // NAN != NAN so we can't use it in the assert_eq:
1153         assert!(vec[0].is_nan());
1154         assert_eq!(vec[1..], f32s[1..]);
1155 
1156         let f64s = [std::f64::NAN, std::f64::INFINITY, 1.234567890123456789, std::f64::EPSILON];
1157 
1158         unsafe {
1159             assert!(parcel.set_data_position(start).is_ok());
1160         }
1161         assert!(f64s.serialize(&mut parcel.borrowed()).is_ok());
1162         unsafe {
1163             assert!(parcel.set_data_position(start).is_ok());
1164         }
1165 
1166         let vec = Vec::<f64>::deserialize(parcel.borrowed_ref()).unwrap();
1167 
1168         // NAN != NAN so we can't use it in the assert_eq:
1169         assert!(vec[0].is_nan());
1170         assert_eq!(vec[1..], f64s[1..]);
1171 
1172         let s1 = "Hello, Binder!";
1173         let s2 = "This is a utf8 string.";
1174         let s3 = "Some more text here.";
1175         let s4 = "Embedded nulls \0 \0";
1176 
1177         let strs = [s1, s2, s3, s4];
1178 
1179         unsafe {
1180             assert!(parcel.set_data_position(start).is_ok());
1181         }
1182         assert!(strs.serialize(&mut parcel.borrowed()).is_ok());
1183         unsafe {
1184             assert!(parcel.set_data_position(start).is_ok());
1185         }
1186 
1187         let vec = Vec::<String>::deserialize(parcel.borrowed_ref()).unwrap();
1188 
1189         assert_eq!(vec, strs);
1190     }
1191 }
1192