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

commonMain.MapperSerializer.kt Maven / Gradle / Ivy

There is a newer version: 0.22.2
Show newest version
package dev.inmo.micro_utils.serialization.mapper

import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

/**
 * Use this serializer when you have serializable type [I] and want to map it to some [O] in process of
 * serialization/deserialization
 *
 * @param base Serializer for [I]
 * @param serialize Will be used in [serialize] method to convert incoming [O] to [I] and serialize with [base]
 * @param deserialize Will be used in [deserialize] method to convert deserialized by [base] [I] to [O]
 */
open class MapperSerializer(
    private val base: KSerializer,
    private val serialize: (Encoder, O) -> I,
    private val deserialize: (Decoder, I) -> O
) : KSerializer,
    DeserializationStrategy by MapperDeserializationStrategy(base, deserialize),
    SerializationStrategy by MapperSerializationStrategy(base, serialize) {
    override val descriptor: SerialDescriptor = base.descriptor

    constructor(
        base: KSerializer,
        serialize: (O) -> I,
        deserialize: (I) -> O
    ) : this(base, { _, o -> serialize(o) }, { _, i -> deserialize(i) })

    constructor(
        base: KSerializer,
        serialize: (Encoder, O) -> I,
        deserialize: (I) -> O
    ) : this(base, serialize, { _, i -> deserialize(i) })

    constructor(
        base: KSerializer,
        serialize: (O) -> I,
        deserialize: (Decoder, I) -> O
    ) : this(base, { _, o -> serialize(o) }, deserialize)
}