2023-03-09 15:55:07 +00:00
|
|
|
package dev.inmo.micro_utils.serialization.mapper
|
|
|
|
|
2023-12-31 07:44:33 +00:00
|
|
|
import kotlinx.serialization.DeserializationStrategy
|
2023-03-09 15:55:07 +00:00
|
|
|
import kotlinx.serialization.KSerializer
|
2023-12-31 07:44:33 +00:00
|
|
|
import kotlinx.serialization.SerializationStrategy
|
2023-03-09 15:55:07 +00:00
|
|
|
import kotlinx.serialization.descriptors.SerialDescriptor
|
|
|
|
import kotlinx.serialization.encoding.Decoder
|
|
|
|
import kotlinx.serialization.encoding.Encoder
|
|
|
|
|
2023-03-09 16:21:11 +00:00
|
|
|
/**
|
|
|
|
* 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<I, O>(
|
2023-03-09 15:55:07 +00:00
|
|
|
private val base: KSerializer<I>,
|
|
|
|
private val serialize: (O) -> I,
|
2023-12-31 07:44:33 +00:00
|
|
|
private val deserialize: (Decoder, I) -> O
|
|
|
|
) : KSerializer<O>,
|
|
|
|
DeserializationStrategy<O> by MapperDeserializationStrategy<I, O>(base, deserialize),
|
|
|
|
SerializationStrategy<O> by MapperSerializationStrategy<I, O>(base, serialize) {
|
2023-03-09 15:55:07 +00:00
|
|
|
override val descriptor: SerialDescriptor = base.descriptor
|
|
|
|
|
2023-12-31 07:44:33 +00:00
|
|
|
constructor(
|
|
|
|
base: KSerializer<I>,
|
|
|
|
serialize: (O) -> I,
|
|
|
|
deserialize: (I) -> O
|
|
|
|
) : this(base, serialize, { _, i -> deserialize(i) })
|
2023-03-09 15:55:07 +00:00
|
|
|
}
|