rsbinder 0.8.0

rsbinder provides crates implemented in pure Rust that make Binder IPC available on both Android and Linux.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// Copyright 2022 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! Parcelable trait and utilities for serializable types.
//!
//! This module defines the core traits and utilities for types that can be
//! serialized and deserialized in binder parcels, providing the foundation
//! for AIDL-generated types and custom parcelable implementations.

use crate::{binder::*, error::*, parcel::Parcel, process_state::*, sys::*};

/// Core trait for types that can be serialized to and from parcels.
///
/// This trait is equivalent to `android::Parcelable` in C++, and defines
/// the basic interface that all parcelable types must implement for binder IPC.
/// It provides low-level serialization methods that work directly with parcel data.
pub trait Parcelable {
    /// Internal serialization function for parcelables.
    ///
    /// This method is mainly for internal use.
    /// `Serialize::serialize` and its variants are generally
    /// preferred over this function, since the former also
    /// prepend a header.
    fn write_to_parcel(&self, parcel: &mut Parcel) -> Result<()>;

    /// Internal deserialization function for parcelables.
    ///
    /// This method is mainly for internal use.
    /// `Deserialize::deserialize` and its variants are generally
    /// preferred over this function, since the former also
    /// parse the additional header.
    fn read_from_parcel(&mut self, parcel: &mut Parcel) -> Result<()>;
}

/// Metadata that `ParcelableHolder` needs for all parcelables.
///
/// The compiler auto-generates implementations of this trait
/// for AIDL parcelables.
pub trait ParcelableMetadata {
    /// The Binder parcelable descriptor string.
    ///
    /// This string is a unique identifier for a Binder parcelable.
    fn descriptor() -> &'static str;

    /// The Binder parcelable stability.
    fn stability(&self) -> Stability {
        Stability::default()
    }
}

/// A struct whose instances can be written to a [`Parcel`].
// Might be able to hook this up as a serde backend in the future?
pub trait Serialize {
    /// Serialize this instance into the given [`Parcel`].
    fn serialize(&self, parcel: &mut Parcel) -> Result<()>;
}

/// A struct whose instances can be restored from a [`Parcel`].
// Might be able to hook this up as a serde backend in the future?
pub trait Deserialize: Sized {
    /// Deserialize an instance from the given [`Parcel`].
    fn deserialize(parcel: &mut Parcel) -> Result<Self>;

    /// Deserialize an instance from the given [`Parcel`] onto the
    /// current object. This operation will overwrite the old value
    /// partially or completely, depending on how much data is available.
    fn deserialize_from(&mut self, parcel: &mut Parcel) -> Result<()> {
        *self = Self::deserialize(parcel)?;
        Ok(())
    }
}

macro_rules! parcelable_primitives {
    {
        $(
            impl $trait:ident for $ty:ty;
        )*
    } => {
        $(impl_parcelable!{$trait, $ty})*
    };
}

macro_rules! impl_parcelable {
    {Serialize, $ty:ty} => {
        impl Serialize for $ty {
            fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
                parcel.write_aligned(self);
                Ok(())
            }
        }
    };

    {Deserialize, $ty:ty} => {
        impl Deserialize for $ty {
            fn deserialize(parcel: &mut Parcel) -> Result<Self> {
                Ok(<$ty>::from_ne_bytes(parcel.try_into()?))
            }
        }
    };

    {SerializeArray, $ty:ty} => {
        impl SerializeArray for $ty {
            fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
                parcel.write_array(slice)
            }
        }
    };

    {DeserializeArray, $ty:ty} => {
        impl DeserializeArray for $ty {
            fn deserialize_array(parcel: &mut Parcel) -> Result<Option<Vec<Self>>> {
                parcel.read_array()
            }
        }
    };
    {SerializeOption, $ty:ty} => {
        impl SerializeOption for $ty {
        }
    };

    {DeserializeOption, $ty:ty} => {
        impl DeserializeOption for $ty {
        }
    };
}

macro_rules! parcelable_primitives_ex {
    {
        $(
            impl $trait:ident for $ty:ty = $to_ty:ty;
        )*
    } => {
        $(impl_parcelable_ex!{$trait, $to_ty, $ty})*

    };
}

macro_rules! impl_parcelable_ex {
    {Serialize, $to_ty:ty, $ty:ty} => {
        impl Serialize for $ty {
            fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
                let val: $to_ty = *self as _;
                parcel.write_aligned(&val);
                Ok(())
            }
        }
    };

    {Deserialize, $to_ty:ty, $ty:ty} => {
        impl Deserialize for $ty {
            fn deserialize(parcel: &mut Parcel) -> Result<Self> {
                Ok(<$to_ty>::from_ne_bytes(parcel.try_into()?) as _)
            }
        }
    };
}

parcelable_primitives! {
    impl SerializeArray for i8;
    impl DeserializeArray for i8;
    impl SerializeOption for i8;
    impl DeserializeOption for i8;

    impl SerializeArray for u8;
    impl DeserializeArray for u8;
    impl SerializeOption for u8;
    impl DeserializeOption for u8;

    impl SerializeOption for i16;
    impl DeserializeOption for i16;

    impl SerializeOption for u16;
    impl DeserializeOption for u16;

    impl Serialize for i32;
    impl Deserialize for i32;
    impl SerializeArray for i32;
    impl DeserializeArray for i32;
    impl SerializeOption for i32;
    impl DeserializeOption for i32;

    impl Serialize for u32;
    impl Deserialize for u32;
    impl SerializeArray for u32;
    impl DeserializeArray for u32;
    impl SerializeOption for u32;
    impl DeserializeOption for u32;

    impl Serialize for f32;
    impl Deserialize for f32;
    impl SerializeArray for f32;
    impl DeserializeArray for f32;
    impl SerializeOption for f32;
    impl DeserializeOption for f32;

    impl Serialize for i64;
    impl Deserialize for i64;
    impl SerializeArray for i64;
    impl DeserializeArray for i64;
    impl SerializeOption for i64;
    impl DeserializeOption for i64;

    impl Serialize for u64;
    impl Deserialize for u64;
    impl SerializeArray for u64;
    impl DeserializeArray for u64;
    impl SerializeOption for u64;
    impl DeserializeOption for u64;

    impl Serialize for f64;
    impl Deserialize for f64;
    impl SerializeArray for f64;
    impl DeserializeArray for f64;
    impl SerializeOption for f64;
    impl DeserializeOption for f64;

    impl Serialize for u128;
    impl Deserialize for u128;
    impl SerializeArray for u128;
    impl DeserializeArray for u128;
    impl SerializeOption for u128;
    impl DeserializeOption for u128;
}

parcelable_primitives_ex! {
    impl Serialize for i8 = i32;
    impl Deserialize for i8 = i32;

    impl Serialize for u8 = i32;
    impl Deserialize for u8 = i32;

    impl Serialize for i16 = i32;
    impl Deserialize for i16 = i32;

    impl Serialize for u16 = u32;
    impl Deserialize for u16 = u32;
}

impl SerializeArray for i16 {
    fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
        parcel.write_array_char(slice)
    }
}

impl DeserializeArray for i16 {
    fn deserialize_array(parcel: &mut Parcel) -> Result<Option<Vec<Self>>> {
        parcel.read_array_char::<Self>()
    }
}

impl SerializeArray for u16 {
    fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
        parcel.write_array_char(slice)
    }
}

impl DeserializeArray for u16 {
    fn deserialize_array(parcel: &mut Parcel) -> Result<Option<Vec<Self>>> {
        parcel.read_array_char::<Self>()
    }
}

impl Deserialize for bool {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        Ok(<i32>::from_ne_bytes(parcel.try_into()?) != 0)
    }
}

impl DeserializeArray for bool {}

impl Serialize for bool {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        let val: i32 = *self as _;
        parcel.write_aligned(&val);
        Ok(())
    }
}

impl SerializeArray for bool {}

impl SerializeOption for str {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        match this {
            None => parcel.write::<i32>(&-1),

            Some(text) => {
                let mut utf16 = Vec::with_capacity(text.len() + 2); // Adding space for final 0 and
                                                                    // padding.
                utf16.extend(text.encode_utf16());

                let len = utf16.len();

                utf16.push(0);

                parcel.write::<i32>(&(len as i32))?;
                // SAFETY: We're creating a byte view of the UTF-16 encoded string.
                // - utf16 is a valid Vec<u16> with proper alignment
                // - The byte count is exactly utf16.len() * size_of::<u16>()
                // - The resulting byte slice will not outlive the utf16 vector
                // - write_aligned_data handles 4-byte padding internally
                parcel.write_aligned_data(unsafe {
                    std::slice::from_raw_parts(
                        utf16.as_ptr() as *const u8,
                        utf16.len() * std::mem::size_of::<u16>(),
                    )
                });

                Ok(())
            }
        }
    }
}

impl Deserialize for StatusCode {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        Ok(<i32>::from_ne_bytes(parcel.try_into()?).into())
    }
}

impl Serialize for StatusCode {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        let val: i32 = i32::from(*self);
        parcel.write_aligned(&val);
        Ok(())
    }
}

impl Serialize for str {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        Some(self).serialize(parcel)
    }
}

impl SerializeArray for &str {}

macro_rules! parcelable_struct {
    {
        $(
            impl $trait:ident for $ty:ty;
        )*
    } => {
        $(impl_parcelable_struct!{$trait, $ty})*
    };
}

macro_rules! impl_parcelable_struct {
    {Serialize, $ty:ty} => {
        impl Serialize for $ty {
            fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
                parcel.write_aligned(self);
                Ok(())
            }
        }
    };

    {Deserialize, $ty:ty} => {
        impl Deserialize for $ty {
            fn deserialize(parcel: &mut Parcel) -> Result<Self> {
                const SIZE: usize = std::mem::size_of::<$ty>();
                // SAFETY: this macro arm is only instantiated for the
                // bindgen `#[repr(C)]` binder-ABI structs listed in the
                // `parcelable_struct!` invocations below — plain-old-data
                // (integers / unions / fixed arrays) with no invalid bit
                // patterns, so every `[u8; SIZE]` is a valid `$ty`.
                // `parcel.try_into()?` yields exactly `SIZE` initialized
                // bytes (length-checked; returns Err otherwise).
                Ok(unsafe { std::mem::transmute::<[u8; SIZE], $ty>(parcel.try_into()?) })
            }
        }
    };
}

parcelable_struct! {
    impl Serialize for binder_transaction_data_secctx;
    impl Deserialize for binder_transaction_data_secctx;

    impl Serialize for binder_transaction_data;
    impl Deserialize for binder_transaction_data;
}

impl Serialize for String {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        self.as_str().serialize(parcel)
    }
}

impl SerializeArray for String {}

impl SerializeOption for String {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(this.map(String::as_str), parcel)
    }
}

impl DeserializeOption for String {
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        let len = parcel.read::<i32>()?;

        if (0..i32::MAX).contains(&len) {
            let data = parcel.read_aligned_data((len as usize + 1) * std::mem::size_of::<u16>())?;
            let res = String::from_utf16(unsafe {
                std::slice::from_raw_parts(data.as_ptr() as *const u16, len as _)
            })
            .map_err(|e| {
                log::error!("Deserialize for Option<String16>: {e}");
                StatusCode::BadValue
            })?;

            Ok(Some(res))
        } else {
            Ok(None)
        }
    }
}

