/* * 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 Array.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) } internal actual fun KClass.compiledSerializerImpl(): KSerializer? = this.constructSerializerForGivenTypeArgs() ?: ( if (this === Nothing::class) NothingSerializer // Workaround for KT-51333 else this.js.asDynamic().Companion?.serializer() ) as? KSerializer internal actual fun createCache(factory: (KClass<*>) -> KSerializer?): SerializerCache { return object: SerializerCache { override fun get(key: KClass): KSerializer? { return factory(key) } } } internal actual fun createParametrizedCache(factory: (KClass, List) -> KSerializer?): ParametrizedSerializerCache { return object: ParametrizedSerializerCache { override fun get(key: KClass, types: List): Result?> { return kotlin.runCatching { factory(key, types) } } } } internal actual fun ArrayList.toNativeArrayImpl(eClass: KClass): Array = toTypedArray() internal actual fun KClass<*>.platformSpecificSerializerNotRegistered(): Nothing { throw SerializationException( notRegisteredMessage() + "To get enum serializer on Kotlin/JS, it should be annotated with @Serializable annotation." ) } @Suppress("UNCHECKED_CAST", "DEPRECATION_ERROR") @OptIn(ExperimentalAssociatedObjects::class) internal actual fun KClass.constructSerializerForGivenTypeArgs(vararg args: KSerializer): KSerializer? = try { val assocObject = findAssociatedObject() when { assocObject is KSerializer<*> -> assocObject as KSerializer assocObject is SerializerFactory -> assocObject.serializer(*args) as KSerializer this.isInterface -> PolymorphicSerializer(this) else -> null } } catch (e: dynamic) { null } internal actual fun isReferenceArray(rootClass: KClass): 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"