1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.documentsui.testing;
18 
19 import static junit.framework.Assert.assertEquals;
20 import static junit.framework.Assert.assertTrue;
21 
22 import android.os.Parcel;
23 import android.os.Parcelable;
24 
25 import java.util.function.BiPredicate;
26 
27 public class Parcelables {
28 
Parcelables()29     private Parcelables() {}
30 
assertParcelable(T p, int flags)31     public static <T extends Parcelable> void assertParcelable(T p, int flags) {
32         final T restored = parcel(p, flags);
33 
34         assertEquals(p, restored);
35     }
36 
assertParcelable( T p, int flags, BiPredicate<T, T> pred)37     public static <T extends Parcelable> void assertParcelable(
38             T p, int flags, BiPredicate<T, T> pred) {
39         T restored = parcel(p, flags);
40 
41         assertTrue(pred.test(p, restored));
42     }
43 
parcel(T p, int flags)44     private static <T extends Parcelable> T parcel(T p, int flags) {
45         Parcel write = Parcel.obtain();
46         Parcel read = Parcel.obtain();
47         final T restored;
48         try {
49             write.writeParcelable(p, flags);
50             final byte[] data = write.marshall();
51 
52             read.unmarshall(data, 0, data.length);
53             read.setDataPosition(0);
54             restored = read.readParcelable(p.getClass().getClassLoader());
55         } finally {
56             write.recycle();
57             read.recycle();
58         }
59 
60         return restored;
61     }
62 }
63