impl Deserialize for String {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        Deserialize::deserialize(parcel)
            .transpose()
            .unwrap_or_else(|| {
                log::error!("Deserialize for String: UnexpectedNull");
                Err(StatusCode::UnexpectedNull)
            })
    }
}

impl DeserializeArray for String {}

impl Deserialize for flat_binder_object {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        parcel.read_object(false)
    }
}

impl Serialize for flat_binder_object {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        parcel.write_object(self, false)?;
        Ok(())
    }
}

impl Serialize for SIBinder {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(Some(self), parcel)
    }
}

impl SerializeOption for SIBinder {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        match this {
            Some(binder) => {
                parcel.write::<flat_binder_object>(&binder.into())?;
                if crate::sdk_at_least(30) {
                    parcel.write::<i32>(&binder.stability().into())?;
                }
                Ok(())
            }

            None => {
                parcel.write::<flat_binder_object>(&flat_binder_object::default())?;
                if crate::sdk_at_least(30) {
                    parcel.write::<i32>(&Stability::Local.into())?;
                }

                Ok(())
            }
        }
    }
}

impl SerializeArray for SIBinder {}

impl Deserialize for SIBinder {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        match DeserializeOption::deserialize_option(parcel) {
            Ok(Some(binder)) => Ok(binder),
            Ok(None) => {
                log::error!("Deserialize for SIBinder: UnexpectedNull");
                Err(StatusCode::UnexpectedNull)
            }
            Err(err) => Err(err),
        }
    }
}

impl DeserializeOption for SIBinder {
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        let flat: flat_binder_object = parcel.read()?;
        let stability: i32 = if crate::sdk_at_least(30) {
            parcel.read()?
        } else {
            Stability::Local.into()
        };

        match flat.header_type() {
            BINDER_TYPE_BINDER => {
                // Receiving BINDER_TYPE_BINDER means the kernel routed
                // a binder back to its original publisher (us).
                // Cross-process binder transfers reach receivers as
                // BINDER_TYPE_HANDLE — the kernel only emits
                // BINDER_TYPE_BINDER on the publisher loopback path.
                // Look up the id in our sidecar table; an unknown id
                // here would mean either (a) a kernel bug surfacing a
                // BINDER_TYPE_BINDER we never published, or (b) the
                // entry was already torn down (shouldn't happen
                // because the round-trip ride keeps `kernel_refs > 0`
                // via the receiving process's outstanding handle).
                // Either way it's an integrity error → DeadObject.
                let id = flat.pointer();
                if id != 0 {
                    let arc = ProcessState::as_self().lookup_native(id).ok_or_else(|| {
                        log::error!("BINDER_TYPE_BINDER for unknown native id {id}");
                        StatusCode::DeadObject
                    })?;
                    Ok(Some(SIBinder::from_arc(arc)))
                } else {
                    Ok(None)
                }
            }

            BINDER_TYPE_HANDLE => {
                let res = ProcessState::as_self()
                    .strong_proxy_for_handle_stability(flat.handle(), stability.try_into()?)?;
                Ok(Some(res))
            }

            _ => {
                log::warn!(
                    "Unknown Binder Type ({}) was delivered.",
                    flat.header_type()
                );
                Err(StatusCode::BadType)
            }
        }
    }
}

impl DeserializeArray for SIBinder {}

/// Flag that specifies that the following parcelable is present.
///
/// This is the Rust equivalent of `Parcel::kNonNullParcelableFlag`
/// from `include/binder/Parcel.h` in C++.
pub const NON_NULL_PARCELABLE_FLAG: i32 = 1;

/// Flag that specifies that the following parcelable is absent.
///
/// This is the Rust equivalent of `Parcel::kNullParcelableFlag`
/// from `include/binder/Parcel.h` in C++.
pub const NULL_PARCELABLE_FLAG: i32 = 0;

