All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.dokar.quickjs.converter.builtinTypes.kt Maven / Gradle / Ivy

The newest version!
package com.dokar.quickjs.converter

import com.dokar.quickjs.binding.JsObject
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.typeOf

@OptIn(ExperimentalContracts::class)
@PublishedApi
internal fun canConvertReturnInternally(instance: Any?): Boolean {
    contract {
        returns(false) implies (instance != null)
    }
    instance ?: return true
    return typeOfInstance(instance) != null
}

@OptIn(ExperimentalUnsignedTypes::class)
@PublishedApi
internal fun typeOfClass(typeConverters: TypeConverters, cls: KClass<*>): KType {
    return when (cls) {
        Unit::class -> typeOf()
        Int::class -> typeOf()
        Long::class -> typeOf()
        Float::class -> typeOf()
        Double::class -> typeOf()
        Boolean::class -> typeOf()
        String::class -> typeOf()
        ByteArray::class -> typeOf()
        UByteArray::class -> typeOf()
        Array::class -> typeOf>()
        List::class -> typeOf>()
        Set::class -> typeOf>()
        JsObject::class -> typeOf()
        Map::class -> typeOf>()
        Error::class -> typeOf()
        else -> typeConverters.typeOfClass(cls)
            ?: throw IllegalStateException(
                "Cannot find the kotlin type of class '$cls', " +
                        "did you forget to add a type converter for it?"
            )
    }
}

@PublishedApi
internal fun typeOfInstance(typeConverters: TypeConverters, instance: Any): KType {
    return typeOfInstance(instance)
        ?: typeConverters.typeOfClass(instance::class)
        ?: throw IllegalStateException(
            "Cannot find the kotlin type of object $instance (${instance::class}), " +
                    "did you forget to add a type converter for it?"
        )
}

@OptIn(ExperimentalUnsignedTypes::class)
private fun typeOfInstance(instance: Any): KType? {
    return when (instance) {
        Unit -> typeOf()
        is Byte -> typeOf()
        is Short -> typeOf()
        is Int -> typeOf()
        is Long -> typeOf()
        is Float -> typeOf()
        is Double -> typeOf()
        is Boolean -> typeOf()
        is String -> typeOf()
        is ByteArray -> typeOf()
        is UByteArray -> typeOf()
        is Array<*> -> typeOf>()
        is List<*> -> typeOf>()
        is Set<*> -> typeOf>()
        is JsObject -> typeOf()
        is Map<*, *> -> typeOf>()
        is Error -> typeOf()
        else -> null
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy