aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowParcel.java
blob: a27e5038e0fb03124f0ca6f0ebe699280fccc08d (plain)
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.KITKAT_WATCH;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.O_MR1;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static android.os.Build.VERSION_CODES.S;
import static android.os.Build.VERSION_CODES.TIRAMISU;
import static org.robolectric.RuntimeEnvironment.castNativePtr;

import android.os.BadParcelableException;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.util.Log;
import android.util.Pair;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.res.android.NativeObjRegistry;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;

/**
 * Robolectric's {@link Parcel} pretends to be backed by a byte buffer, closely matching {@link
 * Parcel}'s position, size, and capacity behavior. However, its internal pure-Java representation
 * is strongly typed, to detect non-portable code and common testing mistakes. It may throw {@link
 * IllegalArgumentException} or {@link IllegalStateException} for error-prone behavior normal {@link
 * Parcel} tolerates.
 */
@Implements(value = Parcel.class, looseSignatures = true)
public class ShadowParcel {
  protected static final String TAG = "Parcel";

  @RealObject private Parcel realObject;

  private static final NativeObjRegistry<ByteBuffer> NATIVE_BYTE_BUFFER_REGISTRY =
      new NativeObjRegistry<>(ByteBuffer.class);

  private static final HashMap<ClassLoader, HashMap<String, Pair<Creator<?>, Class<?>>>>
      pairedCreators = new HashMap<>();

