aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/util/SortedMapSerializer.kt
blob: baa10ad8e154d34d9d9b99bf5bb50d760bd14e60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package moe.nea.firmament.util

import java.util.SortedMap
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

class SortedMapSerializer<K : Comparable<K>, V>(val keyDelegate: KSerializer<K>, val valueDelegate: KSerializer<V>) :
    KSerializer<SortedMap<K, V>> {
    val mapSerializer = MapSerializer(keyDelegate, valueDelegate)
    override val descriptor: SerialDescriptor
        get() = mapSerializer.descriptor

    override fun deserialize(decoder: Decoder): SortedMap<K, V> {
        return (mapSerializer.deserialize(decoder).toSortedMap(Comparator.naturalOrder()))
    }

    override fun serialize(encoder: Encoder, value: SortedMap<K, V>) {
        mapSerializer.serialize(encoder, value)
    }
}