2023-01-12 11:52:54 +03:00
|
|
|
@file:Suppress("UNCHECKED_CAST")
|
|
|
|
|
|
|
|
package center.sciprog.attributes
|
|
|
|
|
|
|
|
import kotlinx.serialization.KSerializer
|
|
|
|
import kotlinx.serialization.descriptors.SerialDescriptor
|
|
|
|
import kotlinx.serialization.encoding.Decoder
|
|
|
|
import kotlinx.serialization.encoding.Encoder
|
2023-02-11 17:14:00 +03:00
|
|
|
import kotlinx.serialization.json.*
|
2023-01-12 11:52:54 +03:00
|
|
|
|
|
|
|
public class AttributesSerializer(
|
|
|
|
private val serializableAttributes: Set<SerializableAttribute<*>>,
|
|
|
|
) : KSerializer<Attributes> {
|
|
|
|
private val jsonSerializer = JsonObject.serializer()
|
|
|
|
override val descriptor: SerialDescriptor get() = jsonSerializer.descriptor
|
|
|
|
|
|
|
|
override fun deserialize(decoder: Decoder): Attributes {
|
|
|
|
val jsonElement = jsonSerializer.deserialize(decoder)
|
|
|
|
val attributeMap: Map<SerializableAttribute<*>, Any> = jsonElement.entries.associate { (key, element) ->
|
|
|
|
val attr = serializableAttributes.find { it.serialId == key }
|
|
|
|
?: error("Attribute serializer for key $key not found")
|
2023-02-11 17:14:00 +03:00
|
|
|
|
|
|
|
val json = if (decoder is JsonDecoder) {
|
|
|
|
decoder.json
|
|
|
|
} else {
|
|
|
|
Json { serializersModule = decoder.serializersModule }
|
|
|
|
}
|
|
|
|
val value = json.decodeFromJsonElement(attr.serializer, element) ?: error("Null values are not allowed")
|
2023-01-12 11:52:54 +03:00
|
|
|
|
|
|
|
attr to value
|
|
|
|
}
|
|
|
|
return Attributes(attributeMap)
|
|
|
|
}
|
|
|
|
|
|
|
|
override fun serialize(encoder: Encoder, value: Attributes) {
|
|
|
|
val json = buildJsonObject {
|
|
|
|
value.content.forEach { (key, value) ->
|
|
|
|
if (key !in serializableAttributes) error("An attribute key $key is not in the list of allowed attributes for this serializer")
|
|
|
|
val serializableKey = key as SerializableAttribute
|
2023-02-11 17:14:00 +03:00
|
|
|
|
|
|
|
val json = if (encoder is JsonEncoder) {
|
|
|
|
encoder.json
|
|
|
|
} else {
|
|
|
|
Json { serializersModule = encoder.serializersModule }
|
|
|
|
}
|
|
|
|
|
2023-01-12 11:52:54 +03:00
|
|
|
put(
|
|
|
|
serializableKey.serialId,
|
2023-02-11 17:14:00 +03:00
|
|
|
json.encodeToJsonElement(serializableKey.serializer as KSerializer<Any>, value)
|
2023-01-12 11:52:54 +03:00
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
jsonSerializer.serialize(encoder, json)
|
|
|
|
}
|
|
|
|
}
|