-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Split PolymorphicListAsMapSerializer into a helper class CustomMapSer…
…ializer
- Loading branch information
Showing
2 changed files
with
65 additions
and
50 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
.../commonMain/kotlin/com/mineinabyss/geary/serialization/serializers/CustomMapSerializer.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package com.mineinabyss.geary.serialization.serializers | ||
|
||
import kotlinx.serialization.ContextualSerializer | ||
import kotlinx.serialization.KSerializer | ||
import kotlinx.serialization.builtins.MapSerializer | ||
import kotlinx.serialization.builtins.serializer | ||
import kotlinx.serialization.descriptors.SerialDescriptor | ||
import kotlinx.serialization.encoding.CompositeDecoder | ||
import kotlinx.serialization.encoding.Decoder | ||
|
||
abstract class CustomMapSerializer { | ||
private val keySerializer = String.serializer() | ||
val descriptor: SerialDescriptor | ||
get() = MapSerializer(keySerializer, ContextualSerializer(Any::class)).descriptor | ||
|
||
abstract fun decode(key: String, compositeDecoder: CompositeDecoder) | ||
|
||
fun <T> CompositeDecoder.decodeMapValue(valueSerializer: KSerializer<T>): T { | ||
val newDescriptor = MapSerializer(keySerializer, valueSerializer).descriptor | ||
val newIndex = decodeElementIndex(newDescriptor) | ||
return decodeSerializableElement(newDescriptor, newIndex, valueSerializer) | ||
} | ||
|
||
fun deserialize(decoder: Decoder) { | ||
var size = 0 | ||
val compositeDecoder = decoder.beginStructure(descriptor) | ||
while (true) { | ||
val index = compositeDecoder.decodeElementIndex(descriptor) | ||
if (index == CompositeDecoder.DECODE_DONE) break | ||
|
||
val startIndex = size * 2 | ||
val key: String = compositeDecoder.decodeSerializableElement(descriptor, startIndex + index, keySerializer) | ||
decode(key, compositeDecoder) | ||
size++ | ||
} | ||
compositeDecoder.endStructure(descriptor) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters