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 com.android.systemui.kairos.util.Maybe
20 import com.android.systemui.kairos.util.None
21 import com.android.systemui.kairos.util.just
22 import java.util.concurrent.ConcurrentHashMap
23 
24 internal interface Key<A>
25 
26 private object NULL
27 
28 internal class HeteroMap {
29 
30     private val store = ConcurrentHashMap<Key<*>, Any>()
31 
32     @Suppress("UNCHECKED_CAST")
33     operator fun <A> get(key: Key<A>): Maybe<A> =
34         store[key]?.let { just((if (it === NULL) null else it) as A) } ?: None
35 
36     operator fun <A> set(key: Key<A>, value: A) {
37         store[key] = value ?: NULL
38     }
39 
40     operator fun contains(key: Key<*>): Boolean = store.containsKey(key)
41 
42     fun clear() {
43         store.clear()
44     }
45 
46     @Suppress("UNCHECKED_CAST")
47     fun <A> remove(key: Key<A>): Maybe<A> =
48         store.remove(key)?.let { just((if (it === NULL) null else it) as A) } ?: None
49 
50     @Suppress("UNCHECKED_CAST")
51     fun <A> getOrPut(key: Key<A>, defaultValue: () -> A): A =
52         store.compute(key) { _, value -> value ?: defaultValue() ?: NULL } as A
53 }
54