1 /*
2  * Copyright (C) 2018 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 package com.android.compatibility.common.util;
17 
18 import static org.junit.Assert.assertNotNull;
19 
20 import android.os.Parcel;
21 import android.os.Parcelable;
22 
23 public class ParcelUtils {
ParcelUtils()24     private ParcelUtils() {
25     }
26 
27     /** Convert a Parcelable into a byte[]. */
toBytes(Parcelable p)28     public static byte[] toBytes(Parcelable p) {
29         assertNotNull(p);
30 
31         final Parcel parcel = Parcel.obtain();
32         parcel.writeParcelable(p, 0);
33         byte[] data = parcel.marshall();
34         parcel.recycle();
35 
36         return data;
37     }
38 
39     /** Decode a byte[] into a Parcelable. */
fromBytes(byte[] data)40     public static <T extends Parcelable> T fromBytes(byte[] data) {
41         assertNotNull(data);
42 
43         final Parcel parcel = Parcel.obtain();
44         parcel.unmarshall(data, 0, data.length);
45         parcel.setDataPosition(0);
46         T ret = parcel.readParcelable(ParcelUtils.class.getClassLoader());
47         parcel.recycle();
48 
49         return ret;
50     }
51 }
52