1 /*
2  * 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.JSONException
20 
21 /**
22  * Golden value type to convert to/from JSON.
23  *
24  * @param typeName identifier written to the JSON, to support de-serialization of the values.
25  * @param jsonToValue convert the [jsonValue] to a native [T], throws [JSONException] if conversion
26  *   fails.
27  * @param valueToJson converts the native [T] to a `org.json` supported type.
28  * @param ensureImmutable copies mutable objects, to avoid subsequent modification.
29  */
30 class DataPointType<T>(
31     val typeName: String,
32     private val jsonToValue: (jsonValue: Any) -> T,
33     private val valueToJson: (T) -> Any,
34     internal val ensureImmutable: (T & Any) -> T & Any = { it },
35 ) {
makeDataPointnull36     fun makeDataPoint(nativeValue: T?): DataPoint<T> {
37         return DataPoint.of(nativeValue, this)
38     }
39 
fromJsonnull40     fun fromJson(jsonValue: Any): DataPoint<T> {
41         return when {
42             NullDataPoint.isNullValue(jsonValue) -> DataPoint.nullValue()
43             NotFoundDataPoint.isNotFoundValue(jsonValue) -> DataPoint.notFound()
44             else ->
45                 try {
46                     makeDataPoint(jsonToValue(jsonValue))
47                 } catch (e: JSONException) {
48                     DataPoint.unknownType()
49                 }
50         }
51     }
52 
toJsonnull53     fun toJson(value: T): Any = valueToJson(value)
54 
55     override fun toString(): String {
56         return typeName
57     }
58 }
59 
60 /** Signals that a JSON value cannot be deserialized by a [DataPointType]. */
61 class UnknownTypeException : JSONException("JSON cannot be converted to DataPoint value")
62