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.SparseBooleanArray 20 21 /** Immutable set with index-based access and [Int] elements. */ 22 sealed class IntSet(internal val array: SparseBooleanArray) : Immutable<MutableIntSet> { 23 val size: Int 24 get() = array.size() 25 isEmptynull26 fun isEmpty(): Boolean = array.size() == 0 27 28 operator fun contains(element: Int): Boolean = array.contains(element) 29 30 fun indexOf(element: Int): Int = array.indexOfKey(element) 31 32 fun elementAt(index: Int): Int = array.keyAt(index) 33 34 override fun toMutable(): MutableIntSet = MutableIntSet(this) 35 36 override fun toString(): String = array.toString() 37 } 38 39 /** Mutable set with index-based access and [Int] elements. */ 40 class MutableIntSet(array: SparseBooleanArray = SparseBooleanArray()) : IntSet(array) { 41 constructor(intSet: IntSet) : this(intSet.array.clone()) 42 43 fun add(element: Int): Boolean = 44 if (array.contains(element)) { 45 false 46 } else { 47 array.put(element, true) 48 true 49 } 50 51 fun remove(element: Int): Boolean { 52 val index = array.indexOfKey(element) 53 return if (index >= 0) { 54 array.removeAt(index) 55 true 56 } else { 57 false 58 } 59 } 60 61 fun clear() { 62 array.clear() 63 } 64 65 fun removeAt(index: Int) { 66 array.removeAt(index) 67 } 68 } 69 70 // Unlike SparseArray, SparseBooleanArray is missing this method. containsnull71private fun SparseBooleanArray.contains(key: Int): Boolean = indexOfKey(key) >= 0 72