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.store
18
19 import com.android.systemui.kairos.internal.util.ConcurrentNullableHashMap
20
21 @JvmInline
22 internal value class MapHolder<K, V>(val unwrapped: Map<K, V>) :
23 MapK<MapHolder.W, K, V>, Map<K, V> by unwrapped {
24 object W
25 }
26
27 @Suppress("NOTHING_TO_INLINE")
asMapHoldernull28 internal inline fun <K, V> MapK<MapHolder.W, K, V>.asMapHolder(): MapHolder<K, V> =
29 this as MapHolder<K, V>
30
31 // TODO: preserve insertion order?
32 internal class ConcurrentHashMapK<K, V>(private val storage: ConcurrentNullableHashMap<K, V>) :
33 MutableMapK<MapHolder.W, K, V>, MutableMap<K, V> by storage {
34
35 override fun readOnlyCopy() = MapHolder(storage.toMap())
36
37 override fun asReadOnly(): MapK<MapHolder.W, K, V> = MapHolder(storage)
38
39 class Factory<K> : MutableMapK.Factory<MapHolder.W, K> {
40 override fun <V> create(capacity: Int?) =
41 ConcurrentHashMapK<K, V>(
42 capacity?.let { ConcurrentNullableHashMap(capacity) } ?: ConcurrentNullableHashMap()
43 )
44
45 override fun <V> create(input: MapK<MapHolder.W, K, V>) =
46 ConcurrentHashMapK(
47 ConcurrentNullableHashMap<K, V>().apply {
48 input.asMapHolder().unwrapped.forEach { (k, v) -> set(k, v) }
49 }
50 )
51 }
52 }
53