-
Notifications
You must be signed in to change notification settings - Fork 612
/
Platform.kt
64 lines (53 loc) · 2.63 KB
/
Platform.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
/*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.internal
import kotlinx.serialization.*
import kotlin.reflect.*
internal actual fun <T> Array<T>.getChecked(index: Int): T {
if (index !in indices) throw IndexOutOfBoundsException("Index $index out of bounds $indices")
return get(index)
}
internal actual fun BooleanArray.getChecked(index: Int): Boolean {
if (index !in indices) throw IndexOutOfBoundsException("Index $index out of bounds $indices")
return get(index)
}
@Suppress("UNCHECKED_CAST")
internal actual fun <T : Any> KClass<T>.compiledSerializerImpl(): KSerializer<T>? =
this.constructSerializerForGivenTypeArgs() ?: this.js.asDynamic().Companion?.serializer() as? KSerializer<T>
internal actual fun createCachedFactoryWrapper(factory: (KClass<*>) -> KSerializer<Any>?): CachedSerializerFactory {
return object : CachedSerializerFactory {
override fun get(key: KClass<*>, isNullable: Boolean): KSerializer<Any?>? = factory(key)?.nullable(isNullable)
}
}
internal actual fun <T : Any, E : T?> ArrayList<E>.toNativeArrayImpl(eClass: KClass<T>): Array<E> = toTypedArray()
internal actual fun Any.isInstanceOf(kclass: KClass<*>): Boolean = kclass.isInstance(this)
internal actual fun KClass<*>.platformSpecificSerializerNotRegistered(): Nothing {
throw SerializationException(
"Serializer for class '${simpleName}' is not found.\n" +
"Mark the class as @Serializable or provide the serializer explicitly.\n" +
"On Kotlin/JS explicitly declared serializer should be used for interfaces and enums without @Serializable annotation"
)
}
@Suppress("UNCHECKED_CAST", "DEPRECATION_ERROR")
@OptIn(ExperimentalAssociatedObjects::class)
internal actual fun <T : Any> KClass<T>.constructSerializerForGivenTypeArgs(vararg args: KSerializer<Any?>): KSerializer<T>? =
try {
val assocObject = findAssociatedObject<SerializableWith>()
when {
assocObject is KSerializer<*> -> assocObject as KSerializer<T>
assocObject is SerializerFactory -> assocObject.serializer(*args) as KSerializer<T>
this.isInterface -> PolymorphicSerializer(this)
else -> null
}
} catch (e: dynamic) {
null
}
internal actual fun isReferenceArray(rootClass: KClass<Any>): Boolean = rootClass == Array::class
/**
* WARNING: may be broken in arbitrary time in the future without notice
*
* Should be eventually replaced with compiler intrinsics
*/
private val KClass<*>.isInterface
get(): Boolean = js.asDynamic().`$metadata$`?.kind == "interface"