Skip to content

Commit

Permalink
use Duration.parse and custom for ticks
Browse files Browse the repository at this point in the history
  • Loading branch information
Boy0000 committed Aug 5, 2023
1 parent 6553213 commit c2f5b6e
Showing 1 changed file with 4 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<Duration> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Time", PrimitiveKind.STRING)
Expand All @@ -21,22 +17,13 @@ object DurationSerializer : KSerializer<Duration> {

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

0 comments on commit c2f5b6e

Please sign in to comment.