1 /*
<lambda>null2 * Copyright (C) 2024 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.systemui.kairos.internal.util
18
19 import kotlinx.coroutines.CoroutineStart
20 import kotlinx.coroutines.async
21 import kotlinx.coroutines.awaitAll
22 import kotlinx.coroutines.coroutineScope
23 import kotlinx.coroutines.yield
24
25 // TODO: It's possible that this is less efficient than having each coroutine directly insert into a
26 // ConcurrentHashMap, but then we would lose ordering
27 internal suspend inline fun <K, A, B : Any, M : MutableMap<K, B>> Map<K, A>
28 .mapValuesNotNullParallelTo(
29 destination: M,
30 crossinline block: suspend (Map.Entry<K, A>) -> B?,
31 ): M =
32 destination.also {
33 coroutineScope {
34 mapValues {
35 async {
36 yield()
37 block(it)
38 }
39 }
40 }
41 .mapValuesNotNullTo(it) { (_, deferred) -> deferred.await() }
42 }
43
mapValuesNotNullTonull44 internal inline fun <K, A, B : Any, M : MutableMap<K, B>> Map<K, A>.mapValuesNotNullTo(
45 destination: M,
46 block: (Map.Entry<K, A>) -> B?,
47 ): M =
48 destination.also {
49 for (entry in this@mapValuesNotNullTo) {
50 block(entry)?.let { destination.put(entry.key, it) }
51 }
52 }
53
mapParallelnull54 internal suspend fun <A, B> Iterable<A>.mapParallel(transform: suspend (A) -> B): List<B> =
55 coroutineScope {
56 map { async(start = CoroutineStart.LAZY) { transform(it) } }.awaitAll()
57 }
58
mapValuesParallelTonull59 internal suspend fun <K, A, B, M : MutableMap<K, B>> Map<K, A>.mapValuesParallelTo(
60 destination: M,
61 transform: suspend (Map.Entry<K, A>) -> B,
62 ): Map<K, B> = entries.mapParallel { it.key to transform(it) }.toMap(destination)
63
mapValuesParallelnull64 internal suspend fun <K, A, B> Map<K, A>.mapValuesParallel(
65 transform: suspend (Map.Entry<K, A>) -> B
66 ): Map<K, B> = mapValuesParallelTo(mutableMapOf(), transform)
67