1 /*
2  * Copyright (C) 2016 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.car.hal;
17 
18 import android.util.SparseIntArray;
19 
20 /**
21  * Helper class that maintains bi-directional mapping between int values.
22  *
23  * <p>This class is immutable. Use {@link #create(int[])} factory method to instantiate this class.
24  */
25 class BidirectionalSparseIntArray {
26     private final SparseIntArray mMap;
27     private final SparseIntArray mInverseMap;
28 
29     /**
30      * Creates {@link BidirectionalSparseIntArray} for provided int pairs.
31      *
32      * <p> The input array should have an even number of elements.
33      */
create(int[] keyValuePairs)34     static BidirectionalSparseIntArray create(int[] keyValuePairs) {
35         int inputLength = keyValuePairs.length;
36         if (inputLength % 2 != 0) {
37             throw new IllegalArgumentException("Odd number of key-value elements");
38         }
39 
40         BidirectionalSparseIntArray biMap = new BidirectionalSparseIntArray(inputLength / 2);
41         for (int i = 0; i < keyValuePairs.length; i += 2) {
42             biMap.put(keyValuePairs[i], keyValuePairs[i + 1]);
43         }
44         return biMap;
45     }
46 
BidirectionalSparseIntArray(int initialCapacity)47     private BidirectionalSparseIntArray(int initialCapacity) {
48         mMap = new SparseIntArray(initialCapacity);
49         mInverseMap = new SparseIntArray(initialCapacity);
50     }
51 
put(int key, int value)52     private void put(int key, int value) {
53         mMap.put(key, value);
54         mInverseMap.put(value, key);
55     }
56 
getValue(int key, int defaultValue)57     int getValue(int key, int defaultValue) {
58         return mMap.get(key, defaultValue);
59     }
60 
getKey(int value, int defaultKey)61     int getKey(int value, int defaultKey) {
62         return mInverseMap.get(value, defaultKey);
63     }
64 }
65