/// Helper trait for types that can be nullable when serialized.
// We really need this trait instead of implementing `Serialize for Option<T>`
// because of the Rust orphan rule which prevents us from doing
// `impl Serialize for Option<&dyn IFoo>` for AIDL interfaces.
// Instead we emit `impl SerializeOption for dyn IFoo` which is allowed.
// We also use it to provide a default implementation for AIDL-generated
// parcelables.
pub trait SerializeOption: Serialize {
    /// Serialize an Option of this type into the given parcel.
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        if let Some(inner) = this {
            parcel.write(&NON_NULL_PARCELABLE_FLAG)?;
            parcel.write(inner)
        } else {
            parcel.write(&NULL_PARCELABLE_FLAG)
        }
    }
}

/// Helper trait for types that can be nullable when deserialized.
pub trait DeserializeOption: Deserialize {
    /// Deserialize an Option of this type from the given parcel.
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        let null: i32 = parcel.read()?;
        if null == NULL_PARCELABLE_FLAG {
            Ok(None)
        } else {
            parcel.read().map(Some)
        }
    }

    /// Deserialize an Option of this type from the given parcel onto the
    /// current object. This operation will overwrite the current value
    /// partially or completely, depending on how much data is available.
    fn deserialize_option_from(this: &mut Option<Self>, parcel: &mut Parcel) -> Result<()> {
        *this = Self::deserialize_option(parcel)?;
        Ok(())
    }
}

impl<T: SerializeOption> Serialize for Option<T> {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(self.as_ref(), parcel)
    }
}

impl<T: DeserializeOption> Deserialize for Option<T> {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        DeserializeOption::deserialize_option(parcel)
    }

    fn deserialize_from(&mut self, parcel: &mut Parcel) -> Result<()> {
        DeserializeOption::deserialize_option_from(self, parcel)
    }
}

// We need these to support Option<&T> for all T
impl<T: Serialize + ?Sized> Serialize for &T {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        Serialize::serialize(*self, parcel)
    }
}

impl<T: SerializeOption + ?Sized> SerializeOption for &T {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(this.copied(), parcel)
    }
}

impl<T: Serialize> Serialize for Box<T> {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        Serialize::serialize(&**self, parcel)
    }
}

impl<T: Deserialize> Deserialize for Box<T> {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        Deserialize::deserialize(parcel).map(Box::new)
    }
}

impl<T: SerializeOption> SerializeOption for Box<T> {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(this.map(|inner| &**inner), parcel)
    }
}

impl<T: DeserializeOption> DeserializeOption for Box<T> {
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        DeserializeOption::deserialize_option(parcel).map(|t| t.map(Box::new))
    }
}

impl<T: FromIBinder + Serialize + ?Sized> Serialize for Strong<T> {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        Serialize::serialize(&**self, parcel)
    }
}

impl<T: FromIBinder + SerializeOption + ?Sized> SerializeOption for Strong<T> {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(this.map(|b| &**b), parcel)
    }
}

impl<T: FromIBinder + Serialize + ?Sized> SerializeArray for Strong<T> {}

impl<T: FromIBinder + ?Sized> Deserialize for Strong<T> {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        let binder: SIBinder = parcel.read()?;
        FromIBinder::try_from(binder)
    }
}

impl<T: FromIBinder + ?Sized> DeserializeOption for Strong<T> {
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        let binder: Option<SIBinder> = parcel.read()?;
        binder.map(FromIBinder::try_from).transpose()
    }
}

impl<T: FromIBinder + ?Sized> DeserializeArray for Strong<T> {}

impl<T: DeserializeOption> DeserializeArray for Option<T> {}
impl<T: SerializeOption> SerializeArray for Option<T> {}

