Skip to content

Commit

Permalink
actually fix DurationSerializer
Browse files Browse the repository at this point in the history
  • Loading branch information
Boy0000 committed Aug 5, 2023
1 parent c2f5b6e commit 070626e
Showing 1 changed file with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<Duration> {
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
}
}
}

0 comments on commit 070626e

Please sign in to comment.