1 package net.pterodactylus.sone.template
3 import net.pterodactylus.util.template.*
6 class DurationFormatFilter : Filter {
8 override fun format(templateContext: TemplateContext?, data: Any?, parameters: Map<String, Any?>?): Any? {
10 val scale = parameters?.get("scale")
11 val duration = when (scale) {
12 "ms" -> Duration.ofSeconds(data.toLong() / 1_000, (data.toDouble() * 1_000_000 % 1_000_000_000).toLong())
13 "μs" -> Duration.ofSeconds(data.toLong() / 1_000_000, (data.toDouble() * 1_000 % 1_000_000_000).toLong())
14 "ns" -> Duration.ofSeconds(data.toLong() / 1_000_000_000, data.toLong() % 1_000_000_000)
15 else -> Duration.ofSeconds(data.toLong(), (data.toDouble() * 1_000_000_000 % 1_000_000_000).toLong())
17 return FixedDuration.values()
18 .map { it to it.number(duration) }
19 .firstOrNull { it.second >= 1 }
20 ?.let { "${"%.1f".format(it.second)}${it.first.symbol}" }
29 private enum class FixedDuration {
32 override fun number(duration: Duration) = DAYS.number(duration) / 7.0
33 override val symbol = "w"
36 override fun number(duration: Duration) = HOURS.number(duration) / 24
37 override val symbol = "d"
40 override fun number(duration: Duration) = MINUTES.number(duration) / 60
41 override val symbol = "h"
44 override fun number(duration: Duration) = SECONDS.number(duration) / 60
45 override val symbol = "m"
48 override fun number(duration: Duration) = duration.seconds + duration.nano / 1_000_000_000.0
49 override val symbol = "s"
52 override fun number(duration: Duration) = duration.nano / 1_000_000.0
53 override val symbol = "ms"
56 override fun number(duration: Duration) = duration.nano / 1_000.0
57 override val symbol = "μs"
60 override fun number(duration: Duration) = duration.nano.toDouble()
61 override val symbol = "ns"
64 abstract fun number(duration: Duration): Double
65 abstract val symbol: String