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 <I : Immutable<M>, M : I> IntReferenceMap<I, M>.allIndexed(
20     predicate: (Int, Int, I) -> Boolean
21 ): 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 <I : Immutable<M>, M : I> IntReferenceMap<I, M>.anyIndexed(
31     predicate: (Int, Int, I) -> Boolean
32 ): Boolean {
33     forEachIndexed { index, key, value ->
34         if (predicate(index, key, value)) {
35             return true
36         }
37     }
38     return false
39 }
40 
forEachIndexednull41 inline fun <I : Immutable<M>, M : I> IntReferenceMap<I, M>.forEachIndexed(
42     action: (Int, Int, I) -> Unit
43 ) {
44     for (index in 0 until size) {
45         action(index, keyAt(index), valueAt(index))
46     }
47 }
48 
forEachReversedIndexednull49 inline fun <I : Immutable<M>, M : I> IntReferenceMap<I, M>.forEachReversedIndexed(
50     action: (Int, Int, I) -> Unit
51 ) {
52     for (index in lastIndex downTo 0) {
53         action(index, keyAt(index), valueAt(index))
54     }
55 }
56 
57 inline val <I : Immutable<M>, M : I> IntReferenceMap<I, M>.lastIndex: Int
58     get() = size - 1
59 
noneIndexednull60 inline fun <I : Immutable<M>, M : I> IntReferenceMap<I, M>.noneIndexed(
61     predicate: (Int, Int, I) -> Boolean
62 ): Boolean {
63     forEachIndexed { index, key, value ->
64         if (predicate(index, key, value)) {
65             return false
66         }
67     }
68     return true
69 }
70 
mutateOrPutnull71 inline fun <I : Immutable<M>, M : I> MutableIntReferenceMap<I, M>.mutateOrPut(
72     key: Int,
73     defaultValue: () -> M
74 ): M {
75     mutate(key)?.let {
76         return it
77     }
78     return defaultValue().also { put(key, it) }
79 }
80 
minusAssignnull81 operator fun <I : Immutable<M>, M : I> MutableIntReferenceMap<I, M>.minusAssign(key: Int) {
82     array.remove(key).also { array.gc() }
83 }
84 
setnull85 operator fun <I : Immutable<M>, M : I> MutableIntReferenceMap<I, M>.set(key: Int, value: M) {
86     array.put(key, MutableReference(value))
87 }
88