1use 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
30pub trait Parcelable {
36 fn write_to_parcel(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
43
44 fn read_from_parcel(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()>;
51}
52
53pub trait UnstructuredParcelable: Sized {
58 fn write_to_parcel(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
63
64 fn from_parcel(parcel: &BorrowedParcel<'_>) -> Result<Self>;
70
71 fn read_from_parcel(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
77 *self = Self::from_parcel(parcel)?;
78 Ok(())
79 }
80}
81
82pub trait Serialize {
85 fn serialize(&self, parcel: &mut BorrowedParcel<'_>) -> Result<()>;
87}
88
89pub trait Deserialize: Sized {
92 type UninitType;
95
96 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 fn uninit() -> Self::UninitType;
108
109 fn from_init(value: Self) -> Self::UninitType;
111
112 fn deserialize(parcel: &BorrowedParcel<'_>) -> Result<Self>;
114
115 fn deserialize_from(&mut self, parcel: &BorrowedParcel<'_>) -> Result<()> {
119 *self = Self::deserialize(parcel)?;
120 Ok(())
121 }
122}
123
124pub trait SerializeArray: Serialize + Sized {
132 fn serialize_array(slice: &[Self], parcel: &mut BorrowedParcel<'_>) -> Result<()> {
134 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
147unsafe extern "C" fn serialize_element<T: Serialize>(
155 parcel: *mut sys::AParcel,
156 array: *const c_void,
157 index: usize,
158) -> status_t {
159 let slice: &[T] = unsafe { slice::from_raw_parts(array.cast(), index + 1) };
162
163 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
174pub trait DeserializeArray: Deserialize {
178 fn deserialize_array(parcel: &BorrowedParcel<'_>) -> Result<Option<Vec<Self>>> {
180 let mut vec: Option<Vec<Self::UninitType>> = None;
181 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 let vec: Option<Vec<Self>> = unsafe { mem::transmute(vec) };
199 Ok(vec)
200 }
201}
202
203unsafe extern "C" fn deserialize_element<T: Deserialize>(
211 parcel: *const sys::AParcel,
212 array: *mut c_void,
213 index: usize,
214) -> status_t {
215 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 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
238pub const NON_NULL_PARCELABLE_FLAG: i32 = 1;
243
244pub const NULL_PARCELABLE_FLAG: i32 = 0;
249
250pub trait SerializeOption: Serialize {
258 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
269pub trait DeserializeOption: Deserialize {
271 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 fn deserialize_option_from(this: &mut Option<Self>, parcel: &BorrowedParcel<'_>) -> Result<()> {
285 *this = Self::deserialize_option(parcel)?;
286 Ok(())
287 }
288}
289
290unsafe 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 let res = unsafe { allocate_vec::<T>(data, len) };
306 let vec = unsafe { &mut *(data as *mut Option<Vec<T::UninitType>>) };
308 if let Some(new_vec) = vec {
309 unsafe {
311 *buffer = new_vec.as_mut_ptr() as *mut T;
312 }
313 }
314 res
315}
316
317unsafe extern "C" fn allocate_vec<T: Deserialize>(data: *mut c_void, len: i32) -> bool {
324 let vec = unsafe { &mut *(data as *mut Option<Vec<T::UninitType>>) };
326 if len < 0 {
327 *vec = None;
328 return true;
329 }
330
331 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 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
353unsafe fn vec_assume_init<T: Deserialize>(vec: Vec<T::UninitType>) -> Vec<T> {
355 let _ = T::ASSERT_UNINIT_SIZE_AND_ALIGNMENT;
357
358 let mut vec = ManuallyDrop::new(vec);
359 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 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 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 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 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 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 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 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 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 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 None => unsafe {
596 status_result(sys::AParcel_writeString(parcel.as_native_mut(), ptr::null(), -1))
597 },
598 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 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 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 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 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 unsafe { sys::AParcel_readStatusHeader(parcel.as_native(), &mut status_ptr) };
832 status_result(ret_status)?;
833 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 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
887impl<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#[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#[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#[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#[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 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 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 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 unsafe {
1293 assert!(parcel.set_data_position(start).is_ok());
1294 }
1295
1296 assert_eq!(parcel.read::<u32>().unwrap(), 4); assert_eq!(parcel.read::<u32>().unwrap(), 0x752aff65); 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 unsafe {
1313 assert!(parcel.set_data_position(start).is_ok());
1314 }
1315
1316 assert!(parcel.write(&i8s[..]).is_ok());
1317
1318 unsafe {
1321 assert!(parcel.set_data_position(start).is_ok());
1322 }
1323
1324 assert_eq!(parcel.read::<u32>().unwrap(), 4); assert_eq!(parcel.read::<u32>().unwrap(), 0x8b2a7f80); 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 unsafe {
1341 assert!(parcel.set_data_position(start).is_ok());
1342 }
1343 assert!(u16s.serialize(&mut parcel.borrowed()).is_ok());
1344 unsafe {
1347 assert!(parcel.set_data_position(start).is_ok());
1348 }
1349
1350 assert_eq!(parcel.read::<u32>().unwrap(), 4); assert_eq!(parcel.read::<u32>().unwrap(), 0xffff); assert_eq!(parcel.read::<u32>().unwrap(), 12345); assert_eq!(parcel.read::<u32>().unwrap(), 42); assert_eq!(parcel.read::<u32>().unwrap(), 117); 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 unsafe {
1371 assert!(parcel.set_data_position(start).is_ok());
1372 }
1373 assert!(i16s.serialize(&mut parcel.borrowed()).is_ok());
1374 unsafe {
1377 assert!(parcel.set_data_position(start).is_ok());
1378 }
1379
1380 assert_eq!(parcel.read::<u32>().unwrap(), 4); assert_eq!(parcel.read::<u32>().unwrap(), 0x7fff); assert_eq!(parcel.read::<u32>().unwrap(), 0x8000); assert_eq!(parcel.read::<u32>().unwrap(), 42); assert_eq!(parcel.read::<u32>().unwrap(), 0xff8b); 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 unsafe {
1401 assert!(parcel.set_data_position(start).is_ok());
1402 }
1403 assert!(u32s.serialize(&mut parcel.borrowed()).is_ok());
1404 unsafe {
1407 assert!(parcel.set_data_position(start).is_ok());
1408 }
1409
1410 assert_eq!(parcel.read::<u32>().unwrap(), 4); assert_eq!(parcel.read::<u32>().unwrap(), 0xffffffff); assert_eq!(parcel.read::<u32>().unwrap(), 12345); assert_eq!(parcel.read::<u32>().unwrap(), 42); assert_eq!(parcel.read::<u32>().unwrap(), 117); 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 unsafe {
1431 assert!(parcel.set_data_position(start).is_ok());
1432 }
1433 assert!(i32s.serialize(&mut parcel.borrowed()).is_ok());
1434 unsafe {
1437 assert!(parcel.set_data_position(start).is_ok());
1438 }
1439
1440 assert_eq!(parcel.read::<u32>().unwrap(), 4); assert_eq!(parcel.read::<u32>().unwrap(), 0x7fffffff); assert_eq!(parcel.read::<u32>().unwrap(), 0x80000000); assert_eq!(parcel.read::<u32>().unwrap(), 42); assert_eq!(parcel.read::<u32>().unwrap(), 0xffffff8b); 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 unsafe {
1461 assert!(parcel.set_data_position(start).is_ok());
1462 }
1463 assert!(u64s.serialize(&mut parcel.borrowed()).is_ok());
1464 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 unsafe {
1479 assert!(parcel.set_data_position(start).is_ok());
1480 }
1481 assert!(i64s.serialize(&mut parcel.borrowed()).is_ok());
1482 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 unsafe {
1497 assert!(parcel.set_data_position(start).is_ok());
1498 }
1499 assert!(f32s.serialize(&mut parcel.borrowed()).is_ok());
1500 unsafe {
1503 assert!(parcel.set_data_position(start).is_ok());
1504 }
1505
1506 let vec = Vec::<f32>::deserialize(parcel.borrowed_ref()).unwrap();
1507
1508 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 unsafe {
1517 assert!(parcel.set_data_position(start).is_ok());
1518 }
1519 assert!(f64s.serialize(&mut parcel.borrowed()).is_ok());
1520 unsafe {
1523 assert!(parcel.set_data_position(start).is_ok());
1524 }
1525
1526 let vec = Vec::<f64>::deserialize(parcel.borrowed_ref()).unwrap();
1527
1528 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 unsafe {
1542 assert!(parcel.set_data_position(start).is_ok());
1543 }
1544 assert!(strs.serialize(&mut parcel.borrowed()).is_ok());
1545 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}