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 /** Immutable set with index-based access, implemented using a list. */
20 sealed class IndexedListSet<T>(internal val list: ArrayList<T>) :
21     Immutable<MutableIndexedListSet<T>> {
22     val size: Int
23         get() = list.size
24 
isEmptynull25     fun isEmpty(): Boolean = list.isEmpty()
26 
27     operator fun contains(element: T): Boolean = list.contains(element)
28 
29     fun indexOf(element: T): Int = list.indexOf(element)
30 
31     @Suppress("ReplaceGetOrSet") fun elementAt(index: Int): T = list.get(index)
32 
33     override fun toMutable(): MutableIndexedListSet<T> = MutableIndexedListSet(this)
34 
35     override fun toString(): String = list.toString()
36 }
37 
38 /** Mutable set with index-based access, implemented using a list. */
39 class MutableIndexedListSet<T>(list: ArrayList<T> = ArrayList()) : IndexedListSet<T>(list) {
40     constructor(indexedListSet: IndexedListSet<T>) : this(ArrayList(indexedListSet.list))
41 
42     fun add(element: T): Boolean =
43         if (list.contains(element)) {
44             false
45         } else {
46             list.add(element)
47             true
48         }
49 
50     fun remove(element: T): Boolean = list.remove(element)
51 
52     fun clear() {
53         list.clear()
54     }
55 
56     fun removeAt(index: Int): T = list.removeAt(index)
57 }
58