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 platform.test.motion.golden 18 19 import org.json.JSONArray 20 21 fun Float.asDataPoint() = DataPointTypes.float.makeDataPoint(this) 22 23 fun Boolean.asDataPoint() = DataPointTypes.boolean.makeDataPoint(this) 24 25 fun Int.asDataPoint() = DataPointTypes.int.makeDataPoint(this) 26 27 fun String.asDataPoint() = DataPointTypes.string.makeDataPoint(this) 28 29 /** [DataPointType] implementations for core Kotlin types. */ 30 object DataPointTypes { 31 32 val boolean: DataPointType<Boolean> = 33 DataPointType( 34 "boolean", 35 jsonToValue = { 36 when { 37 it is Boolean -> it 38 it is String && "true".equals(it, ignoreCase = true) -> true 39 it is String && "false".equals(it, ignoreCase = true) -> false 40 else -> throw UnknownTypeException() 41 } 42 }, 43 valueToJson = { it } 44 ) 45 46 val float: DataPointType<Float> = 47 DataPointType( 48 "float", 49 jsonToValue = { 50 when (it) { 51 is Float -> it 52 is Number -> it.toFloat() 53 is String -> it.toFloatOrNull() ?: throw UnknownTypeException() 54 else -> throw UnknownTypeException() 55 } 56 }, 57 valueToJson = { it } 58 ) 59 60 val int: DataPointType<Int> = 61 DataPointType( 62 "int", 63 jsonToValue = { 64 when (it) { 65 is Int -> it 66 is Number -> it.toInt() 67 is String -> it.toIntOrNull() ?: throw UnknownTypeException() 68 else -> throw UnknownTypeException() 69 } 70 }, 71 valueToJson = { it } 72 ) 73 74 val string: DataPointType<String> = 75 DataPointType("string", jsonToValue = { it.toString() }, valueToJson = { it }) 76 77 /** 78 * Creates a [DataPointType] to serialize a list of values in an array, using [dataPointType]. 79 */ 80 fun <T : Any> listOf(dataPointType: DataPointType<T>): DataPointType<List<T>> { 81 return DataPointType( 82 "${dataPointType.typeName}[]", 83 jsonToValue = { 84 when (it) { 85 is JSONArray -> 86 List(it.length()) { index -> 87 val dataPoint = dataPointType.fromJson(it.get(index)) 88 if (dataPoint !is ValueDataPoint<T>) { 89 throw UnknownTypeException() 90 } 91 dataPoint.value 92 } 93 else -> throw UnknownTypeException() 94 } 95 }, 96 valueToJson = { 97 JSONArray().apply { it.forEach { value -> put(dataPointType.toJson(value)) } } 98 } 99 ) 100 } 101 } 102