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.server.permission.access.immutable
18 
19 import android.util.ArrayMap
20 
21 /** Immutable map with index-based access. */
22 sealed class IndexedMap<K, V>(internal val map: ArrayMap<K, V>) :
23     Immutable<MutableIndexedMap<K, V>> {
24     val size: Int
25         get() = map.size
26 
isEmptynull27     fun isEmpty(): Boolean = map.isEmpty()
28 
29     operator fun contains(key: K): Boolean = map.containsKey(key)
30 
31     @Suppress("ReplaceGetOrSet") operator fun get(key: K): V? = map.get(key)
32 
33     fun indexOfKey(key: K): Int = map.indexOfKey(key)
34 
35     fun keyAt(index: Int): K = map.keyAt(index)
36 
37     fun valueAt(index: Int): V = map.valueAt(index)
38 
39     override fun toMutable(): MutableIndexedMap<K, V> = MutableIndexedMap(this)
40 
41     override fun toString(): String = map.toString()
42 }
43 
44 /** Mutable map with index-based access. */
45 class MutableIndexedMap<K, V>(map: ArrayMap<K, V> = ArrayMap()) : IndexedMap<K, V>(map) {
46     constructor(indexedMap: IndexedMap<K, V>) : this(ArrayMap(indexedMap.map))
47 
48     fun put(key: K, value: V): V? = map.put(key, value)
49 
50     fun remove(key: K): V? = map.remove(key)
51 
52     fun clear() {
53         map.clear()
54     }
55 
56     fun putAt(index: Int, value: V): V = map.setValueAt(index, value)
57 
58     fun removeAt(index: Int): V = map.removeAt(index)
59 }
60