• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 android.net.shared;
18 
19 import android.annotation.NonNull;
20 
21 import java.lang.reflect.Array;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.function.Function;
25 
26 /**
27  * Utility methods to help convert to/from stable parcelables.
28  * @hide
29  */
30 public final class ParcelableUtil {
31     // Below methods could be implemented easily with streams, but streams are frowned upon in
32     // frameworks code.
33 
34     /**
35      * Convert a list of BaseType items to an array of ParcelableType items using the specified
36      * converter function.
37      */
toParcelableArray( @onNull Collection<BaseType> base, @NonNull Function<BaseType, ParcelableType> conv, @NonNull Class<ParcelableType> parcelClass)38     public static <ParcelableType, BaseType> ParcelableType[] toParcelableArray(
39             @NonNull Collection<BaseType> base,
40             @NonNull Function<BaseType, ParcelableType> conv,
41             @NonNull Class<ParcelableType> parcelClass) {
42         final ParcelableType[] out = (ParcelableType[]) Array.newInstance(parcelClass, base.size());
43         int i = 0;
44         for (BaseType b : base) {
45             out[i] = conv.apply(b);
46             i++;
47         }
48         return out;
49     }
50 
51     /**
52      * Convert an array of ParcelableType items to a list of BaseType items using the specified
53      * converter function.
54      */
fromParcelableArray( @onNull ParcelableType[] parceled, @NonNull Function<ParcelableType, BaseType> conv)55     public static <ParcelableType, BaseType> ArrayList<BaseType> fromParcelableArray(
56             @NonNull ParcelableType[] parceled, @NonNull Function<ParcelableType, BaseType> conv) {
57         final ArrayList<BaseType> out = new ArrayList<>(parceled.length);
58         for (ParcelableType t : parceled) {
59             out.add(conv.apply(t));
60         }
61         return out;
62     }
63 }
64