xref: /aosp_15_r20/external/leakcanary2/leakcanary-android-release/src/main/java/leakcanary/JobContext.kt (revision d9e8da70d8c9df9a41d7848ae506fb3115cae6e6)
1 package leakcanary
2 
3 import java.util.concurrent.ConcurrentHashMap
4 import kotlin.reflect.KClass
5 
6 /**
7  * In memory store that can be used to store objects in a given [HeapAnalysisJob] instance.
8  * This is a simple [MutableMap] of [String] to [Any], but with unsafe generics access.
9  *
10  * By convention, [starter] should be the class that triggered the start of the job.
11  */
12 class JobContext constructor(val starter: Class<*>? = null) {
13 
14   constructor(starter: KClass<*>) : this(starter.java)
15 
16   private val store = ConcurrentHashMap<String, Any?>()
17 
getnull18   operator fun <T> get(key: String): T? {
19     @Suppress("UNCHECKED_CAST")
20     return store[key] as T?
21   }
22 
23   /**
24    * @see MutableMap.getOrPut
25    */
getOrPutnull26   fun <T> getOrPut(
27     key: String,
28     defaultValue: () -> T
29   ): T {
30     @Suppress("UNCHECKED_CAST")
31     return store.getOrPut(key) {
32       defaultValue()
33     } as T
34   }
35 
36   /**
37    * @see MutableMap.set
38    */
setnull39   operator fun <T> set(
40     key: String,
41     value: T
42   ) {
43     store[key] = (value as Any?)
44   }
45 
46   /**
47    * @see MutableMap.containsKey
48    */
containsnull49   operator fun contains(key: String): Boolean {
50     return store.containsKey(key)
51   }
52 
53   /**
54    * @see MutableMap.remove
55    */
minusAssignnull56   operator fun minusAssign(key: String) {
57     @Suppress("UNCHECKED_CAST")
58     store -= key
59   }
60 }
61