/// Helper trait for types that can be serialized as arrays.
/// Defaults to calling Serialize::serialize() manually for every element,
/// but can be overridden for custom implementations like `writeByteArray`.
// Until specialization is stabilized in Rust, we need this to be a separate
// trait because it's the only way to have a default implementation for a method.
// We want the default implementation for most types, but an override for
// a few special ones like `readByteArray` for `u8`.
pub trait SerializeArray: Serialize + Sized {
    /// Serialize an array of this type into the given parcel.
    fn serialize_array(slice: &[Self], parcel: &mut Parcel) -> Result<()> {
        parcel.write::<i32>(&(slice.len() as i32))?;

        for s in slice {
            parcel.write(s)?;
        }

        Ok(())
    }
}

/// Helper trait for types that can be deserialized as arrays.
/// Defaults to calling Deserialize::deserialize() manually for every element,
/// but can be overridden for custom implementations like `readByteArray`.
pub trait DeserializeArray: Deserialize {
    /// Deserialize an array of type from the given parcel.
    fn deserialize_array(parcel: &mut Parcel) -> Result<Option<Vec<Self>>> {
        let len: i32 = parcel.read()?;
        if len < -1 {
            log::error!("Negative array size given in parcel: {len}");
            return Err(StatusCode::BadValue);
        }
        if len <= 0 {
            return Ok(None);
        }
        let mut res: Vec<Self> = Vec::with_capacity(len as _);

        for _ in 0..len {
            res.push(parcel.read()?);
        }

        Ok(Some(res))
    }
}

impl<T: SerializeArray> Serialize for [T] {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        SerializeArray::serialize_array(self, parcel)
    }
}

impl<T: SerializeArray> Serialize for Vec<T> {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        SerializeArray::serialize_array(&self[..], parcel)
    }
}

impl<T: SerializeArray> SerializeOption for [T] {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        if let Some(v) = this {
            SerializeArray::serialize_array(v, parcel)
        } else {
            parcel.write(&-1i32)
        }
    }
}

impl<T: SerializeArray> SerializeOption for Vec<T> {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(this.map(Vec::as_slice), parcel)
    }
}

impl<T: DeserializeArray> Deserialize for Vec<T> {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        DeserializeArray::deserialize_array(parcel).map(|v| v.unwrap_or_default())
    }
}

impl<T: DeserializeArray> DeserializeOption for Vec<T> {
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        DeserializeArray::deserialize_array(parcel)
    }
}

impl<T: SerializeArray, const N: usize> Serialize for [T; N] {
    fn serialize(&self, parcel: &mut Parcel) -> Result<()> {
        SerializeArray::serialize_array(self, parcel)
    }
}

impl<T: SerializeArray, const N: usize> SerializeOption for [T; N] {
    fn serialize_option(this: Option<&Self>, parcel: &mut Parcel) -> Result<()> {
        SerializeOption::serialize_option(this.map(|arr| &arr[..]), parcel)
    }
}

impl<T: SerializeArray, const N: usize> SerializeArray for [T; N] {}

impl<T: DeserializeArray, const N: usize> Deserialize for [T; N] {
    fn deserialize(parcel: &mut Parcel) -> Result<Self> {
        let vec = DeserializeArray::deserialize_array(parcel)
            .transpose()
            .unwrap_or_else(|| {
                log::error!("Deserialize for [T; N]: UnexpectedNull");
                Err(StatusCode::UnexpectedNull)
            })?;
        vec.try_into().map_err(|_| {
            log::error!("Deserialize: Failed to convert Vec<T> to [T; N]");
            StatusCode::BadValue
        })
    }
}

impl<T: std::fmt::Debug + DeserializeArray, const N: usize> DeserializeOption for [T; N] {
    fn deserialize_option(parcel: &mut Parcel) -> Result<Option<Self>> {
        let vec = DeserializeArray::deserialize_array(parcel)?;
        vec.map(|v| {
            v.try_into().map_err(|_| {
                log::error!("DeserializeOption: Failed to convert Vec<T> to [T; N]");
                StatusCode::BadValue
            })
        })
        .transpose()
    }
}

impl<T: DeserializeArray, const N: usize> DeserializeArray for [T; N] {}