1 /*
<lambda>null2  * Copyright 2020 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 androidx.compose.ui.inspection.inspector
18 
19 /**
20  * Converter for casting a parameter represented by its primitive value to its inline class type.
21  *
22  * For example: an androidx.compose.ui.graphics.Color instance is often represented by a long
23  */
24 internal class InlineClassConverter {
25     // Map from inline type name to inline class and conversion lambda
26     private val typeMap = mutableMapOf<String, (Any) -> Any>()
27     // Return value used in functions
28     private val notInlineType: (Any) -> Any = { it }
29 
30     /** Clear any cached data. */
31     fun clear() {
32         typeMap.clear()
33     }
34 
35     /**
36      * Cast the specified [value] to a value of type [inlineClassName] if possible.
37      *
38      * @param inlineClassName the fully qualified name of the inline class.
39      * @param value the value to convert to an instance of [inlineClassName].
40      */
41     fun castParameterValue(inlineClassName: String?, value: Any?): Any? =
42         if (value != null && inlineClassName != null) typeMapperFor(inlineClassName)(value)
43         else value
44 
45     private fun typeMapperFor(typeName: String): (Any) -> (Any) =
46         typeMap.getOrPut(typeName) { loadTypeMapper(typeName.replace('.', '/')) }
47 
48     private fun loadTypeMapper(className: String): (Any) -> Any {
49         val javaClass = loadClassOrNull(className) ?: return notInlineType
50         val create = javaClass.declaredConstructors.singleOrNull() ?: return notInlineType
51         create.isAccessible = true
52         return { value -> create.newInstance(value) }
53     }
54 
55     private fun loadClassOrNull(className: String): Class<*>? =
56         try {
57             javaClass.classLoader!!.loadClass(className)
58         } catch (ex: Exception) {
59             null
60         }
61 }
62