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

commonMain.com.ensarsarajcic.kotlinx.serialization.msgpack.extensions.DynamicMsgPackExtensionSerializer.kt Maven / Gradle / Ivy

The newest version!
package com.ensarsarajcic.kotlinx.serialization.msgpack.extensions

import kotlinx.serialization.SerializationException
import kotlin.reflect.KClass

open class DynamicMsgPackExtensionSerializer : BaseMsgPackExtensionSerializer() {
    companion object Default : DynamicMsgPackExtensionSerializer()

    private data class SerializerPair(val klass: KClass, val serializer: BaseMsgPackExtensionSerializer) {
        fun deserialize(extension: MsgPackExtension): T {
            return serializer.deserialize(extension)
        }

        fun serialize(value: Any?): MsgPackExtension {
            return serializer.serialize(value as T)
        }
    }

    private val serializers: MutableMap> = mutableMapOf()

    inline fun  register(serializer: BaseMsgPackExtensionSerializer) {
        register(serializer, T::class)
    }

    final fun  register(
        serializer: BaseMsgPackExtensionSerializer,
        klass: KClass,
    ) {
        serializers[serializer.extTypeId] = SerializerPair(klass, serializer)
    }

    final fun unregister(serializer: BaseMsgPackExtensionSerializer<*>) {
        serializers.remove(serializer.extTypeId)
    }

    final fun canSerialize(value: Any?): Boolean {
        if (value is MsgPackExtension) return true
        for (serializer in serializers.values) {
            if (serializer.klass.isInstance(value)) {
                return true
            }
        }
        return false
    }

    final override fun deserialize(extension: MsgPackExtension): Any? {
        val pair = serializers[extension.extTypeId] ?: return extension
        return pair.deserialize(extension)
    }

    final override fun serialize(extension: Any?): MsgPackExtension {
        if (extension is MsgPackExtension) {
            return extension
        }
        for (serializer in serializers.values) {
            if (serializer.klass.isInstance(extension)) {
                return serializer.serialize(extension)
            }
        }
        throw SerializationException("Missing serializer for extension: $extension")
    }

    final override val extTypeId: Byte = 0x00
    final override val checkTypeId: Boolean = false
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy