commonMain.dk.cachet.carp.common.infrastructure.serialization.CarpPrimitiveSerializer.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.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
const val NAMESPACE = "dk.cachet.carp.common"
/**
* Creates a primitive serializer for CARP types in the [dk.cachet.carp.common] namespace
* which are serialized using `toString` and deserialized using [fromString].
*/
internal inline fun createCarpStringPrimitiveSerializer( noinline fromString: (String) -> T ) =
object : StringConversionSerializer( "$NAMESPACE.${T::class.simpleName!!}", fromString ) { }
internal open class StringConversionSerializer(
serialName: String,
val fromString: (String) -> T
) : KSerializer
{
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor( serialName, PrimitiveKind.STRING )
override fun serialize( encoder: Encoder, value: T ) = encoder.encodeString( value.toString() )
override fun deserialize( decoder: Decoder ): T = fromString( decoder.decodeString() )
}
/**
* Creates a primitive serializer for CARP types in the [dk.cachet.carp.common] namespace
* which are serialized using [toLong] and deserialized using [fromLong].
*/
internal inline fun createCarpLongPrimitiveSerializer(
noinline fromLong: (Long) -> T,
noinline toLong: (T) -> Long
) =
object : LongConversionSerializer( "$NAMESPACE.${T::class.simpleName!!}", fromLong, toLong ) { }
internal open class LongConversionSerializer(
serialName: String,
val fromLong: (Long) -> T,
val toLong: (T) -> Long
) : KSerializer
{
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor( serialName, PrimitiveKind.LONG )
override fun serialize( encoder: Encoder, value: T ) = encoder.encodeLong( toLong( value ) )
override fun deserialize( decoder: Decoder ): T = fromLong( decoder.decodeLong() )
}