From 070626eac3a06d853be2b034d8e62a661c86a6f8 Mon Sep 17 00:00:00 2001 From: Boy Date: Sat, 5 Aug 2023 22:11:15 +0200 Subject: [PATCH] actually fix DurationSerializer --- .../serialization/DurationSerializer.kt | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/DurationSerializer.kt b/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/DurationSerializer.kt index 523ed4d..7511662 100644 --- a/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/DurationSerializer.kt +++ b/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/DurationSerializer.kt @@ -1,5 +1,6 @@ package com.mineinabyss.idofront.serialization +import com.mineinabyss.idofront.messaging.broadcast import com.mineinabyss.idofront.time.ticks import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind @@ -8,22 +9,37 @@ import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlin.time.Duration +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds object DurationSerializer : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Time", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Duration) = - encoder.encodeString(value.inWholeMilliseconds.toString()) + encoder.encodeString(value.toString()) override fun deserialize(decoder: Decoder): Duration { val string = decoder.decodeString() + broadcast(string) return Duration.parseOrNull(string) ?: fromString(decoder.decodeString()) ?: error("Not a valid duration: $string") } private fun fromString(string: String): Duration? { val splitAt = string.indexOfFirst { it.isLetter() }.takeIf { it > 0 } ?: string.length val value = string.take(splitAt).toDouble() - return if (string.drop(splitAt) == "t") value.toInt().ticks - else null + return when (string.drop(splitAt)) { + "ms" -> value.milliseconds + "t" -> value.toInt().ticks + "s" -> value.seconds + "m" -> value.minutes + "h" -> value.hours + "d" -> value.days + "w" -> value.days * 7 + "mo" -> value.days * 31 + else -> null + } } }