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 inline fun <T> IndexedListSet<T>.allIndexed(predicate: (Int, T) -> Boolean): Boolean {
20 forEachIndexed { index, element ->
21 if (!predicate(index, element)) {
22 return false
23 }
24 }
25 return true
26 }
27
anyIndexednull28 inline fun <T> IndexedListSet<T>.anyIndexed(predicate: (Int, T) -> Boolean): Boolean {
29 forEachIndexed { index, element ->
30 if (predicate(index, element)) {
31 return true
32 }
33 }
34 return false
35 }
36
forEachIndexednull37 inline fun <T> IndexedListSet<T>.forEachIndexed(action: (Int, T) -> Unit) {
38 for (index in 0 until size) {
39 action(index, elementAt(index))
40 }
41 }
42
forEachReversedIndexednull43 inline fun <T> IndexedListSet<T>.forEachReversedIndexed(action: (Int, T) -> Unit) {
44 for (index in lastIndex downTo 0) {
45 action(index, elementAt(index))
46 }
47 }
48
49 inline val <T> IndexedListSet<T>.lastIndex: Int
50 get() = size - 1
51
minusnull52 operator fun <T> IndexedListSet<T>.minus(element: T): MutableIndexedListSet<T> =
53 toMutable().apply { this -= element }
54
noneIndexednull55 inline fun <T> IndexedListSet<T>.noneIndexed(predicate: (Int, T) -> Boolean): Boolean {
56 forEachIndexed { index, element ->
57 if (predicate(index, element)) {
58 return false
59 }
60 }
61 return true
62 }
63
plusnull64 operator fun <T> IndexedListSet<T>.plus(element: T): MutableIndexedListSet<T> =
65 toMutable().apply { this += element }
66
67 // Using Int instead of <R> to avoid autoboxing, since we only have the use case for Int.
reduceIndexednull68 inline fun <T> IndexedListSet<T>.reduceIndexed(
69 initialValue: Int,
70 accumulator: (Int, Int, T) -> Int
71 ): Int {
72 var value = initialValue
73 forEachIndexed { index, element -> value = accumulator(value, index, element) }
74 return value
75 }
76
77 @Suppress("NOTHING_TO_INLINE")
minusAssignnull78 inline operator fun <T> MutableIndexedListSet<T>.minusAssign(element: T) {
79 remove(element)
80 }
81
82 @Suppress("NOTHING_TO_INLINE")
plusAssignnull83 inline operator fun <T> MutableIndexedListSet<T>.plusAssign(element: T) {
84 add(element)
85 }
86