/
KotshiUtils.kt
264 lines (241 loc) · 11.5 KB
/
KotshiUtils.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package se.ansman.kotshi
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Types
import java.lang.reflect.*
/**
* A helper class for Kotshi.
*
* These functions should not be considered public and are subject to change without notice.
*/
@InternalKotshiApi
object KotshiUtils {
@JvmStatic
@InternalKotshiApi
val Type.typeArgumentsOrFail: Array<Type>
get() = (this as? ParameterizedType)?.actualTypeArguments
?: throw IllegalArgumentException(
"""
${Types.getRawType(this).simpleName} is generic and requires you to specify its type
arguments. Don't request an adapter using Type::class.java or value.javaClass but rather using
Types.newParameterizedType.
""".trimIndent()
)
@JvmStatic
@JvmOverloads
@InternalKotshiApi
fun StringBuilder?.appendNullableError(propertyName: String, jsonName: String = propertyName): StringBuilder =
(if (this == null) StringBuilder("The following properties were null: ") else append(", "))
.append(propertyName)
.apply {
if (jsonName != propertyName) {
append(" (JSON name ").append(jsonName).append(')')
}
}
@JvmStatic
@InternalKotshiApi
fun matches(
targetType: Type?,
actualType: Type?,
allowSubClasses: Boolean = false,
allowSuperClasses: Boolean = false,
): Boolean = when (targetType) {
// e.g. Array<...>
is GenericArrayType -> actualType is GenericArrayType &&
matches(targetType.genericComponentType, actualType.genericComponentType, allowSubClasses = true)
// e.g. List<...>
is ParameterizedType -> actualType is ParameterizedType &&
matches(actualType.rawType, targetType.rawType, allowSubClasses, allowSuperClasses) &&
matches(actualType.ownerType, targetType.ownerType, allowSubClasses, allowSuperClasses) &&
targetType.actualTypeArguments.size == actualType.actualTypeArguments.size &&
targetType.actualTypeArguments.allIndexed { i, e -> matches(e, actualType.actualTypeArguments[i]) }
// e.g. E : Number
is TypeVariable<*> -> targetType.bounds.all { matches(it, actualType, allowSubClasses = true) }
// e.g. out Number or in Number
is WildcardType -> targetType.lowerBounds.all { matches(it, actualType, allowSuperClasses = true) } &&
targetType.upperBounds.all { matches(it, actualType, allowSubClasses = true) }
// e.g. String
is Class<*> -> {
fun Type.rawType(): Class<*>? =
when (this) {
is GenericArrayType -> Array::class.java
is ParameterizedType -> rawType.rawType()
is TypeVariable<*> -> null // Type variables should not appear in actual type
is WildcardType -> (lowerBounds.singleOrNull() ?: upperBounds[0]).rawType()
is Class<*> -> this
else -> null
}
val rawType = actualType?.rawType()
rawType != null && when {
allowSubClasses -> targetType.isAssignableFrom(rawType)
allowSuperClasses -> rawType.isAssignableFrom(targetType)
else -> targetType == rawType
}
}
null -> actualType == null
// Unknown type
else -> false
}
private inline fun <E> Array<E>.allIndexed(predicate: (index: Int, element: E) -> Boolean): Boolean {
var i = 0
while (i < size) {
if (!predicate(i, get(i))) {
return false
}
++i
}
return true
}
@JvmStatic
@JvmOverloads
@InternalKotshiApi
fun <T : Annotation> Class<T>.createJsonQualifierImplementation(annotationArguments: Map<String, Any> = emptyMap()): T {
require(isAnnotation) { "$this must be an annotation." }
@Suppress("UNCHECKED_CAST")
return Proxy.newProxyInstance(classLoader, arrayOf<Class<*>>(this), object : InvocationHandler {
private val annotationMethods = declaredMethods
.onEach { method ->
val value = annotationArguments[method.name]
if (value == null) {
require(method.defaultValue != null) {
"Annotation value for method ${method.name} is missing"
}
} else {
val expectedType = when (val returnType = method.returnType) {
Boolean::class.java -> Boolean::class.javaObjectType
Byte::class.java -> Byte::class.javaObjectType
Char::class.java -> Char::class.javaObjectType
Double::class.java -> Double::class.javaObjectType
Float::class.java -> Float::class.javaObjectType
Int::class.java -> Int::class.javaObjectType
Long::class.java -> Long::class.javaObjectType
Short::class.java -> Short::class.javaObjectType
Void::class.java -> Void::class.javaObjectType
else -> returnType
}
require(expectedType.isInstance(value)) {
"Expected value for method ${method.name} to be of type $expectedType but was ${value.javaClass}"
}
}
}
.apply { sortBy { it.name } }
init {
val extraArguments =
annotationArguments.keys - annotationMethods.mapTo(HashSet(annotationMethods.size)) { it.name }
require(extraArguments.isEmpty()) {
"Found annotation values for unknown methods: $extraArguments"
}
}
override fun invoke(proxy: Any, method: Method, args: Array<out Any>?): Any =
when (method.name) {
"annotationType" -> this@createJsonQualifierImplementation
"equals" -> args!![0] === proxy || isInstance(args!![0]) && annotationMethods.all { m ->
annotationValuesEquals(m.invoke(args[0]), annotationArguments[m.name] ?: m.defaultValue)
}
// For the implementation see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/annotation/Annotation.html#hashCode()
"hashCode" -> annotationMethods.sumOf { m ->
(m.name.hashCode() * 127) xor (annotationArguments[m.name] ?: m.defaultValue).annotationValueHashCode()
}
"toString" -> buildString {
append('@').append(name)
append('(')
var appendSeparator = false
for (m in annotationMethods) {
if (appendSeparator) {
append(", ")
}
val value = annotationArguments[m.name] ?: m.defaultValue
append(m.name).append('=').append(value.annotationValueToString())
appendSeparator = true
}
append(')')
"@$name(${annotationArguments.entries.joinToString()})"
}
else -> annotationArguments[method.name] ?: method.defaultValue
}
private fun annotationValuesEquals(v1: Any?, v2: Any?): Boolean =
when (v1) {
is BooleanArray -> v2 is BooleanArray && v1.contentEquals(v2)
is ByteArray -> v2 is ByteArray && v1.contentEquals(v2)
is CharArray -> v2 is CharArray && v1.contentEquals(v2)
is ShortArray -> v2 is ShortArray && v1.contentEquals(v2)
is IntArray -> v2 is IntArray && v1.contentEquals(v2)
is LongArray -> v2 is LongArray && v1.contentEquals(v2)
is FloatArray -> v2 is FloatArray && v1.contentEquals(v2)
is DoubleArray -> v2 is DoubleArray && v1.contentEquals(v2)
is Array<*> -> v2 is Array<*> && v1.contentEquals(v2)
else -> v1 == v2
}
private fun Any.annotationValueHashCode(): Int =
when (this) {
is BooleanArray -> contentHashCode()
is ByteArray -> contentHashCode()
is CharArray -> contentHashCode()
is ShortArray -> contentHashCode()
is IntArray -> contentHashCode()
is LongArray -> contentHashCode()
is FloatArray -> contentHashCode()
is DoubleArray -> contentHashCode()
is Array<*> -> contentHashCode()
else -> hashCode()
}
private fun Any.annotationValueToString(): String =
when (this) {
is BooleanArray -> contentToString()
is ByteArray -> contentToString()
is CharArray -> contentToString()
is ShortArray -> contentToString()
is IntArray -> contentToString()
is LongArray -> contentToString()
is FloatArray -> contentToString()
is DoubleArray -> contentToString()
is Array<*> -> contentToString()
else -> toString()
}
}) as T
}
@JvmStatic
@InternalKotshiApi
fun JsonReader.nextFloat(): Float =
nextDouble().toFloat().also {
// Double check for infinity after float conversion; many doubles > Float.MAX
if (!isLenient && it.isInfinite()) {
throw JsonDataException("JSON forbids NaN and infinities: $it at path $path")
}
}
@JvmStatic
@InternalKotshiApi
fun JsonReader.nextByte(): Byte = nextIntInRange("a byte", -128, 255).toByte()
@JvmStatic
fun JsonReader.nextShort(): Short = nextIntInRange("a short", -32768, 32767).toShort()
@JvmStatic
@InternalKotshiApi
fun JsonReader.nextChar(): Char =
nextString()
.also {
if (it.length != 1) {
throw JsonDataException("Expected a char but was $it at path $path")
}
}
.single()
@JvmStatic
@InternalKotshiApi
fun JsonWriter.byteValue(byte: Byte): JsonWriter = value(byte.toInt() and 0xff)
@JvmStatic
@InternalKotshiApi
fun JsonWriter.byteValue(byte: Byte?): JsonWriter = if (byte == null) nullValue() else byteValue(byte)
@JvmStatic
@InternalKotshiApi
fun JsonWriter.value(char: Char): JsonWriter = value(char.toString())
@JvmStatic
@InternalKotshiApi
fun JsonWriter.value(char: Char?): JsonWriter = if (char == null) nullValue() else value(char)
@JvmStatic
private fun JsonReader.nextIntInRange(typeMessage: String, min: Int, max: Int): Int =
nextInt().also {
if (it !in min..max) {
throw JsonDataException("Expected $typeMessage but was $it at path $path")
}
}
}