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

commonMain.dk.cachet.carp.common.infrastructure.serialization.CustomSerializerWrapper.kt Maven / Gradle / Ivy

Go to download

Helper classes and base types relied upon by all subsystems. This library does not contain any domain logic.

The newest version!
package dk.cachet.carp.common.infrastructure.serialization

import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*


/**
 * A wrapper for objects which need to be serialized using a different serializer than the one configured at compile time.
 * When the [Encoder] encounters this wrapper, [inner] will be serialized using [serializer].
 */
@Serializable( CustomSerializerWrapperSerializer::class )
class CustomSerializerWrapper internal constructor( val inner: Any, val serializer: KSerializer )


object CustomSerializerWrapperSerializer : KSerializer
{
    override val descriptor: SerialDescriptor =
        buildClassSerialDescriptor( "dk.cachet.carp.common.infrastructure.serialization.CustomSerializerWrapper" )

    override fun serialize( encoder: Encoder, value: CustomSerializerWrapper ) =
        encoder.encodeSerializableValue( value.serializer, value.inner )

    override fun deserialize( decoder: Decoder ): CustomSerializerWrapper =
        throw UnsupportedOperationException(
            "${CustomSerializerWrapper::class.simpleName} only supports serialization."
        )
}


/**
 * Specify a custom [serializer] to use for [inner].
 * When the [Encoder] encounters this wrapper, [inner] will be serialized using [serializer] instead.
 */
@Suppress( "UNCHECKED_CAST" )
fun  customSerializerWrapper( inner: T, serializer: KSerializer ): CustomSerializerWrapper
{
    return CustomSerializerWrapper( inner, serializer as KSerializer )
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy