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 + } } }