• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 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.compose.ui.util
18 
19 import kotlin.contracts.ExperimentalContracts
20 import kotlin.contracts.contract
21 
22 /**
23  * Iterates through a [List] using the index and calls [action] for each item. This does not
24  * allocate an iterator like [Iterable.forEach].
25  *
26  * **Do not use for collections that come from public APIs**, since they may not support random
27  * access in an efficient way, and this method may actually be a lot slower. Only use for
28  * collections that are created by code we control and are known to support random access.
29  */
30 @Suppress("BanInlineOptIn")
31 @OptIn(ExperimentalContracts::class)
fastForEachnull32 internal inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
33     contract { callsInPlace(action) }
34     for (index in indices) {
35         val item = get(index)
36         action(item)
37     }
38 }
39 
40 /**
41  * Returns a list containing the results of applying the given [transform] function to each element
42  * in the original collection.
43  *
44  * **Do not use for collections that come from public APIs**, since they may not support random
45  * access in an efficient way, and this method may actually be a lot slower. Only use for
46  * collections that are created by code we control and are known to support random access.
47  */
48 @Suppress("BanInlineOptIn")
49 @OptIn(ExperimentalContracts::class)
fastMapnull50 internal inline fun <T, R> List<T>.fastMap(transform: (T) -> R): List<R> {
51     contract { callsInPlace(transform) }
52     val target = ArrayList<R>(size)
53     fastForEach { target += transform(it) }
54     return target
55 }
56