binder/parcel/
parcelable.rs

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
17use crate::binder::{AsNative, FromIBinder, Interface, Stability, Strong};
18use crate::error::{status_result, status_t, Result, Status, StatusCode};
19use crate::parcel::BorrowedParcel;
20use crate::proxy::SpIBinder;
21use crate::sys;
22
23use std::convert::{TryFrom, TryInto};
24use std::ffi::c_void;
25use std::mem::{self, ManuallyDrop};
26use std::os::raw::c_char;
27use std::ptr;
28use std::slice;
29
30/// Super-trait for structured Binder parcelables, i.e. those generated from AIDL.
31///
32/// This trait is equivalent `android::Parcelable` in C++,
33/// and defines a common interface that all parcelables need
34/// to implement.
35pub 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.
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.
50    fn read_from_parcel(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()>;
51}
52
53/// Super-trait for unstructured Binder parcelables, i.e. those implemented manually.
54///
55/// These differ from structured parcelables in that they may not have a reasonable default value
56/// and so aren't required to implement `Default`.
57pub trait UnstructuredParcelable: Sized {
58    /// Internal serialization function for parcelables.
59    ///
60    /// This method is mainly for internal use. `Serialize::serialize` and its variants are
61    /// generally preferred over calling this function, since the former also prepend a header.
62    fn write_to_parcel(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
63
64    /// Internal deserialization function for parcelables.
65    ///
66    /// This method is mainly for internal use. `Deserialize::deserialize` and its variants are
67    /// generally preferred over calling this function, since the former also parse the additional
68    /// header.
69    fn from_parcel(parcel: &BorrowedParcel<'_>) -> Result<Self>;
70
71    /// Internal deserialization function for parcelables.
72    ///
73    /// This method is mainly for internal use. `Deserialize::deserialize_from` and its variants are
74    /// generally preferred over calling this function, since the former also parse the additional
75    /// header.
76    fn read_from_parcel(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
77        *self = Self::from_parcel(parcel)?;
78        Ok(())
79    }
80}
81
82/// A struct whose instances can be written to a [`crate::parcel::Parcel`].
83// Might be able to hook this up as a serde backend in the future?
84pub trait Serialize {
85    /// Serialize this instance into the given [`crate::parcel::Parcel`].
86    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
87}
88
89/// A struct whose instances can be restored from a [`crate::parcel::Parcel`].
90// Might be able to hook this up as a serde backend in the future?
91pub trait Deserialize: Sized {
92    /// Type for the uninitialized value of this type. Will be either `Self`
93    /// if the type implements `Default`, `Option<Self>` otherwise.
94    type UninitType;
95
96    /// Assert at compile-time that `Self` and `Self::UninitType` have the same
97    /// size and alignment. This will either fail to compile or evaluate to `true`.
98    /// The only two macros that work here are `panic!` and `assert!`, so we cannot
99    /// use `assert_eq!`.
100    const ASSERT_UNINIT_SIZE_AND_ALIGNMENT: bool = {
101        assert!(std::mem::size_of::<Self>() == std::mem::size_of::<Self::UninitType>());
102        assert!(std::mem::align_of::<Self>() == std::mem::align_of::<Self::UninitType>());
103        true
104    };
105
106    /// Return an uninitialized or default-initialized value for this type.
107    fn uninit() -> Self::UninitType;
108
109    /// Convert an initialized value of type `Self` into `Self::UninitType`.
110    fn from_init(value: Self) -> Self::UninitType;
111
112    /// Deserialize an instance from the given [`crate::parcel::Parcel`].
113    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>;
114
115    /// Deserialize an instance from the given [`crate::parcel::Parcel`] onto the
116    /// current object. This operation will overwrite the old value
117    /// partially or completely, depending on how much data is available.
118    fn deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
119        *self = Self::deserialize(parcel)?;
120        Ok(())
121    }
122}
123
124/// Helper trait for types that can be serialized as arrays.
125/// Defaults to calling Serialize::serialize() manually for every element,
126/// but can be overridden for custom implementations like `writeByteArray`.
127// Until specialization is stabilized in Rust, we need this to be a separate
128// trait because it's the only way to have a default implementation for a method.
129// We want the default implementation for most types, but an override for
130// a few special ones like `readByteArray` for `u8`.
131pub trait SerializeArray: Serialize + Sized {
132    /// Serialize an array of this type into the given parcel.
133    fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
134        // Safety: Safe FFI, slice will always be a safe pointer to pass.
135        let res = unsafe {
136            sys::AParcel_writeParcelableArray(
137                parcel.as_native_mut(),
138                slice.as_ptr() as *const c_void,
139                slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
140                Some(serialize_element::<Self>),
141            )
142        };
143        status_result(res)
144    }
145}
146
147/// Callback to serialize an element of a generic parcelable array.
148///
149/// # Safety
150///
151/// We are relying on binder_ndk to not overrun our slice. As long as it
152/// doesn't provide an index larger than the length of the original slice in
153/// serialize_array, this operation is safe. The index provided is zero-based.
154unsafe extern "C" fn serialize_element<T: Serialize>(
155    parcel: *mut sys::AParcel,
156    array: *const c_void,
157    index: usize,
158) -> status_t {
159    // Safety: The caller guarantees that `array` is a valid pointer of the
160    // appropriate type.
161    let slice: &[T] = unsafe { slice::from_raw_parts(array.cast(), index + 1) };
162
163    // Safety: The caller must give us a parcel pointer which is either null or
164    // valid at least for the duration of this function call. We don't keep the
165    // resulting value beyond the function.
166    let mut parcel = match unsafe { BorrowedParcel::from_raw(parcel) } {
167        None => return StatusCode::UNEXPECTED_NULL as status_t,
168        Some(p) => p,
169    };
170
171    slice[index].serialize(&mut parcel).err().unwrap_or(StatusCode::OK) as status_t
172}
173
174/// Helper trait for types that can be deserialized as arrays.
175/// Defaults to calling Deserialize::deserialize() manually for every element,
176/// but can be overridden for custom implementations like `readByteArray`.
177pub trait DeserializeArray: Deserialize {
178    /// Deserialize an array of type from the given parcel.
179    fn deserialize_array(parcel: &BorrowedParcel<'_>) -> Result<Option<Vec<Self>>> {
180        let mut vec: Option<Vec<Self::UninitType>> = None;
181        // Safety: Safe FFI, vec is the correct opaque type expected by
182        // allocate_vec and deserialize_element.
183        let res = unsafe {
184            sys::AParcel_readParcelableArray(
185                parcel.as_native(),
186                &mut vec as *mut _ as *mut c_void,
187                Some(allocate_vec::<Self>),
188                Some(deserialize_element::<Self>),
189            )
190        };
191        status_result(res)?;
192        // Safety: We are assuming that the NDK correctly initialized every
193        // element of the vector by now, so we know that all the
194        // UninitTypes are now properly initialized. We can transmute from
195        // Vec<T::UninitType> to Vec<T> because T::UninitType has the same
196        // alignment and size as T, so the pointer to the vector allocation
197        // will be compatible.
198        let vec: Option<Vec<Self>> = unsafe { mem::transmute(vec) };
199        Ok(vec)
200    }
201}
202
203/// Callback to deserialize a parcelable element.
204///
205/// # Safety
206///
207/// The opaque array data pointer must be a mutable pointer to an
208/// `Option<Vec<T::UninitType>>` with at least enough elements for `index` to be valid
209/// (zero-based).
210unsafe extern "C" fn deserialize_element<T: Deserialize>(
211    parcel: *const sys::AParcel,
212    array: *mut c_void,
213    index: usize,
214) -> status_t {
215    // Safety: The caller guarantees that `array` is a valid pointer of the
216    // appropriate type.
217    let vec = unsafe { &mut *(array as *mut Option<Vec<T::UninitType>>) };
218    let vec = match vec {
219        Some(v) => v,
220        None => return StatusCode::BAD_INDEX as status_t,
221    };
222
223    // Safety: The caller must give us a parcel pointer which is either null or
224    // valid at least for the duration of this function call. We don't keep the
225    // resulting value beyond the function.
226    let parcel = match unsafe { BorrowedParcel::from_raw(parcel as *mut _) } {
227        None => return StatusCode::UNEXPECTED_NULL as status_t,
228        Some(p) => p,
229    };
230    let element = match parcel.read() {
231        Ok(e) => e,
232        Err(code) => return code as status_t,
233    };
234    vec[index] = T::from_init(element);
235    StatusCode::OK as status_t
236}
237
238/// Flag that specifies that the following parcelable is present.
239///
240/// This is the Rust equivalent of `Parcel::kNonNullParcelableFlag`
241/// from `include/binder/Parcel.h` in C++.
242pub const NON_NULL_PARCELABLE_FLAG: i32 = 1;
243
244/// Flag that specifies that the following parcelable is absent.
245///
246/// This is the Rust equivalent of `Parcel::kNullParcelableFlag`
247/// from `include/binder/Parcel.h` in C++.
248pub const NULL_PARCELABLE_FLAG: i32 = 0;
249
250/// Helper trait for types that can be nullable when serialized.
251// We really need this trait instead of implementing `Serialize for Option<T>`
252// because of the Rust orphan rule which prevents us from doing
253// `impl Serialize for Option<&dyn IFoo>` for AIDL interfaces.
254// Instead we emit `impl SerializeOption for dyn IFoo` which is allowed.
255// We also use it to provide a default implementation for AIDL-generated
256// parcelables.
257pub trait SerializeOption: Serialize {
258    /// Serialize an Option of this type into the given parcel.
259    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
260        if let Some(inner) = this {
261            parcel.write(&NON_NULL_PARCELABLE_FLAG)?;
262            parcel.write(inner)
263        } else {
264            parcel.write(&NULL_PARCELABLE_FLAG)
265        }
266    }
267}
268
269/// Helper trait for types that can be nullable when deserialized.
270pub trait DeserializeOption: Deserialize {
271    /// Deserialize an Option of this type from the given parcel.
272    fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
273        let null: i32 = parcel.read()?;
274        if null == NULL_PARCELABLE_FLAG {
275            Ok(None)
276        } else {
277            parcel.read().map(Some)
278        }
279    }
280
281    /// Deserialize an Option of this type from the given parcel onto the
282    /// current object. This operation will overwrite the current value
283    /// partially or completely, depending on how much data is available.
284    fn deserialize_option_from(this: &mut Option<Self>, parcel: &BorrowedParcel<'_>) -> Result<()> {
285        *this = Self::deserialize_option(parcel)?;
286        Ok(())
287    }
288}
289
290/// Callback to allocate a vector for parcel array read functions.
291///
292/// This variant is for APIs which use an out buffer pointer.
293///
294/// # Safety
295///
296/// The opaque data pointer passed to the array read function must be a mutable
297/// pointer to an `Option<Vec<T::UninitType>>`. `buffer` will be assigned a mutable pointer
298/// to the allocated vector data if this function returns true. `buffer` must be a valid pointer.
299unsafe extern "C" fn allocate_vec_with_buffer<T: Deserialize>(
300    data: *mut c_void,
301    len: i32,
302    buffer: *mut *mut T,
303) -> bool {
304    // Safety: We have the same safety requirements as `allocate_vec` for `data`.
305    let res = unsafe { allocate_vec::<T>(data, len) };
306    // Safety: The caller guarantees that `data` is a valid mutable pointer to the appropriate type.
307    let vec = unsafe { &mut *(data as *mut Option<Vec<T::UninitType>>) };
308    if let Some(new_vec) = vec {
309        // Safety: The caller guarantees that `buffer` is a valid pointer.
310        unsafe {
311            *buffer = new_vec.as_mut_ptr() as *mut T;
312        }
313    }
314    res
315}
316
317/// Callback to allocate a vector for parcel array read functions.
318///
319/// # Safety
320///
321/// The opaque data pointer passed to the array read function must be a mutable
322/// pointer to an `Option<Vec<T::UninitType>>`.
323unsafe extern "C" fn allocate_vec<T: Deserialize>(data: *mut c_void, len: i32) -> bool {
324    // Safety: The caller guarantees that `data` is a valid mutable pointer to the appropriate type.
325    let vec = unsafe { &mut *(data as *mut Option<Vec<T::UninitType>>) };
326    if len < 0 {
327        *vec = None;
328        return true;
329    }
330
331    // Assert at compile time that `T` and `T::UninitType` have the same size and alignment.
332    let _ = T::ASSERT_UNINIT_SIZE_AND_ALIGNMENT;
333    let mut new_vec: Vec<T::UninitType> = Vec::with_capacity(len as usize);
334    new_vec.resize_with(len as usize, T::uninit);
335
336    // Safety: The caller guarantees that vec is a valid mutable pointer to the appropriate type.
337    unsafe {
338        ptr::write(vec, Some(new_vec));
339    }
340    true
341}
342
343macro_rules! parcelable_primitives {
344    {
345        $(
346            impl $trait:ident for $ty:ty = $fn:path;
347        )*
348    } => {
349        $(impl_parcelable!{$trait, $ty, $fn})*
350    };
351}
352
353/// Safety: All elements in the vector must be properly initialized.
354unsafe fn vec_assume_init<T: Deserialize>(vec: Vec<T::UninitType>) -> Vec<T> {
355    // Assert at compile time that `T` and `T::UninitType` have the same size and alignment.
356    let _ = T::ASSERT_UNINIT_SIZE_AND_ALIGNMENT;
357
358    let mut vec = ManuallyDrop::new(vec);
359    // Safety: We can convert from Vec<T::UninitType> to Vec<T> because
360    // T::UninitType has the same alignment and size as T, so the pointer to the
361    // vector allocation will be compatible.
362    unsafe { Vec::from_raw_parts(vec.as_mut_ptr().cast(), vec.len(), vec.capacity()) }
363}
364
365macro_rules! impl_parcelable {
366    {Serialize, $ty:ty, $write_fn:path} => {
367        impl Serialize for $ty {
368            fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
369                // Safety: `Parcel` always contains a valid pointer to an
370                // `AParcel`, and any `$ty` literal value is safe to pass to
371                // `$write_fn`.
372                unsafe {
373                    status_result($write_fn(parcel.as_native_mut(), *self))
374                }
375            }
376        }
377    };
378
379    {Deserialize, $ty:ty, $read_fn:path} => {
380        impl Deserialize for $ty {
381            type UninitType = Self;
382            fn uninit() -> Self::UninitType { Self::UninitType::default() }
383            fn from_init(value: Self) -> Self::UninitType { value }
384            fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
385                let mut val = Self::default();
386                // Safety: `Parcel` always contains a valid pointer to an
387                // `AParcel`. We pass a valid, mutable pointer to `val`, a
388                // literal of type `$ty`, and `$read_fn` will write the
389                // value read into `val` if successful
390                unsafe {
391                    status_result($read_fn(parcel.as_native(), &mut val))?
392                };
393                Ok(val)
394            }
395        }
396    };
397
398    {SerializeArray, $ty:ty, $write_array_fn:path} => {
399        impl SerializeArray for $ty {
400            fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
401                // Safety: `Parcel` always contains a valid pointer to an
402                // `AParcel`. If the slice is > 0 length, `slice.as_ptr()`
403                // will be a valid pointer to an array of elements of type
404                // `$ty`. If the slice length is 0, `slice.as_ptr()` may be
405                // dangling, but this is safe since the pointer is not
406                // dereferenced if the length parameter is 0.
407                let status = unsafe {
408                    $write_array_fn(
409                        parcel.as_native_mut(),
410                        slice.as_ptr(),
411                        slice
412                            .len()
413                            .try_into()
414                            .or(Err(StatusCode::BAD_VALUE))?,
415                    )
416                };
417                status_result(status)
418            }
419        }
420    };
421
422    {DeserializeArray, $ty:ty, $read_array_fn:path} => {
423        impl DeserializeArray for $ty {
424            fn deserialize_array(parcel: &BorrowedParcel<'_>) -> Result<Option<Vec<Self>>> {
425                let mut vec: Option<Vec<Self::UninitType>> = None;
426                // Safety: `Parcel` always contains a valid pointer to an
427                // `AParcel`. `allocate_vec<T>` expects the opaque pointer to
428                // be of type `*mut Option<Vec<T::UninitType>>`, so `&mut vec` is
429                // correct for it.
430                let status = unsafe {
431                    $read_array_fn(
432                        parcel.as_native(),
433                        &mut vec as *mut _ as *mut c_void,
434                        Some(allocate_vec_with_buffer),
435                    )
436                };
437                status_result(status)?;
438                // Safety: We are assuming that the NDK correctly
439                // initialized every element of the vector by now, so we
440                // know that all the UninitTypes are now properly
441                // initialized.
442                let vec: Option<Vec<Self>> = unsafe {
443                    vec.map(|vec| vec_assume_init(vec))
444                };
445                Ok(vec)
446            }
447        }
448    };
449}
450
451impl<T: DeserializeOption> DeserializeArray for Option<T> {}
452impl<T: SerializeOption> SerializeArray for Option<T> {}
453
454parcelable_primitives! {
455    impl Serialize for bool = sys::AParcel_writeBool;
456    impl Deserialize for bool = sys::AParcel_readBool;
457
458    // This is only safe because `Option<Vec<u8>>` is interchangeable with
459    // `Option<Vec<i8>>` (what the allocator function actually allocates.
460    impl DeserializeArray for u8 = sys::AParcel_readByteArray;
461
462    impl Serialize for i8 = sys::AParcel_writeByte;
463    impl Deserialize for i8 = sys::AParcel_readByte;
464    impl SerializeArray for i8 = sys::AParcel_writeByteArray;
465    impl DeserializeArray for i8 = sys::AParcel_readByteArray;
466
467    impl Serialize for u16 = sys::AParcel_writeChar;
468    impl Deserialize for u16 = sys::AParcel_readChar;
469    impl SerializeArray for u16 = sys::AParcel_writeCharArray;
470    impl DeserializeArray for u16 = sys::AParcel_readCharArray;
471
472    // This is only safe because `Option<Vec<i16>>` is interchangeable with
473    // `Option<Vec<u16>>` (what the allocator function actually allocates.
474    impl DeserializeArray for i16 = sys::AParcel_readCharArray;
475
476    impl Serialize for u32 = sys::AParcel_writeUint32;
477    impl Deserialize for u32 = sys::AParcel_readUint32;
478    impl SerializeArray for u32 = sys::AParcel_writeUint32Array;
479    impl DeserializeArray for u32 = sys::AParcel_readUint32Array;
480
481    impl Serialize for i32 = sys::AParcel_writeInt32;
482    impl Deserialize for i32 = sys::AParcel_readInt32;
483    impl SerializeArray for i32 = sys::AParcel_writeInt32Array;
484    impl DeserializeArray for i32 = sys::AParcel_readInt32Array;
485
486    impl Serialize for u64 = sys::AParcel_writeUint64;
487    impl Deserialize for u64 = sys::AParcel_readUint64;
488    impl SerializeArray for u64 = sys::AParcel_writeUint64Array;
489    impl DeserializeArray for u64 = sys::AParcel_readUint64Array;
490
491    impl Serialize for i64 = sys::AParcel_writeInt64;
492    impl Deserialize for i64 = sys::AParcel_readInt64;
493    impl SerializeArray for i64 = sys::AParcel_writeInt64Array;
494    impl DeserializeArray for i64 = sys::AParcel_readInt64Array;
495
496    impl Serialize for f32 = sys::AParcel_writeFloat;
497    impl Deserialize for f32 = sys::AParcel_readFloat;
498    impl SerializeArray for f32 = sys::AParcel_writeFloatArray;
499    impl DeserializeArray for f32 = sys::AParcel_readFloatArray;
500
501    impl Serialize for f64 = sys::AParcel_writeDouble;
502    impl Deserialize for f64 = sys::AParcel_readDouble;
503    impl SerializeArray for f64 = sys::AParcel_writeDoubleArray;
504    impl DeserializeArray for f64 = sys::AParcel_readDoubleArray;
505}
506
507impl SerializeArray for bool {}
508impl DeserializeArray for bool {}
509
510impl Serialize for u8 {
511    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
512        (*self as i8).serialize(parcel)
513    }
514}
515
516impl Deserialize for u8 {
517    type UninitType = Self;
518    fn uninit() -> Self::UninitType {
519        Self::UninitType::default()
520    }
521    fn from_init(value: Self) -> Self::UninitType {
522        value
523    }
524
525    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
526        i8::deserialize(parcel).map(|v| v as u8)
527    }
528}
529
530impl SerializeArray for u8 {
531    fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
532        // Safety: `Parcel` always contains a valid pointer to an
533        // `AParcel`. If the slice is > 0 length, `slice.as_ptr()` will be a
534        // valid pointer to an array of elements of type `$ty`. If the slice
535        // length is 0, `slice.as_ptr()` may be dangling, but this is safe
536        // since the pointer is not dereferenced if the length parameter is
537        // 0.
538        let status = unsafe {
539            sys::AParcel_writeByteArray(
540                parcel.as_native_mut(),
541                slice.as_ptr() as *const i8,
542                slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
543            )
544        };
545        status_result(status)
546    }
547}
548
549impl Serialize for i16 {
550    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
551        (*self as u16).serialize(parcel)
552    }
553}
554
555impl Deserialize for i16 {
556    type UninitType = Self;
557    fn uninit() -> Self::UninitType {
558        Self::UninitType::default()
559    }
560    fn from_init(value: Self) -> Self::UninitType {
561        value
562    }
563
564    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
565        u16::deserialize(parcel).map(|v| v as i16)
566    }
567}
568
569impl SerializeArray for i16 {
570    fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
571        // Safety: `Parcel` always contains a valid pointer to an
572        // `AParcel`. If the slice is > 0 length, `slice.as_ptr()` will be a
573        // valid pointer to an array of elements of type `$ty`. If the slice
574        // length is 0, `slice.as_ptr()` may be dangling, but this is safe
575        // since the pointer is not dereferenced if the length parameter is
576        // 0.
577        let status = unsafe {
578            sys::AParcel_writeCharArray(
579                parcel.as_native_mut(),
580                slice.as_ptr() as *const u16,
581                slice.len().try_into().or(Err(StatusCode::BAD_VALUE))?,
582            )
583        };
584        status_result(status)
585    }
586}
587
588impl SerializeOption for str {
589    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
590        match this {
591            // Safety: `Parcel` always contains a valid pointer to an
592            // `AParcel`. If the string pointer is null,
593            // `AParcel_writeString` requires that the length is -1 to
594            // indicate that we want to serialize a null string.
595            None => unsafe {
596                status_result(sys::AParcel_writeString(parcel.as_native_mut(), ptr::null(), -1))
597            },
598            // Safety: `Parcel` always contains a valid pointer to an
599            // `AParcel`. `AParcel_writeString` assumes that we pass a utf-8
600            // string pointer of `length` bytes, which is what str in Rust
601            // is. The docstring for `AParcel_writeString` says that the
602            // string input should be null-terminated, but it doesn't
603            // actually rely on that fact in the code. If this ever becomes
604            // necessary, we will need to null-terminate the str buffer
605            // before sending it.
606            Some(s) => unsafe {
607                status_result(sys::AParcel_writeString(
608                    parcel.as_native_mut(),
609                    s.as_ptr() as *const c_char,
610                    s.as_bytes().len().try_into().or(Err(StatusCode::BAD_VALUE))?,
611                ))
612            },
613        }
614    }
615}
616
617impl Serialize for str {
618    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
619        Some(self).serialize(parcel)
620    }
621}
622
623impl SerializeArray for &str {}
624
625impl Serialize for String {
626    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
627        Some(self.as_str()).serialize(parcel)
628    }
629}
630
631impl SerializeArray for String {}
632
633impl SerializeOption for String {
634    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
635        SerializeOption::serialize_option(this.map(String::as_str), parcel)
636    }
637}
638
639impl Deserialize for Option<String> {
640    type UninitType = Self;
641    fn uninit() -> Self::UninitType {
642        Self::UninitType::default()
643    }
644    fn from_init(value: Self) -> Self::UninitType {
645        value
646    }
647
648    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
649        let mut vec: Option<Vec<u8>> = None;
650        // Safety: `Parcel` always contains a valid pointer to an `AParcel`.
651        // `Option<Vec<u8>>` is equivalent to the expected `Option<Vec<i8>>`
652        // for `allocate_vec`, so `vec` is safe to pass as the opaque data
653        // pointer on platforms where char is signed.
654        let status = unsafe {
655            sys::AParcel_readString(
656                parcel.as_native(),
657                &mut vec as *mut _ as *mut c_void,
658                Some(allocate_vec_with_buffer),
659            )
660        };
661
662        status_result(status)?;
663        vec.map(|mut s| {
664            // The vector includes a null-terminator and we don't want the
665            // string to be null-terminated for Rust.
666            s.pop();
667            String::from_utf8(s).or(Err(StatusCode::BAD_VALUE))
668        })
669        .transpose()
670    }
671}
672
673impl DeserializeArray for Option<String> {}
674
675impl Deserialize for String {
676    type UninitType = Self;
677    fn uninit() -> Self::UninitType {
678        Self::UninitType::default()
679    }
680    fn from_init(value: Self) -> Self::UninitType {
681        value
682    }
683
684    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
685        Deserialize::deserialize(parcel).transpose().unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
686    }
687}
688
689impl DeserializeArray for String {}
690
691impl<T: SerializeArray> Serialize for [T] {
692    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
693        SerializeArray::serialize_array(self, parcel)
694    }
695}
696
697impl<T: SerializeArray> Serialize for Vec<T> {
698    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
699        SerializeArray::serialize_array(&self[..], parcel)
700    }
701}
702
703impl<T: SerializeArray> SerializeOption for [T] {
704    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
705        if let Some(v) = this {
706            SerializeArray::serialize_array(v, parcel)
707        } else {
708            parcel.write(&-1i32)
709        }
710    }
711}
712
713impl<T: SerializeArray> SerializeOption for Vec<T> {
714    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
715        SerializeOption::serialize_option(this.map(Vec::as_slice), parcel)
716    }
717}
718
719impl<T: DeserializeArray> Deserialize for Vec<T> {
720    type UninitType = Self;
721    fn uninit() -> Self::UninitType {
722        Self::UninitType::default()
723    }
724    fn from_init(value: Self) -> Self::UninitType {
725        value
726    }
727
728    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
729        DeserializeArray::deserialize_array(parcel)
730            .transpose()
731            .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))
732    }
733}
734
735impl<T: DeserializeArray> DeserializeOption for Vec<T> {
736    fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
737        DeserializeArray::deserialize_array(parcel)
738    }
739}
740
741impl<T: SerializeArray, const N: usize> Serialize for [T; N] {
742    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
743        // forwards to T::serialize_array.
744        SerializeArray::serialize_array(self, parcel)
745    }
746}
747
748impl<T: SerializeArray, const N: usize> SerializeOption for [T; N] {
749    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
750        SerializeOption::serialize_option(this.map(|arr| &arr[..]), parcel)
751    }
752}
753
754impl<T: SerializeArray, const N: usize> SerializeArray for [T; N] {}
755
756impl<T: DeserializeArray, const N: usize> Deserialize for [T; N] {
757    type UninitType = [T::UninitType; N];
758    fn uninit() -> Self::UninitType {
759        [(); N].map(|_| T::uninit())
760    }
761    fn from_init(value: Self) -> Self::UninitType {
762        value.map(T::from_init)
763    }
764
765    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
766        let vec = DeserializeArray::deserialize_array(parcel)
767            .transpose()
768            .unwrap_or(Err(StatusCode::UNEXPECTED_NULL))?;
769        vec.try_into().or(Err(StatusCode::BAD_VALUE))
770    }
771}
772
773impl<T: DeserializeArray, const N: usize> DeserializeOption for [T; N] {
774    fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
775        let vec = DeserializeArray::deserialize_array(parcel)?;
776        vec.map(|v| v.try_into().or(Err(StatusCode::BAD_VALUE))).transpose()
777    }
778}
779
780impl<T: DeserializeArray, const N: usize> DeserializeArray for [T; N] {}
781
782impl Serialize for Stability {
783    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
784        i32::from(*self).serialize(parcel)
785    }
786}
787
788impl Deserialize for Stability {
789    type UninitType = Self;
790    fn uninit() -> Self::UninitType {
791        Self::UninitType::default()
792    }
793    fn from_init(value: Self) -> Self::UninitType {
794        value
795    }
796
797    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
798        i32::deserialize(parcel).and_then(Stability::try_from)
799    }
800}
801
802impl Serialize for Status {
803    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
804        // Safety: `Parcel` always contains a valid pointer to an `AParcel`
805        // and `Status` always contains a valid pointer to an `AStatus`, so
806        // both parameters are valid and safe. This call does not take
807        // ownership of either of its parameters.
808        unsafe {
809            status_result(sys::AParcel_writeStatusHeader(parcel.as_native_mut(), self.as_native()))
810        }
811    }
812}
813
814impl Deserialize for Status {
815    type UninitType = Option<Self>;
816    fn uninit() -> Self::UninitType {
817        Self::UninitType::default()
818    }
819    fn from_init(value: Self) -> Self::UninitType {
820        Some(value)
821    }
822
823    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
824        let mut status_ptr = ptr::null_mut();
825        let ret_status =
826        // Safety: `Parcel` always contains a valid pointer to an
827        // `AParcel`. We pass a mutable out pointer which will be
828        // assigned a valid `AStatus` pointer if the function returns
829        // status OK. This function passes ownership of the status
830        // pointer to the caller, if it was assigned.
831            unsafe { sys::AParcel_readStatusHeader(parcel.as_native(), &mut status_ptr) };
832        status_result(ret_status)?;
833        // Safety: At this point, the return status of the read call was ok,
834        // so we know that `status_ptr` is a valid, owned pointer to an
835        // `AStatus`, from which we can safely construct a `Status` object.
836        Ok(unsafe { Status::from_ptr(status_ptr) })
837    }
838}
839
840impl<T: Serialize + FromIBinder + ?Sized> Serialize for Strong<T> {
841    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
842        Serialize::serialize(&**self, parcel)
843    }
844}
845
846impl<T: SerializeOption + FromIBinder + ?Sized> SerializeOption for Strong<T> {
847    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
848        SerializeOption::serialize_option(this.map(|b| &**b), parcel)
849    }
850}
851
852impl<T: Serialize + FromIBinder + ?Sized> SerializeArray for Strong<T> {}
853
854impl<T: FromIBinder + ?Sized> Deserialize for Strong<T> {
855    type UninitType = Option<Strong<T>>;
856    fn uninit() -> Self::UninitType {
857        Self::UninitType::default()
858    }
859    fn from_init(value: Self) -> Self::UninitType {
860        Some(value)
861    }
862
863    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
864        let ibinder: SpIBinder = parcel.read()?;
865        FromIBinder::try_from(ibinder)
866    }
867}
868
869struct AssertIBinder;
870impl Interface for AssertIBinder {}
871impl FromIBinder for AssertIBinder {
872    // This is only needed so we can assert on the size of Strong<AssertIBinder>
873    fn try_from(_: SpIBinder) -> Result<Strong<Self>> {
874        unimplemented!()
875    }
876}
877
878impl<T: FromIBinder + ?Sized> DeserializeOption for Strong<T> {
879    fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
880        let ibinder: Option<SpIBinder> = parcel.read()?;
881        ibinder.map(FromIBinder::try_from).transpose()
882    }
883}
884
885impl<T: FromIBinder + ?Sized> DeserializeArray for Strong<T> {}
886
887// We need these to support Option<&T> for all T
888impl<T: Serialize + ?Sized> Serialize for &T {
889    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
890        Serialize::serialize(*self, parcel)
891    }
892}
893
894impl<T: SerializeOption + ?Sized> SerializeOption for &T {
895    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
896        SerializeOption::serialize_option(this.copied(), parcel)
897    }
898}
899
900impl<T: SerializeOption> Serialize for Option<T> {
901    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
902        SerializeOption::serialize_option(self.as_ref(), parcel)
903    }
904}
905
906impl<T: DeserializeOption> Deserialize for Option<T> {
907    type UninitType = Self;
908    fn uninit() -> Self::UninitType {
909        Self::UninitType::default()
910    }
911    fn from_init(value: Self) -> Self::UninitType {
912        value
913    }
914
915    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
916        DeserializeOption::deserialize_option(parcel)
917    }
918
919    fn deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
920        DeserializeOption::deserialize_option_from(self, parcel)
921    }
922}
923
924/// Implement `Serialize` trait and friends for a parcelable
925///
926/// This is an internal macro used by the AIDL compiler to implement
927/// `Serialize`, `SerializeArray` and `SerializeOption` for
928/// structured parcelables. The target type must implement the
929/// `Parcelable` trait.
930#[macro_export]
931macro_rules! impl_serialize_for_parcelable {
932    ($parcelable:ident) => {
933        $crate::impl_serialize_for_parcelable!($parcelable < >);
934    };
935    ($parcelable:ident < $( $param:ident ),* , >) => {
936        $crate::impl_serialize_for_parcelable!($parcelable < $($param),* >);
937    };
938    ($parcelable:ident < $( $param:ident ),* > ) => {
939        impl < $($param),* > $crate::binder_impl::Serialize for $parcelable < $($param),* > {
940            fn serialize(
941                &self,
942                parcel: &mut $crate::binder_impl::BorrowedParcel<'_>,
943            ) -> std::result::Result<(), $crate::StatusCode> {
944                <Self as $crate::binder_impl::SerializeOption>::serialize_option(Some(self), parcel)
945            }
946        }
947
948        impl < $($param),* > $crate::binder_impl::SerializeArray for $parcelable < $($param),* > {}
949
950        impl < $($param),* > $crate::binder_impl::SerializeOption for $parcelable < $($param),* > {
951            fn serialize_option(
952                this: Option<&Self>,
953                parcel: &mut $crate::binder_impl::BorrowedParcel<'_>,
954            ) -> std::result::Result<(), $crate::StatusCode> {
955                if let Some(this) = this {
956                    use $crate::Parcelable;
957                    parcel.write(&$crate::binder_impl::NON_NULL_PARCELABLE_FLAG)?;
958                    this.write_to_parcel(parcel)
959                } else {
960                    parcel.write(&$crate::binder_impl::NULL_PARCELABLE_FLAG)
961                }
962            }
963        }
964    };
965}
966
967/// Implement `Deserialize` trait and friends for a parcelable
968///
969/// This is an internal macro used by the AIDL compiler to implement
970/// `Deserialize`, `DeserializeArray` and `DeserializeOption` for
971/// structured parcelables. The target type must implement the
972/// `Parcelable` trait.
973#[macro_export]
974macro_rules! impl_deserialize_for_parcelable {
975    ($parcelable:ident) => {
976        $crate::impl_deserialize_for_parcelable!($parcelable < >);
977    };
978    ($parcelable:ident < $( $param:ident ),* , >) => {
979        $crate::impl_deserialize_for_parcelable!($parcelable < $($param),* >);
980    };
981    ($parcelable:ident < $( $param:ident ),* > ) => {
982        impl < $($param: Default),* > $crate::binder_impl::Deserialize for $parcelable < $($param),* > {
983            type UninitType = Self;
984            fn uninit() -> Self::UninitType { Self::UninitType::default() }
985            fn from_init(value: Self) -> Self::UninitType { value }
986            fn deserialize(
987                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
988            ) -> std::result::Result<Self, $crate::StatusCode> {
989                $crate::binder_impl::DeserializeOption::deserialize_option(parcel)
990                    .transpose()
991                    .unwrap_or(Err($crate::StatusCode::UNEXPECTED_NULL))
992            }
993            fn deserialize_from(
994                &mut self,
995                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
996            ) -> std::result::Result<(), $crate::StatusCode> {
997                let status: i32 = parcel.read()?;
998                if status == $crate::binder_impl::NULL_PARCELABLE_FLAG {
999                    Err($crate::StatusCode::UNEXPECTED_NULL)
1000                } else {
1001                    use $crate::Parcelable;
1002                    self.read_from_parcel(parcel)
1003                }
1004            }
1005        }
1006
1007        impl < $($param: Default),* > $crate::binder_impl::DeserializeArray for $parcelable < $($param),* > {}
1008
1009        impl < $($param: Default),* > $crate::binder_impl::DeserializeOption for $parcelable < $($param),* > {
1010            fn deserialize_option(
1011                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
1012            ) -> std::result::Result<Option<Self>, $crate::StatusCode> {
1013                let mut result = None;
1014                Self::deserialize_option_from(&mut result, parcel)?;
1015                Ok(result)
1016            }
1017            fn deserialize_option_from(
1018                this: &mut Option<Self>,
1019                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
1020            ) -> std::result::Result<(), $crate::StatusCode> {
1021                let status: i32 = parcel.read()?;
1022                if status == $crate::binder_impl::NULL_PARCELABLE_FLAG {
1023                    *this = None;
1024                    Ok(())
1025                } else {
1026                    use $crate::Parcelable;
1027                    this.get_or_insert_with(Self::default).read_from_parcel(parcel)
1028                }
1029            }
1030        }
1031    };
1032}
1033
1034/// Implements `Serialize` trait and friends for an unstructured parcelable.
1035///
1036/// The target type must implement the `UnstructuredParcelable` trait.
1037#[macro_export]
1038macro_rules! impl_serialize_for_unstructured_parcelable {
1039    ($parcelable:ident) => {
1040        $crate::impl_serialize_for_unstructured_parcelable!($parcelable < >);
1041    };
1042    ($parcelable:ident < $( $param:ident ),* , >) => {
1043        $crate::impl_serialize_for_unstructured_parcelable!($parcelable < $($param),* >);
1044    };
1045    ($parcelable:ident < $( $param:ident ),* > ) => {
1046        impl < $($param),* > $crate::binder_impl::Serialize for $parcelable < $($param),* > {
1047            fn serialize(
1048                &self,
1049                parcel: &mut $crate::binder_impl::BorrowedParcel<'_>,
1050            ) -> std::result::Result<(), $crate::StatusCode> {
1051                <Self as $crate::binder_impl::SerializeOption>::serialize_option(Some(self), parcel)
1052            }
1053        }
1054
1055        impl < $($param),* > $crate::binder_impl::SerializeArray for $parcelable < $($param),* > {}
1056
1057        impl < $($param),* > $crate::binder_impl::SerializeOption for $parcelable < $($param),* > {
1058            fn serialize_option(
1059                this: Option<&Self>,
1060                parcel: &mut $crate::binder_impl::BorrowedParcel<'_>,
1061            ) -> std::result::Result<(), $crate::StatusCode> {
1062                if let Some(this) = this {
1063                    use $crate::binder_impl::UnstructuredParcelable;
1064                    parcel.write(&$crate::binder_impl::NON_NULL_PARCELABLE_FLAG)?;
1065                    this.write_to_parcel(parcel)
1066                } else {
1067                    parcel.write(&$crate::binder_impl::NULL_PARCELABLE_FLAG)
1068                }
1069            }
1070        }
1071    };
1072}
1073
1074/// Implement `Deserialize` trait and friends for an unstructured parcelable
1075///
1076/// The target type must implement the `UnstructuredParcelable` trait.
1077#[macro_export]
1078macro_rules! impl_deserialize_for_unstructured_parcelable {
1079    ($parcelable:ident) => {
1080        $crate::impl_deserialize_for_unstructured_parcelable!($parcelable < >);
1081    };
1082    ($parcelable:ident < $( $param:ident ),* , >) => {
1083        $crate::impl_deserialize_for_unstructured_parcelable!($parcelable < $($param),* >);
1084    };
1085    ($parcelable:ident < $( $param:ident ),* > ) => {
1086        impl < $($param: Default),* > $crate::binder_impl::Deserialize for $parcelable < $($param),* > {
1087            type UninitType = Option<Self>;
1088            fn uninit() -> Self::UninitType { None }
1089            fn from_init(value: Self) -> Self::UninitType { Some(value) }
1090            fn deserialize(
1091                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
1092            ) -> std::result::Result<Self, $crate::StatusCode> {
1093                $crate::binder_impl::DeserializeOption::deserialize_option(parcel)
1094                    .transpose()
1095                    .unwrap_or(Err($crate::StatusCode::UNEXPECTED_NULL))
1096            }
1097            fn deserialize_from(
1098                &mut self,
1099                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
1100            ) -> std::result::Result<(), $crate::StatusCode> {
1101                let status: i32 = parcel.read()?;
1102                if status == $crate::binder_impl::NULL_PARCELABLE_FLAG {
1103                    Err($crate::StatusCode::UNEXPECTED_NULL)
1104                } else {
1105                    use $crate::binder_impl::UnstructuredParcelable;
1106                    self.read_from_parcel(parcel)
1107                }
1108            }
1109        }
1110
1111        impl < $($param: Default),* > $crate::binder_impl::DeserializeArray for $parcelable < $($param),* > {}
1112
1113        impl < $($param: Default),* > $crate::binder_impl::DeserializeOption for $parcelable < $($param),* > {
1114            fn deserialize_option(
1115                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
1116            ) -> std::result::Result<Option<Self>, $crate::StatusCode> {
1117                let present: i32 = parcel.read()?;
1118                match present {
1119                    $crate::binder_impl::NULL_PARCELABLE_FLAG => Ok(None),
1120                    $crate::binder_impl::NON_NULL_PARCELABLE_FLAG => {
1121                        use $crate::binder_impl::UnstructuredParcelable;
1122                        Ok(Some(Self::from_parcel(parcel)?))
1123                    }
1124                    _ => Err(StatusCode::BAD_VALUE),
1125                }
1126            }
1127            fn deserialize_option_from(
1128                this: &mut Option<Self>,
1129                parcel: &$crate::binder_impl::BorrowedParcel<'_>,
1130            ) -> std::result::Result<(), $crate::StatusCode> {
1131                let present: i32 = parcel.read()?;
1132                match present {
1133                    $crate::binder_impl::NULL_PARCELABLE_FLAG => {
1134                        *this = None;
1135                        Ok(())
1136                    }
1137                    $crate::binder_impl::NON_NULL_PARCELABLE_FLAG => {
1138                        use $crate::binder_impl::UnstructuredParcelable;
1139                        if let Some(this) = this {
1140                            this.read_from_parcel(parcel)?;
1141                        } else {
1142                            *this = Some(Self::from_parcel(parcel)?);
1143                        }
1144                        Ok(())
1145                    }
1146                    _ => Err(StatusCode::BAD_VALUE),
1147                }
1148            }
1149        }
1150    };
1151}
1152
1153impl<T: Serialize> Serialize for Box<T> {
1154    fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
1155        Serialize::serialize(&**self, parcel)
1156    }
1157}
1158
1159impl<T: Deserialize> Deserialize for Box<T> {
1160    type UninitType = Option<Self>;
1161    fn uninit() -> Self::UninitType {
1162        Self::UninitType::default()
1163    }
1164    fn from_init(value: Self) -> Self::UninitType {
1165        Some(value)
1166    }
1167
1168    fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
1169        Deserialize::deserialize(parcel).map(Box::new)
1170    }
1171}
1172
1173impl<T: SerializeOption> SerializeOption for Box<T> {
1174    fn serialize_option(this: Option<&Self>, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
1175        SerializeOption::serialize_option(this.map(|inner| &**inner), parcel)
1176    }
1177}
1178
1179impl<T: DeserializeOption> DeserializeOption for Box<T> {
1180    fn deserialize_option(parcel: &BorrowedParcel<'_>) -> Result<Option<Self>> {
1181        DeserializeOption::deserialize_option(parcel).map(|t| t.map(Box::new))
1182    }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187    use super::*;
1188    use crate::parcel::Parcel;
1189
1190    #[test]
1191    fn test_custom_parcelable() {
1192        #[derive(Default)]
1193        struct Custom(u32, bool, String, Vec<String>);
1194
1195        impl Serialize for Custom {
1196            fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()> {
1197                self.0.serialize(parcel)?;
1198                self.1.serialize(parcel)?;
1199                self.2.serialize(parcel)?;
1200                self.3.serialize(parcel)
1201            }
1202        }
1203
1204        impl Deserialize for Custom {
1205            type UninitType = Self;
1206            fn uninit() -> Self::UninitType {
1207                Self::UninitType::default()
1208            }
1209            fn from_init(value: Self) -> Self::UninitType {
1210                value
1211            }
1212
1213            fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self> {
1214                Ok(Custom(
1215                    parcel.read()?,
1216                    parcel.read()?,
1217                    parcel.read()?,
1218                    parcel.read::<Option<Vec<String>>>()?.unwrap(),
1219                ))
1220            }
1221        }
1222
1223        let string8 = "Custom Parcelable".to_string();
1224
1225        let s1 = "str1".to_string();
1226        let s2 = "str2".to_string();
1227        let s3 = "str3".to_string();
1228
1229        let strs = vec![s1, s2, s3];
1230
1231        let custom = Custom(123_456_789, true, string8, strs);
1232
1233        let mut parcel = Parcel::new();
1234        let start = parcel.get_data_position();
1235
1236        assert!(custom.serialize(&mut parcel.borrowed()).is_ok());
1237
1238        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1239        // made it any shorter since we got the position.
1240        unsafe {
1241            assert!(parcel.set_data_position(start).is_ok());
1242        }
1243
1244        let custom2 = Custom::deserialize(parcel.borrowed_ref()).unwrap();
1245
1246        assert_eq!(custom2.0, 123_456_789);
1247        assert!(custom2.1);
1248        assert_eq!(custom2.2, custom.2);
1249        assert_eq!(custom2.3, custom.3);
1250    }
1251
1252    #[test]
1253    #[allow(clippy::excessive_precision)]
1254    fn test_slice_parcelables() {
1255        let bools = [true, false, false, true];
1256
1257        let mut parcel = Parcel::new();
1258        let start = parcel.get_data_position();
1259
1260        assert!(bools.serialize(&mut parcel.borrowed()).is_ok());
1261
1262        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1263        // made it any shorter since we got the position.
1264        unsafe {
1265            assert!(parcel.set_data_position(start).is_ok());
1266        }
1267
1268        assert_eq!(parcel.read::<u32>().unwrap(), 4);
1269        assert_eq!(parcel.read::<u32>().unwrap(), 1);
1270        assert_eq!(parcel.read::<u32>().unwrap(), 0);
1271        assert_eq!(parcel.read::<u32>().unwrap(), 0);
1272        assert_eq!(parcel.read::<u32>().unwrap(), 1);
1273        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1274        // made it any shorter since we got the position.
1275        unsafe {
1276            assert!(parcel.set_data_position(start).is_ok());
1277        }
1278
1279        let vec = Vec::<bool>::deserialize(parcel.borrowed_ref()).unwrap();
1280
1281        assert_eq!(vec, [true, false, false, true]);
1282
1283        let u8s = [101u8, 255, 42, 117];
1284
1285        let mut parcel = Parcel::new();
1286        let start = parcel.get_data_position();
1287
1288        assert!(parcel.write(&u8s[..]).is_ok());
1289
1290        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1291        // made it any shorter since we got the position.
1292        unsafe {
1293            assert!(parcel.set_data_position(start).is_ok());
1294        }
1295
1296        assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1297        assert_eq!(parcel.read::<u32>().unwrap(), 0x752aff65); // bytes
1298
1299        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1300        // made it any shorter since we got the position.
1301        unsafe {
1302            assert!(parcel.set_data_position(start).is_ok());
1303        }
1304
1305        let vec = Vec::<u8>::deserialize(parcel.borrowed_ref()).unwrap();
1306        assert_eq!(vec, [101, 255, 42, 117]);
1307
1308        let i8s = [-128i8, 127, 42, -117];
1309
1310        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1311        // made it any shorter since we got the position.
1312        unsafe {
1313            assert!(parcel.set_data_position(start).is_ok());
1314        }
1315
1316        assert!(parcel.write(&i8s[..]).is_ok());
1317
1318        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1319        // made it any shorter since we got the position.
1320        unsafe {
1321            assert!(parcel.set_data_position(start).is_ok());
1322        }
1323
1324        assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1325        assert_eq!(parcel.read::<u32>().unwrap(), 0x8b2a7f80); // bytes
1326
1327        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1328        // made it any shorter since we got the position.
1329        unsafe {
1330            assert!(parcel.set_data_position(start).is_ok());
1331        }
1332
1333        let vec = Vec::<u8>::deserialize(parcel.borrowed_ref()).unwrap();
1334        assert_eq!(vec, [-128i8 as u8, 127, 42, -117i8 as u8]);
1335
1336        let u16s = [u16::MAX, 12_345, 42, 117];
1337
1338        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1339        // made it any shorter since we got the position.
1340        unsafe {
1341            assert!(parcel.set_data_position(start).is_ok());
1342        }
1343        assert!(u16s.serialize(&mut parcel.borrowed()).is_ok());
1344        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1345        // made it any shorter since we got the position.
1346        unsafe {
1347            assert!(parcel.set_data_position(start).is_ok());
1348        }
1349
1350        assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1351        assert_eq!(parcel.read::<u32>().unwrap(), 0xffff); // u16::MAX
1352        assert_eq!(parcel.read::<u32>().unwrap(), 12345); // 12,345
1353        assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1354        assert_eq!(parcel.read::<u32>().unwrap(), 117); // 117
1355
1356        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1357        // made it any shorter since we got the position.
1358        unsafe {
1359            assert!(parcel.set_data_position(start).is_ok());
1360        }
1361
1362        let vec = Vec::<u16>::deserialize(parcel.borrowed_ref()).unwrap();
1363
1364        assert_eq!(vec, [u16::MAX, 12_345, 42, 117]);
1365
1366        let i16s = [i16::MAX, i16::MIN, 42, -117];
1367
1368        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1369        // made it any shorter since we got the position.
1370        unsafe {
1371            assert!(parcel.set_data_position(start).is_ok());
1372        }
1373        assert!(i16s.serialize(&mut parcel.borrowed()).is_ok());
1374        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1375        // made it any shorter since we got the position.
1376        unsafe {
1377            assert!(parcel.set_data_position(start).is_ok());
1378        }
1379
1380        assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1381        assert_eq!(parcel.read::<u32>().unwrap(), 0x7fff); // i16::MAX
1382        assert_eq!(parcel.read::<u32>().unwrap(), 0x8000); // i16::MIN
1383        assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1384        assert_eq!(parcel.read::<u32>().unwrap(), 0xff8b); // -117
1385
1386        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1387        // made it any shorter since we got the position.
1388        unsafe {
1389            assert!(parcel.set_data_position(start).is_ok());
1390        }
1391
1392        let vec = Vec::<i16>::deserialize(parcel.borrowed_ref()).unwrap();
1393
1394        assert_eq!(vec, [i16::MAX, i16::MIN, 42, -117]);
1395
1396        let u32s = [u32::MAX, 12_345, 42, 117];
1397
1398        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1399        // made it any shorter since we got the position.
1400        unsafe {
1401            assert!(parcel.set_data_position(start).is_ok());
1402        }
1403        assert!(u32s.serialize(&mut parcel.borrowed()).is_ok());
1404        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1405        // made it any shorter since we got the position.
1406        unsafe {
1407            assert!(parcel.set_data_position(start).is_ok());
1408        }
1409
1410        assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1411        assert_eq!(parcel.read::<u32>().unwrap(), 0xffffffff); // u32::MAX
1412        assert_eq!(parcel.read::<u32>().unwrap(), 12345); // 12,345
1413        assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1414        assert_eq!(parcel.read::<u32>().unwrap(), 117); // 117
1415
1416        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1417        // made it any shorter since we got the position.
1418        unsafe {
1419            assert!(parcel.set_data_position(start).is_ok());
1420        }
1421
1422        let vec = Vec::<u32>::deserialize(parcel.borrowed_ref()).unwrap();
1423
1424        assert_eq!(vec, [u32::MAX, 12_345, 42, 117]);
1425
1426        let i32s = [i32::MAX, i32::MIN, 42, -117];
1427
1428        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1429        // made it any shorter since we got the position.
1430        unsafe {
1431            assert!(parcel.set_data_position(start).is_ok());
1432        }
1433        assert!(i32s.serialize(&mut parcel.borrowed()).is_ok());
1434        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1435        // made it any shorter since we got the position.
1436        unsafe {
1437            assert!(parcel.set_data_position(start).is_ok());
1438        }
1439
1440        assert_eq!(parcel.read::<u32>().unwrap(), 4); // 4 items
1441        assert_eq!(parcel.read::<u32>().unwrap(), 0x7fffffff); // i32::MAX
1442        assert_eq!(parcel.read::<u32>().unwrap(), 0x80000000); // i32::MIN
1443        assert_eq!(parcel.read::<u32>().unwrap(), 42); // 42
1444        assert_eq!(parcel.read::<u32>().unwrap(), 0xffffff8b); // -117
1445
1446        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1447        // made it any shorter since we got the position.
1448        unsafe {
1449            assert!(parcel.set_data_position(start).is_ok());
1450        }
1451
1452        let vec = Vec::<i32>::deserialize(parcel.borrowed_ref()).unwrap();
1453
1454        assert_eq!(vec, [i32::MAX, i32::MIN, 42, -117]);
1455
1456        let u64s = [u64::MAX, 12_345, 42, 117];
1457
1458        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1459        // made it any shorter since we got the position.
1460        unsafe {
1461            assert!(parcel.set_data_position(start).is_ok());
1462        }
1463        assert!(u64s.serialize(&mut parcel.borrowed()).is_ok());
1464        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1465        // made it any shorter since we got the position.
1466        unsafe {
1467            assert!(parcel.set_data_position(start).is_ok());
1468        }
1469
1470        let vec = Vec::<u64>::deserialize(parcel.borrowed_ref()).unwrap();
1471
1472        assert_eq!(vec, [u64::MAX, 12_345, 42, 117]);
1473
1474        let i64s = [i64::MAX, i64::MIN, 42, -117];
1475
1476        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1477        // made it any shorter since we got the position.
1478        unsafe {
1479            assert!(parcel.set_data_position(start).is_ok());
1480        }
1481        assert!(i64s.serialize(&mut parcel.borrowed()).is_ok());
1482        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1483        // made it any shorter since we got the position.
1484        unsafe {
1485            assert!(parcel.set_data_position(start).is_ok());
1486        }
1487
1488        let vec = Vec::<i64>::deserialize(parcel.borrowed_ref()).unwrap();
1489
1490        assert_eq!(vec, [i64::MAX, i64::MIN, 42, -117]);
1491
1492        let f32s = [f32::NAN, f32::INFINITY, 1.23456789, f32::EPSILON];
1493
1494        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1495        // made it any shorter since we got the position.
1496        unsafe {
1497            assert!(parcel.set_data_position(start).is_ok());
1498        }
1499        assert!(f32s.serialize(&mut parcel.borrowed()).is_ok());
1500        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1501        // made it any shorter since we got the position.
1502        unsafe {
1503            assert!(parcel.set_data_position(start).is_ok());
1504        }
1505
1506        let vec = Vec::<f32>::deserialize(parcel.borrowed_ref()).unwrap();
1507
1508        // NAN != NAN so we can't use it in the assert_eq:
1509        assert!(vec[0].is_nan());
1510        assert_eq!(vec[1..], f32s[1..]);
1511
1512        let f64s = [f64::NAN, f64::INFINITY, 1.234567890123456789, f64::EPSILON];
1513
1514        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1515        // made it any shorter since we got the position.
1516        unsafe {
1517            assert!(parcel.set_data_position(start).is_ok());
1518        }
1519        assert!(f64s.serialize(&mut parcel.borrowed()).is_ok());
1520        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1521        // made it any shorter since we got the position.
1522        unsafe {
1523            assert!(parcel.set_data_position(start).is_ok());
1524        }
1525
1526        let vec = Vec::<f64>::deserialize(parcel.borrowed_ref()).unwrap();
1527
1528        // NAN != NAN so we can't use it in the assert_eq:
1529        assert!(vec[0].is_nan());
1530        assert_eq!(vec[1..], f64s[1..]);
1531
1532        let s1 = "Hello, Binder!";
1533        let s2 = "This is a utf8 string.";
1534        let s3 = "Some more text here.";
1535        let s4 = "Embedded nulls \0 \0";
1536
1537        let strs = [s1, s2, s3, s4];
1538
1539        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1540        // made it any shorter since we got the position.
1541        unsafe {
1542            assert!(parcel.set_data_position(start).is_ok());
1543        }
1544        assert!(strs.serialize(&mut parcel.borrowed()).is_ok());
1545        // SAFETY: start is less than the current size of the parcel data buffer, because we haven't
1546        // made it any shorter since we got the position.
1547        unsafe {
1548            assert!(parcel.set_data_position(start).is_ok());
1549        }
1550
1551        let vec = Vec::<String>::deserialize(parcel.borrowed_ref()).unwrap();
1552
1553        assert_eq!(vec, strs);
1554    }
1555}