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