  @Implementation(maxSdk = JELLY_BEAN_MR1)
  @SuppressWarnings("TypeParameterUnusedInFormals")
  protected <T extends Parcelable> T readParcelable(ClassLoader loader) {
    // prior to JB MR2, readParcelableCreator() is inlined here.
    Parcelable.Creator<?> creator = readParcelableCreator(loader);
    if (creator == null) {
      return null;
    }

    if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
      Parcelable.ClassLoaderCreator<?> classLoaderCreator =
          (Parcelable.ClassLoaderCreator<?>) creator;
      return (T) classLoaderCreator.createFromParcel(realObject, loader);
    }
    return (T) creator.createFromParcel(realObject);
  }

  @HiddenApi
  @Implementation
  public Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
    // note: calling `readString` will also consume the string, and increment the data-pointer.
    // which is exactly what we need, since we do not call the real `readParcelableCreator`.
    final String name = realObject.readString();
    if (name == null) {
      return null;
    }

    Parcelable.Creator<?> creator;
    try {
      // If loader == null, explicitly emulate Class.forName(String) "caller
      // classloader" behavior.
      ClassLoader parcelableClassLoader = (loader == null ? getClass().getClassLoader() : loader);
      // Avoid initializing the Parcelable class until we know it implements
      // Parcelable and has the necessary CREATOR field.
      Class<?> parcelableClass = Class.forName(name, false /* initialize */, parcelableClassLoader);
      if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
        throw new BadParcelableException(
            "Parcelable protocol requires that the " + "class implements Parcelable");
      }
      Field f = parcelableClass.getField("CREATOR");

      // this is a fix for JDK8<->Android VM incompatibility:
      // Apparently, JDK will not allow access to a public field if its
      // class is not visible (private or package-private) from the call-site.
      f.setAccessible(true);

      if ((f.getModifiers() & Modifier.STATIC) == 0) {
        throw new BadParcelableException(
            "Parcelable protocol requires " + "the CREATOR object to be static on class " + name);
      }
      Class<?> creatorType = f.getType();
      if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
        // Fail before calling Field.get(), not after, to avoid initializing
        // parcelableClass unnecessarily.
        throw new BadParcelableException(
            "Parcelable protocol requires a "
                + "Parcelable.Creator object called "
                + "CREATOR on class "
                + name);
      }
      creator = (Parcelable.Creator<?>) f.get(null);
    } catch (IllegalAccessException e) {
      Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
      throw new BadParcelableException("IllegalAccessException when unmarshalling: " + name);
    } catch (ClassNotFoundException e) {
      Log.e(TAG, "Class not found when unmarshalling: " + name, e);
      throw new BadParcelableException("ClassNotFoundException when unmarshalling: " + name);
    } catch (NoSuchFieldException e) {
      throw new BadParcelableException(
          "Parcelable protocol requires a "
              + "Parcelable.Creator object called "
              + "CREATOR on class "
              + name);
    }
    if (creator == null) {
      throw new BadParcelableException(
          "Parcelable protocol requires a "
              + "non-null Parcelable.Creator object called "
              + "CREATOR on class "
              + name);
    }
    return creator;
  }

  /**
   * The goal of this shadow method is to workaround a JVM/ART incompatibility.
   *
   * <p>In ART, a public field is visible regardless whether or not the enclosing class is public.
   * On the JVM, this is not the case. For compatibility, we need to use {@link
   * Field#setAccessible(boolean)} to simulate the same behavior.
   */
  @SuppressWarnings("unchecked")
  @Implementation(minSdk = TIRAMISU)
  protected <T> Parcelable.Creator<T> readParcelableCreatorInternal(
      ClassLoader loader, Class<T> clazz) {
    String name = realObject.readString();
    if (name == null) {
      return null;
    }

    Pair<Creator<?>, Class<?>> creatorAndParcelableClass;
    synchronized (pairedCreators) {
      HashMap<String, Pair<Creator<?>, Class<?>>> map = pairedCreators.get(loader);
      if (map == null) {
        pairedCreators.put(loader, new HashMap<>());
        creatorAndParcelableClass = null;
      } else {
        creatorAndParcelableClass = map.get(name);
      }
    }

    if (creatorAndParcelableClass != null) {
      Parcelable.Creator<?> creator = creatorAndParcelableClass.first;
      Class<?> parcelableClass = creatorAndParcelableClass.second;
      if (clazz != null) {
        if (!clazz.isAssignableFrom(parcelableClass)) {
          throw newBadTypeParcelableException(
              "Parcelable creator "
                  + name
                  + " is not "
                  + "a subclass of required class "
                  + clazz.getName()
                  + " provided in the parameter");
        }
      }

      return (Parcelable.Creator<T>) creator;
    }

    Parcelable.Creator<?> creator;
    Class<?> parcelableClass;
    try {
      // If loader == null, explicitly emulate Class.forName(String) "caller
      // classloader" behavior.
      ClassLoader parcelableClassLoader = (loader == null ? getClass().getClassLoader() : loader);
      // Avoid initializing the Parcelable class until we know it implements
      // Parcelable and has the necessary CREATOR field.
      parcelableClass = Class.forName(name, /* initialize= */ false, parcelableClassLoader);
      if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
        throw new BadParcelableException(
            "Parcelable protocol requires subclassing " + "from Parcelable on class " + name);
      }
      if (clazz != null) {
        if (!clazz.isAssignableFrom(parcelableClass)) {
          throw newBadTypeParcelableException(
              "Parcelable creator "
                  + name
                  + " is not "
                  + "a subclass of required class "
                  + clazz.getName()
                  + " provided in the parameter");
        }
      }

      Field f = parcelableClass.getField("CREATOR");

      // this is a fix for JDK8<->Android VM incompatibility:
      // Apparently, JDK will not allow access to a public field if its
      // class is not visible (private or package-private) from the call-site.
      f.setAccessible(true);

      if ((f.getModifiers() & Modifier.STATIC) == 0) {
        throw new BadParcelableException(
            "Parcelable protocol requires " + "the CREATOR object to be static on class " + name);
      }
      Class<?> creatorType = f.getType();
      if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
        // Fail before calling Field.get(), not after, to avoid initializing
        // parcelableClass unnecessarily.
        throw new BadParcelableException(
            "Parcelable protocol requires a "
                + "Parcelable.Creator object called "
                + "CREATOR on class "
                + name);
      }
      creator = (Parcelable.Creator<?>) f.get(null);
    } catch (IllegalAccessException e) {
      Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
      throw new BadParcelableException("IllegalAccessException when unmarshalling: " + name, e);
    } catch (ClassNotFoundException e) {
      Log.e(TAG, "Class not found when unmarshalling: " + name, e);
      throw new BadParcelableException("ClassNotFoundException when unmarshalling: " + name, e);
    } catch (NoSuchFieldException e) {
      throw new BadParcelableException(
          "Parcelable protocol requires a "
              + "Parcelable.Creator object called "
              + "CREATOR on class "
              + name,
          e);
    }
    if (creator == null) {
      throw new BadParcelableException(
          "Parcelable protocol requires a "
              + "non-null Parcelable.Creator object called "
              + "CREATOR on class "
              + name);
    }

    synchronized (pairedCreators) {
      pairedCreators.get(loader).put(name, Pair.create(creator, parcelableClass));
    }

    return (Parcelable.Creator<T>) creator;
  }

  private BadParcelableException newBadTypeParcelableException(String message) {
    try {
      return (BadParcelableException)
          ReflectionHelpers.callConstructor(
              Class.forName("android.os.BadTypeParcelableException"),
              ClassParameter.from(String.class, message));
    } catch (ClassNotFoundException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }

  @Implementation
  protected void writeByteArray(byte[] b, int offset, int len) {
    if (b == null) {
      realObject.writeInt(-1);
      return;
    }
    Number nativePtr = ReflectionHelpers.getField(realObject, "mNativePtr");
    nativeWriteByteArray(nativePtr.longValue(), b, offset, len);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static int nativeDataSize(int nativePtr) {
    return nativeDataSize((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static int nativeDataSize(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).dataSize();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static int nativeDataAvail(int nativePtr) {
    return nativeDataAvail((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static int nativeDataAvail(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).dataAvailable();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static int nativeDataPosition(int nativePtr) {
    return nativeDataPosition((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static int nativeDataPosition(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).dataPosition();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static int nativeDataCapacity(int nativePtr) {
    return nativeDataCapacity((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static int nativeDataCapacity(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).dataCapacity();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeSetDataSize(int nativePtr, int size) {
    nativeSetDataSize((long) nativePtr, size);
  }

  @Implementation(minSdk = LOLLIPOP)
  @SuppressWarnings("robolectric.ShadowReturnTypeMismatch")
  protected static void nativeSetDataSize(long nativePtr, int size) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).setDataSize(size);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeSetDataPosition(int nativePtr, int pos) {
    nativeSetDataPosition((long) nativePtr, pos);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeSetDataPosition(long nativePtr, int pos) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).setDataPosition(pos);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeSetDataCapacity(int nativePtr, int size) {
    nativeSetDataCapacity((long) nativePtr, size);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeSetDataCapacity(long nativePtr, int size) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).setDataCapacityAtLeast(size);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteByteArray(int nativePtr, byte[] b, int offset, int len) {
    nativeWriteByteArray((long) nativePtr, b, offset, len);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeByteArray(b, offset, len);
  }

  // duplicate the writeBlob implementation from latest android, to avoid referencing the
  // non-existent-in-JDK java.util.Arrays.checkOffsetAndCount method.
  @Implementation(minSdk = M)
  protected void writeBlob(byte[] b, int offset, int len) {
    if (b == null) {
      realObject.writeInt(-1);
      return;
    }
    throwsIfOutOfBounds(b.length, offset, len);
    long nativePtr = ReflectionHelpers.getField(realObject, "mNativePtr");
    nativeWriteBlob(nativePtr, b, offset, len);
  }

  private static void throwsIfOutOfBounds(int len, int offset, int count) {
    if (len < 0) {
      throw new ArrayIndexOutOfBoundsException("Negative length: " + len);
    }

    if ((offset | count) < 0 || offset > len - count) {
      throw new ArrayIndexOutOfBoundsException();
    }
  }

  // nativeWriteBlob was introduced in lollipop, thus no need for a int nativePtr variant
  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len) {
    nativeWriteByteArray(nativePtr, b, offset, len);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteInt(int nativePtr, int val) {
    nativeWriteInt((long) nativePtr, val);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = R)
  protected static void nativeWriteInt(long nativePtr, int val) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeInt(val);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteLong(int nativePtr, long val) {
    nativeWriteLong((long) nativePtr, val);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = R)
  protected static void nativeWriteLong(long nativePtr, long val) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeLong(val);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteFloat(int nativePtr, float val) {
    nativeWriteFloat((long) nativePtr, val);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = R)
  protected static void nativeWriteFloat(long nativePtr, float val) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeFloat(val);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteDouble(int nativePtr, double val) {
    nativeWriteDouble((long) nativePtr, val);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = R)
  protected static void nativeWriteDouble(long nativePtr, double val) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeDouble(val);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteString(int nativePtr, String val) {
    nativeWriteString((long) nativePtr, val);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = Q)
  protected static void nativeWriteString(long nativePtr, String val) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeString(val);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  protected static void nativeWriteStrongBinder(int nativePtr, IBinder val) {
    nativeWriteStrongBinder((long) nativePtr, val);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeWriteStrongBinder(long nativePtr, IBinder val) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeStrongBinder(val);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static byte[] nativeCreateByteArray(int nativePtr) {
    return nativeCreateByteArray((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static byte[] nativeCreateByteArray(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).createByteArray();
  }

  // nativeReadBlob was introduced in lollipop, thus no need for a int nativePtr variant
  @Implementation(minSdk = LOLLIPOP)
  protected static byte[] nativeReadBlob(long nativePtr) {
    return nativeCreateByteArray(nativePtr);
  }

  @Implementation(minSdk = O_MR1)
  protected static boolean nativeReadByteArray(long nativePtr, byte[] dest, int destLen) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readByteArray(dest, destLen);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static int nativeReadInt(int nativePtr) {
    return nativeReadInt((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static int nativeReadInt(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readInt();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static long nativeReadLong(int nativePtr) {
    return nativeReadLong((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static long nativeReadLong(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readLong();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static float nativeReadFloat(int nativePtr) {
    return nativeReadFloat((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static float nativeReadFloat(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readFloat();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static double nativeReadDouble(int nativePtr) {
    return nativeReadDouble((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static double nativeReadDouble(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readDouble();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static String nativeReadString(int nativePtr) {
    return nativeReadString((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = Q)
  protected static String nativeReadString(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readString();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  protected static IBinder nativeReadStrongBinder(int nativePtr) {
    return nativeReadStrongBinder((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static IBinder nativeReadStrongBinder(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readStrongBinder();
  }

  @Implementation
  @HiddenApi
  public static Number nativeCreate() {
    return castNativePtr(NATIVE_BYTE_BUFFER_REGISTRY.register(new ByteBuffer()));
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeFreeBuffer(int nativePtr) {
    nativeFreeBuffer((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @SuppressWarnings("robolectric.ShadowReturnTypeMismatch")
  protected static void nativeFreeBuffer(long nativePtr) {
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).clear();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeDestroy(int nativePtr) {
    nativeDestroy((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeDestroy(long nativePtr) {
    NATIVE_BYTE_BUFFER_REGISTRY.unregister(nativePtr);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static byte[] nativeMarshall(int nativePtr) {
    return nativeMarshall((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static byte[] nativeMarshall(long nativePtr) {
    return NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).toByteArray();
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeUnmarshall(int nativePtr, byte[] data, int offset, int length) {
    nativeUnmarshall((long) nativePtr, data, offset, length);
  }

  @Implementation(minSdk = LOLLIPOP)
  @SuppressWarnings("robolectric.ShadowReturnTypeMismatch")
  protected static void nativeUnmarshall(long nativePtr, byte[] data, int offset, int length) {
    NATIVE_BYTE_BUFFER_REGISTRY.update(nativePtr, ByteBuffer.fromByteArray(data, offset, length));
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeAppendFrom(
      int thisNativePtr, int otherNativePtr, int offset, int length) {
    nativeAppendFrom((long) thisNativePtr, otherNativePtr, offset, length);
  }

  @Implementation(minSdk = LOLLIPOP)
  @SuppressWarnings("robolectric.ShadowReturnTypeMismatch")
  protected static void nativeAppendFrom(
      long thisNativePtr, long otherNativePtr, int offset, int length) {
    ByteBuffer thisByteBuffer = NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(thisNativePtr);
    ByteBuffer otherByteBuffer = NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(otherNativePtr);
    thisByteBuffer.appendFrom(otherByteBuffer, offset, length);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeWriteInterfaceToken(int nativePtr, String interfaceName) {
    nativeWriteInterfaceToken((long) nativePtr, interfaceName);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeWriteInterfaceToken(long nativePtr, String interfaceName) {
    // Write StrictMode.ThreadPolicy bits (assume 0 for test).
    nativeWriteInt(nativePtr, 0);
    nativeWriteString(nativePtr, interfaceName);
  }

  @HiddenApi
  @Implementation(maxSdk = KITKAT_WATCH)
  public static void nativeEnforceInterface(int nativePtr, String interfaceName) {
    nativeEnforceInterface((long) nativePtr, interfaceName);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected static void nativeEnforceInterface(long nativePtr, String interfaceName) {
    // Consume StrictMode.ThreadPolicy bits (don't bother setting in test).
    nativeReadInt(nativePtr);
    String actualInterfaceName = nativeReadString(nativePtr);
    if (!Objects.equals(interfaceName, actualInterfaceName)) {
      throw new SecurityException("Binder invocation to an incorrect interface");
    }
  }

  /**
   * Robolectric-specific error thrown when tests exercise error-prone behavior in Parcel.
   *
   * <p>Standard Android parcels rarely throw exceptions, but will happily behave in unintended
   * ways. Parcels are not strongly typed, so will happily re-interpret corrupt contents in ways
   * that cause hard-to-diagnose failures, or will cause tests to pass when they should not.
   * ShadowParcel attempts to detect these conditions.
   *
   * <p>This exception is package-private because production or test code should never catch or rely
   * on this, and may be changed to be an Error (rather than Exception) in the future.
   */
  static class UnreliableBehaviorError extends AssertionError {
    UnreliableBehaviorError(String message) {
      super(message);
    }

    UnreliableBehaviorError(String message, Throwable cause) {
      super(message, cause);
    }

    UnreliableBehaviorError(
        Class<?> clazz, int position, ByteBuffer.FakeEncodedItem item, String extraMessage) {
      super(
          String.format(
              Locale.US,
              "Looking for %s at position %d, found %s [%s] taking %d bytes, %s",
              clazz.getSimpleName(),
              position,
              item.value == null ? "null" : item.value.getClass().getSimpleName(),
              item.value,
              item.sizeBytes,
              extraMessage));
    }
  }

  /**
   * ByteBuffer pretends to be the underlying Parcel implementation.
   *
   * <p>It faithfully simulates Parcel's handling of position, size, and capacity, but is strongly
   * typed internally. It was debated whether this should instead faithfully represent Android's
   * Parcel bug-for-bug as a true byte array, along with all of its error-tolerant behavior and
   * ability essentially to {@code reinterpret_cast} data. However, the fail-fast behavior here has
   * found several test bugs and avoids reliance on architecture-specific details like Endian-ness.
   *
   * <p>Quirky behavior this explicitly emulates:
   *
   * <ul>
   *   <li>Continuing to read past the end returns zeros/nulls.
   *   <li>{@link setDataCapacity} never decreases buffer size.
   *   <li>It is possible to partially or completely overwrite byte ranges in the buffer.
   *   <li>Zero bytes can be exchanged between primitive data types and empty array/string.
   * </ul>
   *
   * <p>Quirky behavior this forbids:
   *
   * <ul>
   *   <li>Reading past the end after writing without calling setDataPosition(0), since there's no
   *       legitimate reason to do this, and is a very common test bug.
   *   <li>Writing one type and reading another; for example, writing a Long and reading two
   *       Integers, or writing a byte array and reading a String. This, effectively like {@code
   *       reinterpret_cast}, may not be portable across architectures.
   *   <li>Similarly, reading from objects that have been truncated or partially overwritten, or
   *       reading from the middle of them.
   *   <li>Using appendFrom to overwrite data, which in Parcel will overwrite the data <i>and</i>
   *       expand data size by the same amount, introducing empty gaps.
   *   <li>Reading from or marshalling buffers with uninitialized gaps (e.g. where data position was
   *       expanded but nothing was written)
   * </ul>
   *
   * <p>Possibly-unwanted divergent behavior:
   *
   * <ul>
   *   <li>Reading an object will often return the same instance that was written.
   *   <li>The marshalled form does not at all resemble Parcel's. This is to maintain compatibility
   *       with existing clients that rely on the Java-serialization-based format.
   *   <li>Uses substantially more memory, since each "byte" takes at minimum 4 bytes for a pointer,
   *       and even more for the overhead of allocating a record for each write. But note there is
   *       only at most one allocation for every 4 byte positions.
   * </ul>
   */
  private static class ByteBuffer {
    /** Number of bytes in Parcel used by an int, length, or anything smaller. */
    private static final int INT_SIZE_BYTES = 4;
    /** Number of bytes in Parcel used by a long or double. */
    private static final int LONG_OR_DOUBLE_SIZE_BYTES = 8;
    /** Immutable empty byte array. */
    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    /** Representation for an item that has been serialized in a parcel. */
    private static class FakeEncodedItem implements Serializable {
      /** Number of consecutive bytes consumed by this object. */
      final int sizeBytes;
      /** The original typed value stored. */
      final Object value;
      /**
       * Whether this item's byte-encoding is all zero.
       *
       * <p>This is the one exception to strong typing in ShadowParcel. Since zero can be portably
       * handled by many primitive types as zeros, and strings and arrays as empty. Note that when
       * zeroes are successfully read, the size of this entry may be ignored and the position may
       * progress to the middle of this, which remains safe as long as types that handle zeros are
       * used.
       */
      final boolean isEncodedAsAllZeroBytes;

      FakeEncodedItem(int sizeBytes, Object value) {
        this.sizeBytes = sizeBytes;
        this.value = value;
        this.isEncodedAsAllZeroBytes = isEncodedAsAllZeroBytes(value);
      }
    }

    /**
     * A type-safe simulation of the Parcel's data buffer.
     *
     * <p>Each index represents a byte of the parcel. Instead of storing raw bytes, this contains
     * records containing both the original data (in its original Java type) as well as the length.
     * Consecutive indices will point to the same FakeEncodedItem instance; for example, an item
     * with sizeBytes of 24 will, in normal cases, have references from 24 consecutive indices.
     *
     * <p>There are two main fail-fast features in this type-safe buffer. First, objects may only be
     * read from the parcel as the same type they were stored with, enforced by casting. Second,
     * this fails fast when reading incomplete or partially overwritten items.
     *
     * <p>Even though writing a custom resizable array is a code smell vs ArrayList, arrays' fixed
     * capacity closely models Parcel's dataCapacity (which we emulate anyway), and bulk array
     * utilities are robust compared to ArrayList's bulk operations.
     */
    private FakeEncodedItem[] data;
    /** The read/write pointer. */
    private int dataPosition;
    /** The length of the buffer; the capacity is data.length. */
    private int dataSize;
    /**
     * Whether the next read should fail if it's past the end of the array.
     *
     * <p>This is set true when modifying the end of the buffer, and cleared if a data position was
     * explicitly set.
     */
    private boolean failNextReadIfPastEnd;

    ByteBuffer() {
      clear();
    }

    /** Removes all elements from the byte buffer */
    public void clear() {
      data = new FakeEncodedItem[0];
      dataPosition = 0;
      dataSize = 0;
      failNextReadIfPastEnd = false;
    }

    /** Reads a byte array from the byte buffer based on the current data position */
    public byte[] createByteArray() {
      // It would be simpler just to store the byte array without a separate length.  However, the
      // "non-native" code in Parcel short-circuits null to -1, so this must consistently write a
      // separate length field in all cases.
      int length = readInt();
      if (length == -1) {
        return null;
      }
      if (length == 0) {
        return EMPTY_BYTE_ARRAY;
      }
      Object current = peek();
      if (current instanceof Byte) {
        // Legacy-encoded byte arrays (created by some tests) encode individual bytes, and do not
        // align to the integer.
        return readLegacyByteArray(length);
      } else if (readZeroes(alignToInt(length))) {
        return new byte[length];
      }
      byte[] result = readValue(EMPTY_BYTE_ARRAY, byte[].class, /* allowNull= */ false);
      if (result.length != length) {
        // Looks like the length doesn't correspond to the array.
        throw new UnreliableBehaviorError(
            String.format(
                Locale.US,
                "Byte array's length prefix is %d but real length is %d",
                length,
                result.length));
      }
      return result;
    }

    /** Reads a byte array encoded the way ShadowParcel previously encoded byte arrays. */
    private byte[] readLegacyByteArray(int length) {
      // Some tests rely on ShadowParcel's previous byte-by-byte encoding.
      byte[] result = new byte[length];
      for (int i = 0; i < length; i++) {
        result[i] = readPrimitive(1, (byte) 0, Byte.class);
      }
      return result;
    }

    /** Reads a byte array from the byte buffer based on the current data position */
    public boolean readByteArray(byte[] dest, int destLen) {
      byte[] result = createByteArray();
      if (result == null || destLen != result.length) {
        // Since older versions of Android (pre O MR1) don't call this method at all, let's be more
        // consistent with them and let android.os.Parcel throw RuntimeException, instead of
        // throwing a more helpful exception.
        return false;
      }
      System.arraycopy(result, 0, dest, 0, destLen);
      return true;
    }

    /**
     * Writes a byte array starting at offset for length bytes to the byte buffer at the current
     * data position
     */
    public void writeByteArray(byte[] b, int offset, int length) {
      writeInt(length);
      // Native parcel writes a byte array as length plus the individual bytes.  But we can't write
      // bytes individually because each byte would take up 4 bytes due to Parcel's alignment
      // behavior.  Instead we write the length, and if non-empty, we write the array.
      if (length != 0) {
        writeValue(length, Arrays.copyOfRange(b, offset, offset + length));
      }
    }

    /** Writes an int to the byte buffer at the current data position */
    public void writeInt(int i) {
      writeValue(INT_SIZE_BYTES, i);
    }

    /** Reads a int from the byte buffer based on the current data position */
    public int readInt() {
      return readPrimitive(INT_SIZE_BYTES, 0, Integer.class);
    }

    /** Writes a long to the byte buffer at the current data position */
    public void writeLong(long l) {
      writeValue(LONG_OR_DOUBLE_SIZE_BYTES, l);
    }

    /** Reads a long from the byte buffer based on the current data position */
    public long readLong() {
      return readPrimitive(LONG_OR_DOUBLE_SIZE_BYTES, 0L, Long.class);
    }

    /** Writes a float to the byte buffer at the current data position */
    public void writeFloat(float f) {
      writeValue(INT_SIZE_BYTES, f);
    }

    /** Reads a float from the byte buffer based on the current data position */
    public float readFloat() {
      return readPrimitive(INT_SIZE_BYTES, 0f, Float.class);
    }

    /** Writes a double to the byte buffer at the current data position */
    public void writeDouble(double d) {
      writeValue(LONG_OR_DOUBLE_SIZE_BYTES, d);
    }

    /** Reads a double from the byte buffer based on the current data position */
    public double readDouble() {
      return readPrimitive(LONG_OR_DOUBLE_SIZE_BYTES, 0d, Double.class);
    }

    /** Writes a String to the byte buffer at the current data position */
    public void writeString(String s) {
      int nullTerminatedChars = (s != null) ? (s.length() + 1) : 0;
      // Android encodes strings as length plus a null-terminated array of 2-byte characters.
      // writeValue will pad to nearest 4 bytes.  Null is encoded as just -1.
      int sizeBytes = INT_SIZE_BYTES + (nullTerminatedChars * 2);
      writeValue(sizeBytes, s);
    }

    /** Reads a String from the byte buffer based on the current data position */
    public String readString() {
      if (readZeroes(INT_SIZE_BYTES * 2)) {
        // Empty string is 4 bytes for length of 0, and 4 bytes for null terminator and padding.
        return "";
      }
      return readValue(null, String.class, /* allowNull= */ true);
    }

    /** Writes an IBinder to the byte buffer at the current data position */
    public void writeStrongBinder(IBinder b) {
      // Size of struct flat_binder_object in android/binder.h used to encode binders in the real
      // parceling code.
      int length = 5 * INT_SIZE_BYTES;
      writeValue(length, b);
    }

    /** Reads an IBinder from the byte buffer based on the current data position */
    public IBinder readStrongBinder() {
      return readValue(null, IBinder.class, /* allowNull= */ true);
    }

    /**
     * Appends the contents of the other byte buffer to this byte buffer starting at offset and
     * ending at length.
     *
     * @param other ByteBuffer to append to this one
     * @param offset number of bytes from beginning of byte buffer to start copy from
     * @param length number of bytes to copy
     */
    public void appendFrom(ByteBuffer other, int offset, int length) {
      int oldSize = dataSize;
      if (dataPosition != dataSize) {
        // Parcel.cpp will always expand the buffer by length even if it is overwriting existing
        // data, yielding extra uninitialized data at the end, in contrast to write methods that
        // won't increase the data length if they are overwriting in place.  This is surprising
        // behavior that production code should avoid.
        throw new UnreliableBehaviorError(
            "Real Android parcels behave unreliably if appendFrom is "
                + "called from any position other than the end");
      }
      setDataSize(oldSize + length);
      // Just blindly copy whatever happens to be in the buffer.  Reads will validate whether any
      // of the objects were only incompletely copied.
      System.arraycopy(other.data, offset, data, dataPosition, length);
      dataPosition += length;
      failNextReadIfPastEnd = true;
    }

    /** Returns whether a data type is encoded as all zeroes. */
    private static boolean isEncodedAsAllZeroBytes(Object value) {
      if (value == null) {
        return false; // Nulls are usually encoded as -1.
      }
      if (value instanceof Number) {
        Number number = (Number) value;
        return number.longValue() == 0 && number.doubleValue() == 0;
      }
      if (value instanceof byte[]) {
        byte[] array = (byte[]) value;
        return isAllZeroes(array, 0, array.length);
      }
      // NOTE: While empty string is all zeros, trying to read an empty string as zeroes is
      // probably unintended; the reverse is supported just so all-zero buffers don't fail.
      return false;
    }

    /** Identifies all zeroes, which can be safely reinterpreted to other types. */
    private static boolean isAllZeroes(byte[] array, int offset, int length) {
      for (int i = offset; i < length; i++) {
        if (array[i] != 0) {
          return false;
        }
      }
      return true;
    }

    /**
     * Creates a Byte buffer from a raw byte array.
     *
     * @param array byte array to read from
     * @param offset starting position in bytes to start reading array at
     * @param length number of bytes to read from array
     */
    @SuppressWarnings("BanSerializableRead")
    public static ByteBuffer fromByteArray(byte[] array, int offset, int length) {
      ByteBuffer byteBuffer = new ByteBuffer();

      if (isAllZeroes(array, offset, length)) {
        // Special case: for all zeroes, it's definitely not an ObjectInputStream, because it has a
        // non-zero mandatory magic.  Zeroes have a portable, unambiguous interpretation.
        byteBuffer.setDataSize(length);
        byteBuffer.writeItem(new FakeEncodedItem(length, new byte[length]));
        return byteBuffer;
      }

      try {
        ByteArrayInputStream bis = new ByteArrayInputStream(array, offset, length);
        ObjectInputStream ois = new ObjectInputStream(bis);
        int numElements = ois.readInt();
        for (int i = 0; i < numElements; i++) {
          int sizeOf = ois.readInt();
          Object value = ois.readObject();
          // NOTE: Bypassing writeValue so that this will support ShadowParcels that were
          // marshalled before ShadowParcel simulated alignment.
          byteBuffer.writeItem(new FakeEncodedItem(sizeOf, value));
        }
        // Android leaves the data position at the end in this case.
        return byteBuffer;
      } catch (Exception e) {
        throw new UnreliableBehaviorError("ShadowParcel unable to unmarshall its custom format", e);
      }
    }

    /**
     * Converts a ByteBuffer to a raw byte array. This method should be symmetrical with
     * fromByteArray.
     */
    public byte[] toByteArray() {
      int oldDataPosition = dataPosition;
      try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        // NOTE: Serializing the data array would be simpler, and serialization would actually
        // preserve reference equality between entries.  However, the length-encoded format here
        // preserves the previous format, which some tests appear to rely on.
        List<FakeEncodedItem> entries = new ArrayList<>();
        // NOTE: Use readNextItem to scan so the contents can be proactively validated.
        dataPosition = 0;
        while (dataPosition < dataSize) {
          entries.add(readNextItem(Object.class));
        }
        oos.writeInt(entries.size());
        for (FakeEncodedItem item : entries) {
          oos.writeInt(item.sizeBytes);
          oos.writeObject(item.value);
        }
        oos.flush();
        return bos.toByteArray();
      } catch (IOException e) {
        throw new UnreliableBehaviorError("ErrorProne unable to serialize its custom format", e);
      } finally {
        dataPosition = oldDataPosition;
      }
    }

    /** Number of unused bytes in this byte buffer. */
    public int dataAvailable() {
      return dataSize() - dataPosition();
    }

    /** Total buffer size in bytes of byte buffer included unused space. */
    public int dataCapacity() {
      return data.length;
    }

    /** Current data position of byte buffer in bytes. Reads / writes are from this position. */
    public int dataPosition() {
      return dataPosition;
    }

    /** Current amount of bytes currently written for ByteBuffer. */
    public int dataSize() {
      return dataSize;
    }

    /**
     * Sets the current data position.
     *
     * @param pos Desired position in bytes
     */
    public void setDataPosition(int pos) {
      if (pos > dataSize) {
        // NOTE: Real parcel ignores this until a write occurs.
        throw new UnreliableBehaviorError(pos + " greater than dataSize " + dataSize);
      }
      dataPosition = pos;
      failNextReadIfPastEnd = false;
    }

    public void setDataSize(int size) {
      if (size < dataSize) {
        // Clear all the inaccessible bytes when shrinking, to allow garbage collection, and so
        // they remain cleared if expanded again.  Note this might truncate something mid-object,
        // which would be handled at read time.
        Arrays.fill(data, size, dataSize, null);
      }
      setDataCapacityAtLeast(size);
      dataSize = size;
      if (dataPosition >= dataSize) {
        dataPosition = dataSize;
      }
    }

    public void setDataCapacityAtLeast(int newCapacity) {
      // NOTE: Oddly, Parcel only every increases data capacity, and never decreases it, so this
      // really should have never been named setDataCapacity.
      if (newCapacity > data.length) {
        FakeEncodedItem[] newData = new FakeEncodedItem[newCapacity];
        dataSize = Math.min(dataSize, newCapacity);
        dataPosition = Math.min(dataPosition, dataSize);
        System.arraycopy(data, 0, newData, 0, dataSize);
        data = newData;
      }
    }

    /** Rounds to next 4-byte bounder similar to native Parcel. */
    private int alignToInt(int unpaddedSizeBytes) {
      return ((unpaddedSizeBytes + 3) / 4) * 4;
    }

    /**
     * Ensures that the next sizeBytes are all the initial value we read.
     *
     * <p>This detects:
     *
     * <ul>
     *   <li>Reading an item, but not starting at its start position
     *   <li>Reading items that were truncated by setSize
     *   <li>Reading items that were partially overwritten by another
     * </ul>
     */
    private void checkConsistentReadAndIncrementPosition(Class<?> clazz, FakeEncodedItem item) {
      int endPosition = dataPosition + item.sizeBytes;
      for (int i = dataPosition; i < endPosition; i++) {
        FakeEncodedItem foundItemItem = i < dataSize ? data[i] : null;
        if (foundItemItem != item) {
          throw new UnreliableBehaviorError(
              clazz,
              dataPosition,
              item,
              String.format(
                  Locale.US,
                  "but [%s] interrupts it at position %d",
                  foundItemItem == null
                      ? "uninitialized data or the end of the buffer"
                      : foundItemItem.value,
                  i));
        }
      }
      dataPosition = Math.min(dataSize, dataPosition + item.sizeBytes);
    }

    /** Returns the item at the current position, or null if uninitialized or null. */
    private Object peek() {
      return dataPosition < dataSize && data[dataPosition] != null
          ? data[dataPosition].value
          : null;
    }

    /**
     * Reads a complete item in the byte buffer.
     *
     * @param clazz this is the type that is being read, but not checked in this method
     * @return null if the default value should be returned, otherwise the item holding the data
     */
    private <T> FakeEncodedItem readNextItem(Class<T> clazz) {
      FakeEncodedItem item = data[dataPosition];
      if (item == null) {
        // While Parcel will treat these as zeros, in tests, this is almost always an error.
        throw new UnreliableBehaviorError("Reading uninitialized data at position " + dataPosition);
      }
      checkConsistentReadAndIncrementPosition(clazz, item);
      return item;
    }

    /**
     * Reads the next value in the byte buffer of a specified type.
     *
     * @param pastEndValue value to return when reading past the end of the buffer
     * @param clazz this is the type that is being read, but not checked in this method
     * @param allowNull whether null values are permitted
     */
    private <T> T readValue(T pastEndValue, Class<T> clazz, boolean allowNull) {
      if (dataPosition >= dataSize) {
        // Normally, reading past the end is permitted, and returns the default values.  However,
        // writing to a parcel then reading without setting the position back to 0 is an incredibly
        // common error to make in tests, and should never really happen in production code, so
        // this shadow will fail in this condition.
        if (failNextReadIfPastEnd) {
          throw new UnreliableBehaviorError(
              "Did you forget to setDataPosition(0) before reading the parcel?");
        }
        return pastEndValue;
      }
      int startPosition = dataPosition;
      FakeEncodedItem item = readNextItem(clazz);
      if (item == null) {
        return pastEndValue;
      } else if (item.value == null && allowNull) {
        return null;
      } else if (clazz.isInstance(item.value)) {
        return clazz.cast(item.value);
      } else {
        // Numerous existing tests rely on ShadowParcel throwing RuntimeException and catching
        // them.  Many of these tests are trying to test what happens when an invalid Parcel is
        // provided.  However, Android has no concept of an "invalid parcel" because Parcel will
        // happily return garbage if you ask for it.  The only runtime exceptions are thrown on
        // array length mismatches, or higher-level APIs like Parcelable (which has its own safety
        // checks).  Tests trying to test error-handling behavior should instead craft a Parcel
        // that specifically triggers a BadParcelableException.
        throw new RuntimeException(
            new UnreliableBehaviorError(
                clazz, startPosition, item, "and it is non-portable to reinterpret it"));
      }
    }

    /**
     * Determines if there is a sequence of castable zeroes, and consumes them.
     *
     * <p>This is the only exception for strong typing, because zero bytes are portable and
     * unambiguous. There are a few situations where well-written code can rely on this, so it is
     * worthwhile making a special exception for. This tolerates partially-overwritten and truncated
     * values if all bytes are zero.
     */
    private boolean readZeroes(int bytes) {
      int endPosition = dataPosition + bytes;
      if (endPosition > dataSize) {
        return false;
      }
      for (int i = dataPosition; i < endPosition; i++) {
        if (data[i] == null || !data[i].isEncodedAsAllZeroBytes) {
          return false;
        }
      }
      // Note in this case we short-circuit other verification -- even if we are reading weirdly
      // clobbered zeroes, they're still zeroes.  Future reads might fail, though.
      dataPosition = endPosition;
      return true;
    }

    /**
     * Reads a primitive, which may reinterpret zeros of other types.
     *
     * @param defaultSizeBytes if reinterpreting zeros, the number of bytes to consume
     * @param defaultValue the default value for zeros or reading past the end
     * @param clazz this is the type that is being read, but not checked in this method
     */
    private <T> T readPrimitive(int defaultSizeBytes, T defaultValue, Class<T> clazz) {
      // Check for zeroes first, since partially-overwritten values are not an error for zeroes.
      if (readZeroes(defaultSizeBytes)) {
        return defaultValue;
      }
      return readValue(defaultValue, clazz, /* allowNull= */ false);
    }

    /** Writes an encoded item directly, bypassing alignment, and possibly repeating an item. */
    private void writeItem(FakeEncodedItem item) {
      int endPosition = dataPosition + item.sizeBytes;
      if (endPosition > data.length) {
        // Parcel grows by 3/2 of the new size.
        setDataCapacityAtLeast(endPosition * 3 / 2);
      }
      if (endPosition > dataSize) {
        failNextReadIfPastEnd = true;
        dataSize = endPosition;
      }
      Arrays.fill(data, dataPosition, endPosition, item);
      dataPosition = endPosition;
    }

    /**
     * Writes a value to the next range of bytes.
     *
     * <p>Writes are aligned to 4-byte regions.
     */
    private void writeValue(int unpaddedSizeBytes, Object o) {
      // Create the item with its final, aligned byte size.
      writeItem(new FakeEncodedItem(alignToInt(unpaddedSizeBytes), o));
    }
  }

  @Implementation(maxSdk = P)
  protected static FileDescriptor openFileDescriptor(String file, int mode) throws IOException {
    RandomAccessFile randomAccessFile =
        new RandomAccessFile(file, mode == ParcelFileDescriptor.MODE_READ_ONLY ? "r" : "rw");
    return randomAccessFile.getFD();
  }

  @Implementation(minSdk = M, maxSdk = R)
  protected static long nativeWriteFileDescriptor(long nativePtr, FileDescriptor val) {
    // The Java version of FileDescriptor stored the fd in a field called "fd", and the Android
    // version changed the field name to "descriptor". But it looks like Robolectric uses the
    // Java version of FileDescriptor instead of the Android version.
    int fd = ReflectionHelpers.getField(val, "fd");
    NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).writeInt(fd);
    return (long) nativeDataPosition(nativePtr);
  }

  @Implementation(minSdk = M)
  protected static FileDescriptor nativeReadFileDescriptor(long nativePtr) {
    int fd = NATIVE_BYTE_BUFFER_REGISTRY.getNativeObject(nativePtr).readInt();
    return ReflectionHelpers.callConstructor(
        FileDescriptor.class, ClassParameter.from(int.class, fd));
  }

  @Implementation(minSdk = R)
  protected static void nativeWriteString8(long nativePtr, String val) {
    nativeWriteString(nativePtr, val);
  }

  @Implementation(minSdk = R)
  protected static void nativeWriteString16(long nativePtr, String val) {
    nativeWriteString(nativePtr, val);
  }

  @Implementation(minSdk = R)
  protected static String nativeReadString8(long nativePtr) {
    return nativeReadString(nativePtr);
  }

  @Implementation(minSdk = R)
  protected static String nativeReadString16(long nativePtr) {
    return nativeReadString(nativePtr);
  }

  // need to use looseSignatures for the S methods because method signatures differ only by return
  // type
  @Implementation(minSdk = S)
  protected static int nativeWriteInt(Object nativePtr, Object val) {
    nativeWriteInt((long) nativePtr, (int) val);
    return 0; /* OK */
  }

  @Implementation(minSdk = S)
  protected static int nativeWriteLong(Object nativePtr, Object val) {
    nativeWriteLong((long) nativePtr, (long) val);
    return 0; /* OK */
  }

  @Implementation(minSdk = S)
  protected static int nativeWriteFloat(Object nativePtr, Object val) {
    nativeWriteFloat((long) nativePtr, (float) val);
    return 0; /* OK */
  }

  @Implementation(minSdk = S)
  protected static int nativeWriteDouble(Object nativePtr, Object val) {
    nativeWriteDouble((long) nativePtr, (double) val);
    return 0; /* OK */
  }

  @Implementation(minSdk = S)
  protected static void nativeWriteFileDescriptor(Object nativePtr, Object val) {
    nativeWriteFileDescriptor((long) nativePtr, (FileDescriptor) val);
  }

  @Resetter
  public static void reset() {
    pairedCreators.clear();
  }
}