Utils.java revision f151a7b3377e956fedd4f3e63afc880c35310219
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 17package android.hardware.radio; 18 19import android.annotation.NonNull; 20import android.annotation.Nullable; 21import android.os.Parcel; 22import android.os.Parcelable; 23import android.os.RemoteException; 24 25import java.util.HashMap; 26import java.util.HashSet; 27import java.util.Map; 28import java.util.Objects; 29import java.util.Set; 30 31final class Utils { 32 private static final String TAG = "BroadcastRadio.utils"; 33 34 static void writeStringMap(@NonNull Parcel dest, @Nullable Map<String, String> map) { 35 if (map == null) { 36 dest.writeInt(0); 37 return; 38 } 39 dest.writeInt(map.size()); 40 for (Map.Entry<String, String> entry : map.entrySet()) { 41 dest.writeString(entry.getKey()); 42 dest.writeString(entry.getValue()); 43 } 44 } 45 46 static @NonNull Map<String, String> readStringMap(@NonNull Parcel in) { 47 int size = in.readInt(); 48 Map<String, String> map = new HashMap<>(); 49 while (size-- > 0) { 50 String key = in.readString(); 51 String value = in.readString(); 52 map.put(key, value); 53 } 54 return map; 55 } 56 57 static <T extends Parcelable> void writeSet(@NonNull Parcel dest, @Nullable Set<T> set) { 58 if (set == null) { 59 dest.writeInt(0); 60 return; 61 } 62 dest.writeInt(set.size()); 63 set.stream().forEach(elem -> dest.writeTypedObject(elem, 0)); 64 } 65 66 static <T> Set<T> createSet(@NonNull Parcel in, Parcelable.Creator<T> c) { 67 int size = in.readInt(); 68 Set<T> set = new HashSet<>(); 69 while (size-- > 0) { 70 set.add(in.readTypedObject(c)); 71 } 72 return set; 73 } 74 75 static void writeIntSet(@NonNull Parcel dest, @Nullable Set<Integer> set) { 76 if (set == null) { 77 dest.writeInt(0); 78 return; 79 } 80 dest.writeInt(set.size()); 81 set.stream().forEach(elem -> dest.writeInt(Objects.requireNonNull(elem))); 82 } 83 84 static Set<Integer> createIntSet(@NonNull Parcel in) { 85 return createSet(in, new Parcelable.Creator<Integer>() { 86 public Integer createFromParcel(Parcel in) { 87 return in.readInt(); 88 } 89 90 public Integer[] newArray(int size) { 91 return new Integer[size]; 92 } 93 }); 94 } 95 96 static void close(ICloseHandle handle) { 97 try { 98 handle.close(); 99 } catch (RemoteException ex) { 100 ex.rethrowFromSystemServer(); 101 } 102 } 103} 104