1 /*
2  * Copyright (C) 2023 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.ondevicepersonalization.services.util;
18 
19 import android.os.Parcel;
20 import android.os.Parcelable;
21 
22 import java.io.Serializable;
23 
24 /**
25  * A Serializable wrapper for a Parcelable object.
26  * @param <T> a parcelable type
27  */
28 public class ParcelWrapper<T extends Parcelable> implements Serializable {
29     private final byte[] mParcelBytes;
30 
31     /** Wraps a Parcelable in a Serializable */
ParcelWrapper(T value)32     public ParcelWrapper(T value) {
33         if (value == null) {
34             mParcelBytes = null;
35         } else {
36             Parcel parcel = Parcel.obtain();
37             value.writeToParcel(parcel, 0);
38             mParcelBytes = parcel.marshall();
39         }
40     }
41 
42     /** Unwraps the Parcelable. */
get(Parcelable.Creator<T> creator)43     public T get(Parcelable.Creator<T> creator) {
44         if (mParcelBytes == null) {
45             return null;
46         } else {
47             Parcel parcel = Parcel.obtain();
48             parcel.unmarshall(mParcelBytes, 0, mParcelBytes.length);
49             parcel.setDataPosition(0);
50             return creator.createFromParcel(parcel);
51         }
52     }
53 }
54