make it possible to use encoder inside of serialize callback

This commit is contained in:
InsanusMokrassar 2024-01-04 10:24:39 +06:00
parent 386fa830c3
commit 759a3f2784
2 changed files with 21 additions and 6 deletions

View File

@ -1,9 +1,7 @@
package dev.inmo.micro_utils.serialization.mapper
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
/**
@ -11,15 +9,20 @@ import kotlinx.serialization.encoding.Encoder
* serialization
*
* @param base Serializer for [I]
* @param serialize Will be used in [serialize] method to convert incoming [O] to [I] and serialize with [base]
* @param internalSerialize Will be used in [internalSerialize] method to convert incoming [O] to [I] and serialize with [base]
*/
open class MapperSerializationStrategy<I, O>(
private val base: SerializationStrategy<I>,
private val serialize: (O) -> I
private val internalSerialize: (Encoder, O) -> I
) : SerializationStrategy<O> {
override val descriptor: SerialDescriptor = base.descriptor
constructor(
base: SerializationStrategy<I>,
serialize: (O) -> I
) : this(base, { _, o -> serialize(o) })
override fun serialize(encoder: Encoder, value: O) {
base.serialize(encoder, serialize(value))
base.serialize(encoder, internalSerialize(encoder, value))
}
}

View File

@ -17,7 +17,7 @@ import kotlinx.serialization.encoding.Encoder
*/
open class MapperSerializer<I, O>(
private val base: KSerializer<I>,
private val serialize: (O) -> I,
private val serialize: (Encoder, O) -> I,
private val deserialize: (Decoder, I) -> O
) : KSerializer<O>,
DeserializationStrategy<O> by MapperDeserializationStrategy<I, O>(base, deserialize),
@ -28,5 +28,17 @@ open class MapperSerializer<I, O>(
base: KSerializer<I>,
serialize: (O) -> I,
deserialize: (I) -> O
) : this(base, { _, o -> serialize(o) }, { _, i -> deserialize(i) })
constructor(
base: KSerializer<I>,
serialize: (Encoder, O) -> I,
deserialize: (I) -> O
) : this(base, serialize, { _, i -> deserialize(i) })
constructor(
base: KSerializer<I>,
serialize: (O) -> I,
deserialize: (Decoder, I) -> O
) : this(base, { _, o -> serialize(o) }, deserialize)
}