commonMain.components.DayOfWeek.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fluid-time-iosarm64 Show documentation
Show all versions of fluid-time-iosarm64 Show documentation
multiplatform date & time library
The newest version!
package com.github.fluidsonic.fluid.time
import kotlinx.serialization.*
import kotlinx.serialization.internal.*
@Serializable(with = DayOfWeekSerializer::class)
enum class DayOfWeek : DateTimeComponent {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday;
@Suppress("OVERRIDE_BY_INLINE")
override inline fun map(transform: (Long) -> Long) =
of(transform(toLong()))
override fun minus(other: DayOfWeek) =
Days(toLong() - other.toLong()) // FIXME check
override fun minus(other: Days) =
plus(-(other % 7))
override fun plus(other: Days) =
values()[((ordinal + (other.toLong() % 7) + 7) % 7).toInt()]
override fun toInt() =
ordinal + 1
override fun toLong() =
ordinal + 1L
override fun toString() =
name
companion object : DateTimeComponent.CompanionInterface {
override val max = sunday
override val min = monday
override fun of(value: Long) =
of(value, firstDayOfWeek = monday)
fun of(value: Long, firstDayOfWeek: DayOfWeek): DayOfWeek {
check(value, inRange = min.toLong() .. max.toLong(), name = "day [of week]")
return unchecked((value + firstDayOfWeek.ordinal) % 7)
}
fun serializer(): KSerializer =
DayOfWeekSerializer
internal fun unchecked(value: Long) =
values()[(value - 1).toInt()]
}
}
@Serializer(forClass = DayOfWeek::class)
internal object DayOfWeekSerializer : KSerializer {
override val descriptor = StringDescriptor.withName("com.github.fluidsonic.fluid.time.DayOfWeek")
override fun deserialize(decoder: Decoder) =
decoder.decodeString().let { string ->
DayOfWeek.values().firstOrNull { it.name == string }
?: throw SerializationException("Invalid day of week: $string - valid values: ${DayOfWeek.values().joinToString { it.name }}")
}
override fun serialize(encoder: Encoder, obj: DayOfWeek) {
encoder.encodeString(obj.name)
}
}