1 /*
<lambda>null2 * Copyright (C) 2022 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.collection
18
19 import android.util.SparseArray
20
21 inline fun <T> SparseArray<T>.allIndexed(predicate: (Int, Int, T) -> Boolean): Boolean {
22 forEachIndexed { index, key, value ->
23 if (!predicate(index, key, value)) {
24 return false
25 }
26 }
27 return true
28 }
29
anyIndexednull30 inline fun <T> SparseArray<T>.anyIndexed(predicate: (Int, Int, T) -> Boolean): Boolean {
31 forEachIndexed { index, key, value ->
32 if (predicate(index, key, value)) {
33 return true
34 }
35 }
36 return false
37 }
38
forEachIndexednull39 inline fun <T> SparseArray<T>.forEachIndexed(action: (Int, Int, T) -> Unit) {
40 for (index in 0 until size) {
41 action(index, keyAt(index), valueAt(index))
42 }
43 }
44
forEachReversedIndexednull45 inline fun <T> SparseArray<T>.forEachReversedIndexed(action: (Int, Int, T) -> Unit) {
46 for (index in lastIndex downTo 0) {
47 action(index, keyAt(index), valueAt(index))
48 }
49 }
50
getOrPutnull51 inline fun <T> SparseArray<T>.getOrPut(key: Int, defaultValue: () -> T): T {
52 val index = indexOfKey(key)
53 return if (index >= 0) {
54 valueAt(index)
55 } else {
56 defaultValue().also { put(key, it) }
57 }
58 }
59
60 inline val <T> SparseArray<T>.lastIndex: Int
61 get() = size - 1
62
63 @Suppress("NOTHING_TO_INLINE")
minusAssignnull64 inline operator fun <T> SparseArray<T>.minusAssign(key: Int) {
65 delete(key)
66 }
67
noneIndexednull68 inline fun <T> SparseArray<T>.noneIndexed(predicate: (Int, Int, T) -> Boolean): Boolean {
69 forEachIndexed { index, key, value ->
70 if (predicate(index, key, value)) {
71 return false
72 }
73 }
74 return true
75 }
76
removeAllIndexednull77 inline fun <T> SparseArray<T>.removeAllIndexed(predicate: (Int, Int, T) -> Boolean): Boolean {
78 var isChanged = false
79 forEachReversedIndexed { index, key, value ->
80 if (predicate(index, key, value)) {
81 removeAt(index)
82 isChanged = true
83 }
84 }
85 return isChanged
86 }
87
retainAllIndexednull88 inline fun <T> SparseArray<T>.retainAllIndexed(predicate: (Int, Int, T) -> Boolean): Boolean {
89 var isChanged = false
90 forEachReversedIndexed { index, key, value ->
91 if (!predicate(index, key, value)) {
92 removeAt(index)
93 isChanged = true
94 }
95 }
96 return isChanged
97 }
98
99 inline val <T> SparseArray<T>.size: Int
100 get() = size()
101