From a24a335743f49e142e38738b77cb33d96032c9d8 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 8 Sep 2021 12:18:42 +0600 Subject: [PATCH] TypedSerializer#plusAssign and TypedSerializer#minusAssign --- CHANGELOG.md | 2 ++ .../typed_serializer/TypedSerializer.kt | 18 ++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f3a78d427c..82782f96337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ * New property `MPPFile#withoutSlashAtTheEnd` * Extension `clamp` has been deprecated * New extension `Iterable#diff` +* `Serialization`: + * New operators `TypedSerializer#plusAssign` and `TypedSerializer#minusAssign` ## 0.5.24 diff --git a/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt b/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt index 158d22994e5..3e6d9045f34 100644 --- a/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt +++ b/serialization/typed_serializer/src/commonMain/kotlin/dev/inmo/micro_utils/serialization/typed_serializer/TypedSerializer.kt @@ -11,6 +11,7 @@ open class TypedSerializer( presetSerializers: Map> = emptyMap(), ) : KSerializer { protected val serializers = presetSerializers.toMutableMap() + @ExperimentalSerializationApi @InternalSerializationApi override val descriptor: SerialDescriptor = buildSerialDescriptor( "TypedSerializer", @@ -32,8 +33,9 @@ open class TypedSerializer( element("value", ContextualSerializer(kClass).descriptor) } + @ExperimentalSerializationApi @InternalSerializationApi - open override fun deserialize(decoder: Decoder): T { + override fun deserialize(decoder: Decoder): T { return decoder.decodeStructure(descriptor) { var type: String? = null lateinit var result: T @@ -56,13 +58,15 @@ open class TypedSerializer( } } + @ExperimentalSerializationApi @InternalSerializationApi protected open fun CompositeEncoder.encode(value: O) { encodeSerializableElement(descriptor, 1, value::class.serializer() as KSerializer, value) } + @ExperimentalSerializationApi @InternalSerializationApi - open override fun serialize(encoder: Encoder, value: T) { + override fun serialize(encoder: Encoder, value: T) { encoder.encodeStructure(descriptor) { val valueSerializer = value::class.serializer() val type = serializers.keys.first { serializers[it] == valueSerializer } @@ -81,6 +85,16 @@ open class TypedSerializer( } } +@InternalSerializationApi +operator fun TypedSerializer.plusAssign(kClass: KClass) { + include(kClass.simpleName!!, kClass.serializer()) +} + +@InternalSerializationApi +operator fun TypedSerializer.minusAssign(kClass: KClass) { + exclude(kClass.simpleName!!) +} + inline fun TypedSerializer( presetSerializers: Map> = emptyMap() ) = TypedSerializer(T::class, presetSerializers)