1 /*
<lambda>null2 * 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.ArraySet
20 import com.android.server.permission.access.collection.forEachIndexed
21
22 fun <T> indexedSetOf(vararg elements: T): IndexedSet<T> =
23 MutableIndexedSet(ArraySet(elements.asList()))
24
25 inline fun <T> IndexedSet<T>.allIndexed(predicate: (Int, T) -> Boolean): Boolean {
26 forEachIndexed { index, element ->
27 if (!predicate(index, element)) {
28 return false
29 }
30 }
31 return true
32 }
33
anyIndexednull34 inline fun <T> IndexedSet<T>.anyIndexed(predicate: (Int, T) -> Boolean): Boolean {
35 forEachIndexed { index, element ->
36 if (predicate(index, element)) {
37 return true
38 }
39 }
40 return false
41 }
42
forEachIndexednull43 inline fun <T> IndexedSet<T>.forEachIndexed(action: (Int, T) -> Unit) {
44 for (index in 0 until size) {
45 action(index, elementAt(index))
46 }
47 }
48
forEachReversedIndexednull49 inline fun <T> IndexedSet<T>.forEachReversedIndexed(action: (Int, T) -> Unit) {
50 for (index in lastIndex downTo 0) {
51 action(index, elementAt(index))
52 }
53 }
54
55 inline val <T> IndexedSet<T>.lastIndex: Int
56 get() = size - 1
57
minusnull58 operator fun <T> IndexedSet<T>.minus(element: T): MutableIndexedSet<T> =
59 toMutable().apply { this -= element }
60
noneIndexednull61 inline fun <T> IndexedSet<T>.noneIndexed(predicate: (Int, T) -> Boolean): Boolean {
62 forEachIndexed { index, element ->
63 if (predicate(index, element)) {
64 return false
65 }
66 }
67 return true
68 }
69
plusnull70 operator fun <T> IndexedSet<T>.plus(element: T): MutableIndexedSet<T> =
71 toMutable().apply { this += element }
72
73 @Suppress("NOTHING_TO_INLINE")
minusAssignnull74 inline operator fun <T> MutableIndexedSet<T>.minusAssign(element: T) {
75 remove(element)
76 }
77
78 @Suppress("NOTHING_TO_INLINE")
plusAssignnull79 inline operator fun <T> MutableIndexedSet<T>.plusAssign(element: T) {
80 add(element)
81 }
82
plusAssignnull83 operator fun <T> MutableIndexedSet<T>.plusAssign(collection: Collection<T>) {
84 collection.forEach { this += it }
85 }
86