From c2f5b6e433ab0984407ecfc64a06ac1320dd89bd Mon Sep 17 00:00:00 2001 From: Boy Date: Sat, 5 Aug 2023 21:43:05 +0200 Subject: [PATCH] use Duration.parse and custom for ticks --- .../serialization/DurationSerializer.kt | 21 ++++--------------- 1 file changed, 4 insertions(+), 17 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 a498a21..523ed4d 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 @@ -8,10 +8,6 @@ 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.minutes -import kotlin.time.Duration.Companion.seconds object DurationSerializer : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Time", PrimitiveKind.STRING) @@ -21,22 +17,13 @@ object DurationSerializer : KSerializer { override fun deserialize(decoder: Decoder): Duration { val string = decoder.decodeString() - return fromString(string) ?: error("Not a valid duration: $string") + return Duration.parseOrNull(string) ?: fromString(decoder.decodeString()) ?: error("Not a valid duration: $string") } - fun fromString(string: String): Duration? { + private fun fromString(string: String): Duration? { val splitAt = string.indexOfFirst { it.isLetter() }.takeIf { it > 0 } ?: string.length val value = string.take(splitAt).toDouble() - val ext = string.drop(splitAt) - return when (ext) { - "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 - } + return if (string.drop(splitAt) == "t") value.toInt().ticks + else null } }