1 /*
2  * Copyright (C) 2024 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.google.snippet.wifi.aware;
17 
18 import android.os.Parcel;
19 import android.os.Parcelable;
20 import android.util.Base64;
21 
22 /**
23  * Utility class for serializing and deserializing Parcel and Serializable objects to and from
24  * Strings.
25  */
26 public class SerializationUtil {
27 
28 
29     /**
30      * Serializes a Parcelable object to a Base64 encoded string.
31      *
32      * @param parcelable The Parcelable object to serialize.
33      * @return Base64 encoded string of the serialized Parcelable object.
34      */
parcelableToString(Parcelable parcelable)35     public static String parcelableToString(Parcelable parcelable) {
36         Parcel parcel = Parcel.obtain();
37         parcelable.writeToParcel(parcel, 0); // Ensure this object implements Parcelable
38         byte[] bytes = parcel.marshall(); // Convert the Parcel into a byte array
39         parcel.recycle(); // Recycle the Parcel to free up resources
40         return Base64.encodeToString(bytes, Base64.DEFAULT);
41     }
42 
43     /**
44      * Deserializes a Base64 encoded string back into a Parcelable object.
45      *
46      * @param input   The Base64 encoded string of the serialized Parcelable object.
47      * @param creator The CREATOR field of the Parcelable object, used to recreate the object.
48      * @param <T>     The type of the Parcelable object.
49      * @return A Parcelable object recreated from the string.
50      */
stringToParcelable(String input, Parcelable.Creator<T> creator)51     public static <T> T stringToParcelable(String input, Parcelable.Creator<T> creator) {
52         byte[] bytes = Base64.decode(input, Base64.DEFAULT);
53         Parcel parcel = Parcel.obtain();
54         parcel.unmarshall(bytes, 0, bytes.length); // Unmarshall the byte array into a Parcel
55         parcel.setDataPosition(0); // Reset the position to the start of the Parcel data
56         T result = creator.createFromParcel(parcel); // Recreate the Parcelable object
57         parcel.recycle(); // Recycle the Parcel to free up resources
58         return result;
59     }
60 }
61