From 46ba81a45f7cb10c7f870bbf6946a46207ee353c Mon Sep 17 00:00:00 2001 From: Alessio Leonardo Tomei <122273875+T0mexX@users.noreply.github.com> Date: Tue, 18 Mar 2025 10:31:21 +0100 Subject: Unit System v2 (#243) * Separated `Time` unit into `TimeDelta` and `TimeStamp` + small fixes Addition and subtruction between `Timestamp`s is not allowed, but any other `Unit` operation/comparison is. `TimeDelta`s can be added/subtructed to/form `Timestamp`s. Deserialization of `Timestamp`: - `Number` -> interpreted as millis from Epoch - `Instant` (string representation) -> converted to Timestamp - `Duration` (string representation) -> interpreted as duration since Epoch (warn msg is logged) Deserialization of `TimeDelta` is the same as `Time` was before, with the diference that when an `Instant` is converted to an timedelta since Epoch a warning message is logged. * Unit System v2 - Merged `BoundedPercentage` and `UnboundedPercentage` - Overrided all operation defined in `Unit` in all subclasses to avoid as much as possible value classes being boxed in bytecode. If units are used as generics (hence also functions defined in Unit) they are boxed (as double would if used as generic). - All units companions now subclass `UnitId`, and can be used as keys (e.g `Map`), while offering `max` `min` and `zero` methods. - Division between the same unit now returns `Percentage` - Added `Iterable.averageOfUnitOrNull(selector (T) -> )` - `ifNeg0ThenPos0()` now is optional and not invoked on every constructor - Now methods in `Unit` are all abstract, forcing override and avoid boxing in some cases - Added `@UnintendedOperation` and `UnitOperationException` for methods that must be defined but are not intended for use (e.g. `Timestamp` + `Timestamp`) --- .../kotlin/org/opendc/common/units/DataRate.kt | 149 ++++++++-- .../kotlin/org/opendc/common/units/DataSize.kt | 152 ++++++++-- .../main/kotlin/org/opendc/common/units/Energy.kt | 145 +++++++++- .../kotlin/org/opendc/common/units/Frequency.kt | 148 +++++++++- .../kotlin/org/opendc/common/units/Percentage.kt | 312 ++++++++++----------- .../main/kotlin/org/opendc/common/units/Power.kt | 146 +++++++++- .../main/kotlin/org/opendc/common/units/Time.kt | 166 ----------- .../kotlin/org/opendc/common/units/TimeDelta.kt | 277 ++++++++++++++++++ .../kotlin/org/opendc/common/units/Timestamp.kt | 273 ++++++++++++++++++ .../main/kotlin/org/opendc/common/units/Unit.kt | 307 ++++++++++++++------ .../org/opendc/common/units/UnitSerializer.kt | 7 +- .../opendc/trace/util/parquet/exporter/Exporter.kt | 9 +- 12 files changed, 1588 insertions(+), 503 deletions(-) delete mode 100644 opendc-common/src/main/kotlin/org/opendc/common/units/Time.kt create mode 100644 opendc-common/src/main/kotlin/org/opendc/common/units/TimeDelta.kt create mode 100644 opendc-common/src/main/kotlin/org/opendc/common/units/Timestamp.kt diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/DataRate.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/DataRate.kt index 2af45b7b..15f69ebf 100644 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/DataRate.kt +++ b/opendc-common/src/main/kotlin/org/opendc/common/units/DataRate.kt @@ -20,13 +20,19 @@ * SOFTWARE. */ -@file:OptIn(InternalUse::class) +@file:OptIn(InternalUse::class, NonInlinableUnit::class) package org.opendc.common.units import kotlinx.serialization.Serializable import org.opendc.common.annotations.InternalUse -import org.opendc.common.units.Time.Companion.toTime +import org.opendc.common.units.TimeDelta.Companion.toTimeDelta +import org.opendc.common.utils.DFLT_MIN_EPS +import org.opendc.common.utils.approx +import org.opendc.common.utils.approxLarger +import org.opendc.common.utils.approxLargerOrEq +import org.opendc.common.utils.approxSmaller +import org.opendc.common.utils.approxSmallerOrEq import org.opendc.common.utils.ifNeg0thenPos0 import java.time.Duration @@ -40,8 +46,19 @@ public value class DataRate private constructor( // In bits/s. override val value: Double, ) : Unit { - @InternalUse - override fun new(value: Double): DataRate = DataRate(value.ifNeg0thenPos0()) + override fun toString(): String = fmtValue() + + public override fun fmtValue(fmt: String): String = + when (abs()) { + in zero..ofBps(100) -> "${String.format(fmt, tobps())} bps" + in ofbps(100)..ofKbps(100) -> "${String.format(fmt, toKbps())} Kbps" + in ofKbps(100)..ofMbps(100) -> "${String.format(fmt, toMbps())} Mbps" + else -> "${String.format(fmt, toGbps())} Gbps" + } + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Conversions to Double + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public fun tobps(): Double = value @@ -69,22 +86,118 @@ public value class DataRate private constructor( public fun toGBps(): Double = toGbps() / 8 - override fun toString(): String = fmtValue() + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Operation Override (to avoid boxing of value classes in byte code) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - public override fun fmtValue(fmt: String): String = - when (abs()) { - in ZERO..ofBps(100) -> "${String.format(fmt, tobps())} bps" - in ofbps(100)..ofKbps(100) -> "${String.format(fmt, toKbps())} Kbps" - in ofKbps(100)..ofMbps(100) -> "${String.format(fmt, toMbps())} Mbps" - else -> "${String.format(fmt, toGbps())} Gbps" + public override fun ifNeg0ThenPos0(): DataRate = DataRate(value.ifNeg0thenPos0()) + + public override operator fun plus(other: DataRate): DataRate = DataRate(value + other.value) + + public override operator fun minus(other: DataRate): DataRate = DataRate(value - other.value) + + public override operator fun div(scalar: Number): DataRate = DataRate(value / scalar.toDouble()) + + public override operator fun div(other: DataRate): Percentage = Percentage.ofRatio(value / other.value) + + public override operator fun times(scalar: Number): DataRate = DataRate(value * scalar.toDouble()) + + public override operator fun times(percentage: Percentage): DataRate = DataRate(value * percentage.value) + + public override operator fun unaryMinus(): DataRate = DataRate(-value) + + public override operator fun compareTo(other: DataRate): Int = this.value.compareTo(other.value) + + public override fun isZero(): Boolean = value == .0 + + public override fun approxZero(epsilon: Double): Boolean = value.approx(.0, epsilon = epsilon) + + public override fun approx( + other: DataRate, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this == other || this.value.approx(other.value, minEpsilon, epsilon) + + public override infix fun approx(other: DataRate): Boolean = approx(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLarger( + other: DataRate, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLarger(other.value, minEpsilon, epsilon) + + public override infix fun approxLarger(other: DataRate): Boolean = approxLarger(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLargerOrEq( + other: DataRate, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLargerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxLargerOrEq(other: DataRate): Boolean = approxLargerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmaller( + other: DataRate, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmaller(other.value, minEpsilon, epsilon) + + public override infix fun approxSmaller(other: DataRate): Boolean = approxSmaller(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmallerOrEq( + other: DataRate, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmallerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxSmallerOrEq(other: DataRate): Boolean = approxSmallerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override infix fun max(other: DataRate): DataRate = if (this.value > other.value) this else other + + public override infix fun min(other: DataRate): DataRate = if (this.value < other.value) this else other + + public override fun abs(): DataRate = DataRate(kotlin.math.abs(value)) + + public override fun roundToIfWithinEpsilon( + to: DataRate, + epsilon: Double, + ): DataRate = + if (this.value in (to.value - epsilon)..(to.value + epsilon)) { + to + } else { + this } - public operator fun times(time: Time): DataSize = DataSize.ofKiB(toKiBps() * time.toSec()) + public fun max( + a: DataRate, + b: DataRate, + ): DataRate = if (a.value > b.value) a else b + + public fun min( + a: DataRate, + b: DataRate, + ): DataRate = if (a.value < b.value) a else b + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Unit Specific Operations + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public operator fun times(timeDelta: TimeDelta): DataSize = DataSize.ofKiB(toKiBps() * timeDelta.toSec()) - public operator fun times(duration: Duration): DataSize = this * duration.toTime() + public operator fun times(duration: Duration): DataSize = this * duration.toTimeDelta() - public companion object { - @JvmStatic public val ZERO: DataRate = DataRate(.0) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Companion + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public companion object : UnitId { + @JvmStatic override val zero: DataRate = DataRate(.0) + + @JvmStatic override val max: DataRate = DataRate(Double.MAX_VALUE) + + @JvmStatic override val min: DataRate = DataRate(Double.MIN_VALUE) + + public operator fun Number.times(unit: DataRate): DataRate = unit * this @JvmStatic @JvmName("ofbps") @@ -142,9 +255,13 @@ public value class DataRate private constructor( @JvmName("ofGBps") public fun ofGBps(gBps: Number): DataRate = ofGbps(gBps.toDouble() * 8) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Serializer + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** * Serializer for [DataRate] value class. It needs to be a compile - * time constant in order to be used as serializer automatically, + * time constant to be used as serializer automatically, * hence `object :` instead of class instantiation. * * ```json diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/DataSize.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/DataSize.kt index e32d9e88..a17fda4c 100644 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/DataSize.kt +++ b/opendc-common/src/main/kotlin/org/opendc/common/units/DataSize.kt @@ -20,14 +20,21 @@ * SOFTWARE. */ -@file:OptIn(InternalUse::class) +@file:OptIn(InternalUse::class, NonInlinableUnit::class) package org.opendc.common.units import kotlinx.serialization.Serializable import org.opendc.common.annotations.InternalUse -import org.opendc.common.units.Time.Companion.toTime +import org.opendc.common.units.TimeDelta.Companion.toTimeDelta +import org.opendc.common.utils.DFLT_MIN_EPS +import org.opendc.common.utils.approx +import org.opendc.common.utils.approxLarger +import org.opendc.common.utils.approxLargerOrEq +import org.opendc.common.utils.approxSmaller +import org.opendc.common.utils.approxSmallerOrEq import org.opendc.common.utils.fmt +import org.opendc.common.utils.ifNeg0thenPos0 import java.time.Duration /** @@ -40,8 +47,19 @@ public value class DataSize private constructor( // In MiB. override val value: Double, ) : Unit { - @InternalUse - override fun new(value: Double): DataSize = DataSize(value) + override fun toString(): String = fmtValue() + + override fun fmtValue(fmt: String): String = + when (abs()) { + in zero..ofBytes(100) -> "${toBytes().fmt(fmt)} Bytes" + in ofBytes(100)..ofKiB(100) -> "${toKiB().fmt(fmt)} KiB" + in ofKiB(100)..ofMiB(100) -> "${toMiB().fmt(fmt)} MiB" + else -> "${toGiB().fmt(fmt)} GiB" + } + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Conversions to Double + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public fun toBits(): Double = toKib() * 1024 @@ -83,22 +101,120 @@ public value class DataSize private constructor( public fun toTiB(): Double = toGiB() / 1024 - override fun toString(): String = fmtValue() + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Operation Override (to avoid boxing of value classes in byte code) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - override fun fmtValue(fmt: String): String = - when (abs()) { - in ZERO..ofBytes(100) -> "${toBytes().fmt(fmt)} Bytes" - in ofBytes(100)..ofKiB(100) -> "${toKiB().fmt(fmt)} KiB" - in ofKiB(100)..ofMiB(100) -> "${toMiB().fmt(fmt)} MiB" - else -> "${toGiB().fmt(fmt)} GiB" + public override fun ifNeg0ThenPos0(): DataSize = DataSize(value.ifNeg0thenPos0()) + + public override operator fun plus(other: DataSize): DataSize = DataSize(value + other.value) + + public override operator fun minus(other: DataSize): DataSize = DataSize(value - other.value) + + public override operator fun div(scalar: Number): DataSize = DataSize(value / scalar.toDouble()) + + public override operator fun div(other: DataSize): Percentage = Percentage.ofRatio(value / other.value) + + public override operator fun times(scalar: Number): DataSize = DataSize(value * scalar.toDouble()) + + public override operator fun times(percentage: Percentage): DataSize = DataSize(value * percentage.value) + + public override operator fun unaryMinus(): DataSize = DataSize(-value) + + public override operator fun compareTo(other: DataSize): Int = this.value.compareTo(other.value) + + public override fun isZero(): Boolean = value == .0 + + public override fun approxZero(epsilon: Double): Boolean = value.approx(.0, epsilon = epsilon) + + public override fun approx( + other: DataSize, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this == other || this.value.approx(other.value, minEpsilon, epsilon) + + public override infix fun approx(other: DataSize): Boolean = approx(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLarger( + other: DataSize, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLarger(other.value, minEpsilon, epsilon) + + public override infix fun approxLarger(other: DataSize): Boolean = approxLarger(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLargerOrEq( + other: DataSize, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLargerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxLargerOrEq(other: DataSize): Boolean = approxLargerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmaller( + other: DataSize, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmaller(other.value, minEpsilon, epsilon) + + public override infix fun approxSmaller(other: DataSize): Boolean = approxSmaller(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmallerOrEq( + other: DataSize, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmallerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxSmallerOrEq(other: DataSize): Boolean = approxSmallerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override infix fun max(other: DataSize): DataSize = if (this.value > other.value) this else other + + public override infix fun min(other: DataSize): DataSize = if (this.value < other.value) this else other + + public override fun abs(): DataSize = DataSize(kotlin.math.abs(value)) + + public override fun roundToIfWithinEpsilon( + to: DataSize, + epsilon: Double, + ): DataSize = + if (this.value in (to.value - epsilon)..(to.value + epsilon)) { + to + } else { + this } - public operator fun div(time: Time): DataRate = DataRate.ofKBps(this.toKiB() / time.toSec()) + public fun max( + a: DataSize, + b: DataSize, + ): DataSize = if (a.value > b.value) a else b + + public fun min( + a: DataSize, + b: DataSize, + ): DataSize = if (a.value < b.value) a else b + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Unit Specific Operations + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public operator fun div(timeDelta: TimeDelta): DataRate = DataRate.ofKBps(this.toKiB() / timeDelta.toSec()) - public operator fun div(duration: Duration): DataRate = this / duration.toTime() + public operator fun div(duration: Duration): DataRate = this / duration.toTimeDelta() - public companion object { - @JvmStatic public val ZERO: DataSize = DataSize(.0) + public operator fun div(dataRate: DataRate): TimeDelta = TimeDelta.ofSec(this.toKb() / dataRate.toKbps()) + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Companion + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public companion object : UnitId { + @JvmStatic override val zero: DataSize = DataSize(.0) + + @JvmStatic override val max: DataSize = DataSize(Double.MAX_VALUE) + + @JvmStatic override val min: DataSize = DataSize(Double.MIN_VALUE) + + public operator fun Number.times(unit: DataSize): DataSize = unit * this @JvmStatic @JvmName("ofBits") @@ -176,9 +292,13 @@ public value class DataSize private constructor( @JvmName("ofTiB") public fun ofTiB(tiB: Number): DataSize = ofGiB(tiB.toDouble() * 1024) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Serializer + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** * Serializer for [DataSize] value class. It needs to be a compile - * time constant in order to be used as serializer automatically, + * time constant to be used as serializer automatically, * hence `object :` instead of class instantiation. * * ```json diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/Energy.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/Energy.kt index 467192a0..f54fe515 100644 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/Energy.kt +++ b/opendc-common/src/main/kotlin/org/opendc/common/units/Energy.kt @@ -20,13 +20,19 @@ * SOFTWARE. */ -@file:OptIn(InternalUse::class) +@file:OptIn(InternalUse::class, NonInlinableUnit::class) package org.opendc.common.units import kotlinx.serialization.Serializable import org.opendc.common.annotations.InternalUse -import org.opendc.common.units.Time.Companion.toTime +import org.opendc.common.units.TimeDelta.Companion.toTimeDelta +import org.opendc.common.utils.DFLT_MIN_EPS +import org.opendc.common.utils.approx +import org.opendc.common.utils.approxLarger +import org.opendc.common.utils.approxLargerOrEq +import org.opendc.common.utils.approxSmaller +import org.opendc.common.utils.approxSmallerOrEq import org.opendc.common.utils.fmt import org.opendc.common.utils.ifNeg0thenPos0 import java.time.Duration @@ -42,7 +48,18 @@ public value class Energy private constructor( // In Joule override val value: Double, ) : Unit { - override fun new(value: Double): Energy = Energy(value.ifNeg0thenPos0()) + override fun toString(): String = fmtValue() + + override fun fmtValue(fmt: String): String = + if (value <= 1000.0) { + "${toJoule().fmt(fmt)} Joule" + } else { + "${toKJoule().fmt(fmt)} KJoule" + } + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Conversions to Double + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public fun toJoule(): Double = value @@ -52,22 +69,118 @@ public value class Energy private constructor( public fun toKWh(): Double = toWh() / 1000 - override fun toString(): String = fmtValue() + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Operation Override (to avoid boxing of value classes in byte code) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - override fun fmtValue(fmt: String): String = - if (value >= 1000.0) { - "${toJoule().fmt(fmt)} Joule" + public override fun ifNeg0ThenPos0(): Energy = Energy(value.ifNeg0thenPos0()) + + public override operator fun plus(other: Energy): Energy = Energy(value + other.value) + + public override operator fun minus(other: Energy): Energy = Energy(value - other.value) + + public override operator fun div(scalar: Number): Energy = Energy(value / scalar.toDouble()) + + public override operator fun div(other: Energy): Percentage = Percentage.ofRatio(value / other.value) + + public override operator fun times(scalar: Number): Energy = Energy(value * scalar.toDouble()) + + public override operator fun times(percentage: Percentage): Energy = Energy(value * percentage.value) + + public override operator fun unaryMinus(): Energy = Energy(-value) + + public override operator fun compareTo(other: Energy): Int = this.value.compareTo(other.value) + + public override fun isZero(): Boolean = value == .0 + + public override fun approxZero(epsilon: Double): Boolean = value.approx(.0, epsilon = epsilon) + + public override fun approx( + other: Energy, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this == other || this.value.approx(other.value, minEpsilon, epsilon) + + public override infix fun approx(other: Energy): Boolean = approx(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLarger( + other: Energy, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLarger(other.value, minEpsilon, epsilon) + + public override infix fun approxLarger(other: Energy): Boolean = approxLarger(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLargerOrEq( + other: Energy, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLargerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxLargerOrEq(other: Energy): Boolean = approxLargerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmaller( + other: Energy, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmaller(other.value, minEpsilon, epsilon) + + public override infix fun approxSmaller(other: Energy): Boolean = approxSmaller(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmallerOrEq( + other: Energy, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmallerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxSmallerOrEq(other: Energy): Boolean = approxSmallerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override infix fun max(other: Energy): Energy = if (this.value > other.value) this else other + + public override infix fun min(other: Energy): Energy = if (this.value < other.value) this else other + + public override fun abs(): Energy = Energy(kotlin.math.abs(value)) + + public override fun roundToIfWithinEpsilon( + to: Energy, + epsilon: Double, + ): Energy = + if (this.value in (to.value - epsilon)..(to.value + epsilon)) { + to } else { - "${toKJoule().fmt(fmt)} KJoule" + this } - public operator fun div(time: Time): Power = Power.ofWatts(toWh() / time.toHours()) + public fun max( + a: Energy, + b: Energy, + ): Energy = if (a.value > b.value) a else b - public operator fun div(duration: Duration): Power = this / duration.toTime() + public fun min( + a: Energy, + b: Energy, + ): Energy = if (a.value < b.value) a else b - public companion object { - @JvmStatic - public val ZERO: Energy = Energy(.0) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Unit Specific Operations + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public operator fun div(timeDelta: TimeDelta): Power = Power.ofWatts(toWh() / timeDelta.toHours()) + + public operator fun div(duration: Duration): Power = this / duration.toTimeDelta() + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Companion + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public companion object : UnitId { + @JvmStatic override val zero: Energy = Energy(.0) + + @JvmStatic override val max: Energy = Energy(Double.MAX_VALUE) + + @JvmStatic override val min: Energy = Energy(Double.MIN_VALUE) + + public operator fun Number.times(unit: Frequency): Frequency = unit * this @JvmStatic @JvmName("ofJoule") @@ -87,9 +200,13 @@ public value class Energy private constructor( private val JOULES = Regex("\\s*(?:j|(?:joule|Joule)(?:|s))") + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Serializer + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** * Serializer for [Energy] value class. It needs to be a compile - * time constant in order to be used as serializer automatically, + * time constant to be used as serializer automatically, * hence `object :` instead of class instantiation. * * ```json diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/Frequency.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/Frequency.kt index df1b49f6..4ffb3992 100644 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/Frequency.kt +++ b/opendc-common/src/main/kotlin/org/opendc/common/units/Frequency.kt @@ -20,13 +20,19 @@ * SOFTWARE. */ -@file:OptIn(InternalUse::class) +@file:OptIn(InternalUse::class, NonInlinableUnit::class) package org.opendc.common.units import kotlinx.serialization.Serializable import org.opendc.common.annotations.InternalUse -import org.opendc.common.units.Time.Companion.toTime +import org.opendc.common.units.TimeDelta.Companion.toTimeDelta +import org.opendc.common.utils.DFLT_MIN_EPS +import org.opendc.common.utils.approx +import org.opendc.common.utils.approxLarger +import org.opendc.common.utils.approxLargerOrEq +import org.opendc.common.utils.approxSmaller +import org.opendc.common.utils.approxSmallerOrEq import org.opendc.common.utils.fmt import org.opendc.common.utils.ifNeg0thenPos0 import java.time.Duration @@ -42,7 +48,19 @@ public value class Frequency private constructor( // As MHz. override val value: Double, ) : Unit { - override fun new(value: Double): Frequency = Frequency(value.ifNeg0thenPos0().also { check(it >= .0) }) + override fun toString(): String = fmtValue() + + override fun fmtValue(fmt: String): String = + when (abs()) { + in zero..ofHz(500) -> "${toHz().fmt(fmt)} Hz" + in ofHz(500)..ofKHz(500) -> "${toKHz().fmt(fmt)} KHz" + in ofKHz(500)..ofMHz(500) -> "${toMHz().fmt(fmt)} MHz" + else -> "${toGHz().fmt(fmt)} GHz" + } + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Conversions to Double + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public fun toHz(): Double = value * 1e6 @@ -52,22 +70,118 @@ public value class Frequency private constructor( public fun toGHz(): Double = value / 1e3 - override fun toString(): String = fmtValue() + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Operation Override (to avoid boxing of value classes in byte code) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - override fun fmtValue(fmt: String): String = - when (abs()) { - in ZERO..ofHz(500) -> "${toHz().fmt(fmt)} Hz" - in ofHz(500)..ofKHz(500) -> "${toKHz().fmt(fmt)} KHz" - in ofKHz(500)..ofMHz(500) -> "${toMHz().fmt(fmt)} MHz" - else -> "${toGHz().fmt(fmt)} GHz" + public override fun ifNeg0ThenPos0(): Frequency = Frequency(value.ifNeg0thenPos0()) + + public override operator fun plus(other: Frequency): Frequency = Frequency(value + other.value) + + public override operator fun minus(other: Frequency): Frequency = Frequency(value - other.value) + + public override operator fun div(scalar: Number): Frequency = Frequency(value / scalar.toDouble()) + + public override operator fun div(other: Frequency): Percentage = Percentage.ofRatio(value / other.value) + + public override operator fun times(scalar: Number): Frequency = Frequency(value * scalar.toDouble()) + + public override operator fun times(percentage: Percentage): Frequency = Frequency(value * percentage.value) + + public override operator fun unaryMinus(): Frequency = Frequency(-value) + + public override operator fun compareTo(other: Frequency): Int = this.value.compareTo(other.value) + + public override fun isZero(): Boolean = value == .0 + + public override fun approxZero(epsilon: Double): Boolean = value.approx(.0, epsilon = epsilon) + + public override fun approx( + other: Frequency, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this == other || this.value.approx(other.value, minEpsilon, epsilon) + + public override infix fun approx(other: Frequency): Boolean = approx(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLarger( + other: Frequency, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLarger(other.value, minEpsilon, epsilon) + + public override infix fun approxLarger(other: Frequency): Boolean = approxLarger(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLargerOrEq( + other: Frequency, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLargerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxLargerOrEq(other: Frequency): Boolean = approxLargerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmaller( + other: Frequency, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmaller(other.value, minEpsilon, epsilon) + + public override infix fun approxSmaller(other: Frequency): Boolean = approxSmaller(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmallerOrEq( + other: Frequency, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmallerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxSmallerOrEq(other: Frequency): Boolean = approxSmallerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override infix fun max(other: Frequency): Frequency = if (this.value > other.value) this else other + + public override infix fun min(other: Frequency): Frequency = if (this.value < other.value) this else other + + public override fun abs(): Frequency = Frequency(kotlin.math.abs(value)) + + public override fun roundToIfWithinEpsilon( + to: Frequency, + epsilon: Double, + ): Frequency = + if (this.value in (to.value - epsilon)..(to.value + epsilon)) { + to + } else { + this } - public operator fun times(time: Time): Double = toHz() * time.toSec() + public fun max( + a: Frequency, + b: Frequency, + ): Frequency = if (a.value > b.value) a else b + + public fun min( + a: Frequency, + b: Frequency, + ): Frequency = if (a.value < b.value) a else b + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Unit Specific Operations + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public operator fun times(timeDelta: TimeDelta): Double = toHz() * timeDelta.toSec() - public operator fun times(duration: Duration): Double = toHz() * duration.toTime().toSec() + public operator fun times(duration: Duration): Double = toHz() * duration.toTimeDelta().toSec() - public companion object { - @JvmStatic public val ZERO: Frequency = Frequency(.0) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Companion + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public companion object : UnitId { + @JvmStatic override val zero: Frequency = Frequency(.0) + + @JvmStatic override val max: Frequency = Frequency(Double.MAX_VALUE) + + @JvmStatic override val min: Frequency = Frequency(Double.MIN_VALUE) + + public operator fun Number.times(unit: Frequency): Frequency = unit * this @JvmStatic @JvmName("ofHz") @@ -87,9 +201,13 @@ public value class Frequency private constructor( private val HERTZ = Regex("\\s*(?:Hz|Hertz|hz|hertz)\\s*?") + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Serializer + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** * Serializer for [Frequency] value class. It needs to be a compile - * time constant in order to be used as serializer automatically, + * time constant to be used as serializer automatically, * hence `object :` instead of class instantiation. * * ```json diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/Percentage.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/Percentage.kt index 377fdecc..b9f8f7ae 100644 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/Percentage.kt +++ b/opendc-common/src/main/kotlin/org/opendc/common/units/Percentage.kt @@ -20,38 +20,53 @@ * SOFTWARE. */ -@file:OptIn(InternalUse::class) +@file:OptIn(InternalUse::class, NonInlinableUnit::class) package org.opendc.common.units import kotlinx.serialization.Serializable -import mu.KotlinLogging import org.opendc.common.annotations.InternalUse +import org.opendc.common.utils.DFLT_MIN_EPS +import org.opendc.common.utils.approx +import org.opendc.common.utils.approxLarger +import org.opendc.common.utils.approxLargerOrEq +import org.opendc.common.utils.approxSmaller +import org.opendc.common.utils.approxSmallerOrEq import org.opendc.common.utils.fmt import org.opendc.common.utils.ifNeg0thenPos0 import kotlin.text.RegexOption.IGNORE_CASE /** - * Represents a percentage. This interface has 2 value classes implementations. - * - * Using the interface instead of its implementation will likely result in worse - * performances compared to using the value-classes themselves, - * since the jvm will allocate an object for the interface. Therefore, it is suggested - * to use the interface as little as possible. Operations between the same implementation - * ([BoundedPercentage] + [BoundedPercentage]) will result in the same return type. - * - * [BoundedPercentage]s are adjusted to remain in range 0-100%, - * logging warning whenever an adjustment has been made. + * Represents a percentage. * * As all [Unit]s, offers the vast majority * of mathematical operations that one would perform on a simple [Double]. */ + +@JvmInline @Serializable(with = Percentage.Companion.PercentageSerializer::class) -public sealed interface Percentage : Unit { - override val value: Double +public value class Percentage( + override val value: Double, +) : Unit { + override fun toString(): String = fmtValue() + + /** + * ```kotlin + * // e.g. + * val perc: Percentage = Percentage.ofRatio(0.123456789) + * perc.fmtValue("%.4f") // "12.3456%" + * ``` + * + * @see[Unit.fmtValue] + */ + override fun fmtValue(fmt: String): String = "${toPercentageValue().fmt(fmt)}%" + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Conversions to Double + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** - * @return the value as a ratio (e.g. 50% -> 0.5) + * @return the value as a ratio (e.g., 50% -> 0.5) */ public fun toRatio(): Double = value @@ -60,75 +75,145 @@ public sealed interface Percentage : Unit { */ public fun toPercentageValue(): Double = value * 1e2 - /** - * @return *this* percentage converted to [BoundedPercentage]. - */ - public fun toBoundedPercentage(): BoundedPercentage + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Operation Override (to avoid boxing of value classes in byte code) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * @return *this* percentage converted to [UnboundedPercentage]. - */ - public fun toUnboundedPercentage(): UnboundedPercentage + public override fun ifNeg0ThenPos0(): Percentage = Percentage(value.ifNeg0thenPos0()) - /** - * ```kotlin - * // e.g. - * val perc: Percentage = Percentage.ofRatio(0.123456789) - * perc.fmtValue("%.4f") // "12.3456%" - * ``` - * - * @see[Unit.fmtValue] - */ - override fun fmtValue(fmt: String): String = "${toPercentageValue().fmt(fmt)}%" + public override operator fun plus(other: Percentage): Percentage = Percentage(value + other.value) - public companion object { - @JvmStatic public val ZERO: Percentage = UnboundedPercentage(.0) + public override operator fun minus(other: Percentage): Percentage = Percentage(value - other.value) - @JvmStatic - @JvmName("ofRatio") - public fun ofRatio(ratio: Double): UnboundedPercentage = UnboundedPercentage(ratio) + public override operator fun div(scalar: Number): Percentage = Percentage(value / scalar.toDouble()) - @JvmStatic - @JvmName("ofRatioBounded") - public fun ofRatioBounded(ratio: Double): BoundedPercentage = BoundedPercentage(ratio) + public override operator fun div(other: Percentage): Percentage = Percentage.ofRatio(value / other.value) + + public override operator fun times(scalar: Number): Percentage = Percentage(value * scalar.toDouble()) + + public override operator fun times(percentage: Percentage): Percentage = Percentage(value * percentage.value) + + public override operator fun unaryMinus(): Percentage = Percentage(-value) + + public override operator fun compareTo(other: Percentage): Int = this.value.compareTo(other.value) + + public override fun isZero(): Boolean = value == .0 + + public override fun approxZero(epsilon: Double): Boolean = value.approx(.0, epsilon = epsilon) + + public override fun approx( + other: Percentage, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this == other || this.value.approx(other.value, minEpsilon, epsilon) + + public override infix fun approx(other: Percentage): Boolean = approx(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLarger( + other: Percentage, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLarger(other.value, minEpsilon, epsilon) + + public override infix fun approxLarger(other: Percentage): Boolean = approxLarger(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLargerOrEq( + other: Percentage, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLargerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxLargerOrEq(other: Percentage): Boolean = approxLargerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmaller( + other: Percentage, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmaller(other.value, minEpsilon, epsilon) + + public override infix fun approxSmaller(other: Percentage): Boolean = approxSmaller(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmallerOrEq( + other: Percentage, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmallerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxSmallerOrEq(other: Percentage): Boolean = approxSmallerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override infix fun max(other: Percentage): Percentage = if (this.value > other.value) this else other + + public override infix fun min(other: Percentage): Percentage = if (this.value < other.value) this else other + + public override fun abs(): Percentage = Percentage(kotlin.math.abs(value)) + + public override fun roundToIfWithinEpsilon( + to: Percentage, + epsilon: Double, + ): Percentage = + if (this.value in (to.value - epsilon)..(to.value + epsilon)) { + to + } else { + this + } + + public fun max( + a: Percentage, + b: Percentage, + ): Percentage = if (a.value > b.value) a else b + + public fun min( + a: Percentage, + b: Percentage, + ): Percentage = if (a.value < b.value) a else b + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Unit Specific Operations + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Companion + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public companion object : UnitId { + @JvmStatic override val zero: Percentage = Percentage(.0) + + @JvmStatic override val max: Percentage = Percentage(Double.MAX_VALUE) + + @JvmStatic override val min: Percentage = Percentage(Double.MIN_VALUE) + + public operator fun Number.times(unit: Percentage): Percentage = unit * this @JvmStatic - @JvmName("ofPercentage") - public fun ofPercentage(percentage: Number): UnboundedPercentage = UnboundedPercentage(percentage.toDouble() / 100) + @JvmName("ofRatio") + public fun ofRatio(ratio: Double): Percentage = Percentage(ratio) @JvmStatic - @JvmName("ofPercentageBounded") - public fun ofPercentageBounded(percentage: Double): BoundedPercentage = BoundedPercentage(percentage / 100) + @JvmName("ofPercentage") + public fun ofPercentage(percentage: Number): Percentage = Percentage(percentage.toDouble() / 100) /** * @return the percentage resulting from [this] / [other]. */ - public infix fun Number.percentageOf(other: Number): UnboundedPercentage = UnboundedPercentage(this.toDouble() / other.toDouble()) + public infix fun Number.percentageOf(other: Number): Percentage = Percentage(this.toDouble() / other.toDouble()) /** - * @return the *bounded* percentage resulting from [this] / [other]. + * @return the percentage resulting from [this] / [other], applicable on all [Unit]s of the same type. */ - public infix fun Number.boundedPercentageOf(other: Number): BoundedPercentage = - BoundedPercentage(this.toDouble() / other.toDouble()) + public infix fun > T.percentageOf(other: T): Percentage = Percentage(this.value / other.value) - /** - * @return the percentage resulting from [this] / [other], applicable on all [Unit]s of same type. - */ - public infix fun > T.percentageOf(other: T): UnboundedPercentage = UnboundedPercentage(this.value / other.value) - - /** - * @return the *bounded* percentage resulting from [this] / [other], applicable on all [Unit]s of same type. - */ - public infix fun > T.boundedPercentageOf(other: T): BoundedPercentage = BoundedPercentage(this.value / other.value) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Serializer + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// private val PERCENTAGE = Regex("\\s*(?:percentage|Percentage|%)\\s*?") /** * Serializer for [Percentage] value class. It needs to be a compile - * time constant in order to be used as serializer automatically, + * time constant to be used as serializer automatically, * hence `object :` instead of class instantiation. * - * For implementation purposes it always deserialize an [UnboundedPercentage] as [Percentage]. + * For implementation purposes it always deserializes an [Percentage] as [Percentage]. * * ```json * // e.g. @@ -151,110 +236,3 @@ public sealed interface Percentage : Unit { ) } } - -/** - * Bounded implementation of [Percentage], meaning the - * percentage value is adjusted to always be in the range 0-100%, - * logging a warning whenever an adjustment has been made. - */ -@JvmInline -public value class BoundedPercentage - @InternalUse - internal constructor( - override val value: Double, - ) : Percentage { - override fun toBoundedPercentage(): BoundedPercentage = this - - override fun toUnboundedPercentage(): UnboundedPercentage = UnboundedPercentage(value) - - override fun new(value: Double): BoundedPercentage = BoundedPercentage(value.forceInRange().ifNeg0thenPos0()) - - override fun toString(): String = fmtValue() - - /** - * "Override" to return [BoundedPercentage] insteadof [Percentage]. - * @see[Unit.plus] - */ - public infix operator fun plus(other: BoundedPercentage): BoundedPercentage = BoundedPercentage(this.value + other.value) - - /** - * "Override" to return [BoundedPercentage] insteadof [Percentage]. - * @see[Unit.minus] - */ - public infix operator fun minus(other: BoundedPercentage): BoundedPercentage = BoundedPercentage(this.value - other.value) - - /** - * Override to return [BoundedPercentage] insteadof [Percentage]. - * @see[Unit.times] - */ - override operator fun times(scalar: Number): BoundedPercentage = BoundedPercentage(this.value * scalar.toDouble()) - - /** - * Override to return [BoundedPercentage] insteadof [Percentage]. - * @see[Unit.div] - */ - override operator fun div(scalar: Number): BoundedPercentage = BoundedPercentage(this.value / scalar.toDouble()) - - private fun Double.forceInRange( - from: Double = .0, - to: Double = 1.0, - ): Double = - if (this < from) { - LOG.warn("bounded percentage has been rounded up (from ${this * 1e2}% to ${from * 1e2}%") - from - } else if (this > to) { - LOG.warn("bounded percentage has been rounded down (from ${this * 1e2}% to ${to * 1e2}%") - to - } else { - this - } - - public companion object { - // TODO: replace with `by logger()` if pr #241 is approved - private val LOG = KotlinLogging.logger(name = this::class.java.enclosingClass.simpleName) - } - } - -/** - * Unbounded implementation of [Percentage], meaning the - * percentage value is allowed to be outside the range 0-100%. - */ -@JvmInline -public value class UnboundedPercentage - @InternalUse - internal constructor( - override val value: Double, - ) : Percentage { - override fun toBoundedPercentage(): BoundedPercentage = BoundedPercentage(value.ifNeg0thenPos0()) - - override fun toUnboundedPercentage(): UnboundedPercentage = this - - @InternalUse - override fun new(value: Double): UnboundedPercentage = UnboundedPercentage(value) - - override fun toString(): String = fmtValue() - - /** - * "Override" to return [UnboundedPercentage] insteadof [Percentage]. - * @see[Unit.plus] - */ - public infix operator fun plus(other: UnboundedPercentage): UnboundedPercentage = UnboundedPercentage(this.value + other.value) - - /** - * "Override" to return [UnboundedPercentage] insteadof [Percentage]. - * @see[Unit.minus] - */ - public infix operator fun minus(other: UnboundedPercentage): UnboundedPercentage = UnboundedPercentage(this.value - other.value) - - /** - * Override to return [UnboundedPercentage] insteadof [Percentage]. - * @see[Unit.times] - */ - override operator fun times(scalar: Number): UnboundedPercentage = UnboundedPercentage(this.value * scalar.toDouble()) - - /** - * Override to return [UnboundedPercentage] insteadof [Percentage]. - * @see[Unit.div] - */ - override operator fun div(scalar: Number): UnboundedPercentage = UnboundedPercentage(this.value / scalar.toDouble()) - } diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/Power.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/Power.kt index fc9f6bf4..85fb95ae 100644 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/Power.kt +++ b/opendc-common/src/main/kotlin/org/opendc/common/units/Power.kt @@ -20,13 +20,19 @@ * SOFTWARE. */ -@file:OptIn(InternalUse::class) +@file:OptIn(InternalUse::class, NonInlinableUnit::class) package org.opendc.common.units import kotlinx.serialization.Serializable import org.opendc.common.annotations.InternalUse -import org.opendc.common.units.Time.Companion.toTime +import org.opendc.common.units.TimeDelta.Companion.toTimeDelta +import org.opendc.common.utils.DFLT_MIN_EPS +import org.opendc.common.utils.approx +import org.opendc.common.utils.approxLarger +import org.opendc.common.utils.approxLargerOrEq +import org.opendc.common.utils.approxSmaller +import org.opendc.common.utils.approxSmallerOrEq import org.opendc.common.utils.fmt import org.opendc.common.utils.ifNeg0thenPos0 import java.time.Duration @@ -42,13 +48,6 @@ public value class Power private constructor( // In Watts. override val value: Double, ) : Unit { - @InternalUse - override fun new(value: Double): Power = Power(value.ifNeg0thenPos0()) - - public fun toWatts(): Double = value - - public fun toKWatts(): Double = value / 1000.0 - override fun toString(): String = fmtValue() override fun fmtValue(fmt: String): String = @@ -58,13 +57,126 @@ public value class Power private constructor( "${toWatts().fmt(fmt)} Watts" } - public operator fun times(time: Time): Energy = Energy.ofWh(toWatts() * time.toHours()) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Conversions to Double + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public fun toWatts(): Double = value - public operator fun times(duration: Duration): Energy = this * duration.toTime() + public fun toKWatts(): Double = value / 1000.0 - public companion object { - @JvmStatic - public val ZERO: Power = Power(.0) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Operation Override (to avoid boxing of value classes in byte code) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public override fun ifNeg0ThenPos0(): Power = Power(value.ifNeg0thenPos0()) + + public override operator fun plus(other: Power): Power = Power(value + other.value) + + public override operator fun minus(other: Power): Power = Power(value - other.value) + + public override operator fun div(scalar: Number): Power = Power(value / scalar.toDouble()) + + public override operator fun div(other: Power): Percentage = Percentage.ofRatio(value / other.value) + + public override operator fun times(scalar: Number): Power = Power(value * scalar.toDouble()) + + public override operator fun times(percentage: Percentage): Power = Power(value * percentage.value) + + public override operator fun unaryMinus(): Power = Power(-value) + + public override operator fun compareTo(other: Power): Int = this.value.compareTo(other.value) + + public override fun isZero(): Boolean = value == .0 + + public override fun approxZero(epsilon: Double): Boolean = value.approx(.0, epsilon = epsilon) + + public override fun approx( + other: Power, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this == other || this.value.approx(other.value, minEpsilon, epsilon) + + public override infix fun approx(other: Power): Boolean = approx(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLarger( + other: Power, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLarger(other.value, minEpsilon, epsilon) + + public override infix fun approxLarger(other: Power): Boolean = approxLarger(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxLargerOrEq( + other: Power, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxLargerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxLargerOrEq(other: Power): Boolean = approxLargerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmaller( + other: Power, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmaller(other.value, minEpsilon, epsilon) + + public override infix fun approxSmaller(other: Power): Boolean = approxSmaller(other, minEpsilon = DFLT_MIN_EPS) + + public override fun approxSmallerOrEq( + other: Power, + minEpsilon: Double, + epsilon: Double, + ): Boolean = this.value.approxSmallerOrEq(other.value, minEpsilon, epsilon) + + public override infix fun approxSmallerOrEq(other: Power): Boolean = approxSmallerOrEq(other, minEpsilon = DFLT_MIN_EPS) + + public override infix fun max(other: Power): Power = if (this.value > other.value) this else other + + public override infix fun min(other: Power): Power = if (this.value < other.value) this else other + + public override fun abs(): Power = Power(kotlin.math.abs(value)) + + public override fun roundToIfWithinEpsilon( + to: Power, + epsilon: Double, + ): Power = + if (this.value in (to.value - epsilon)..(to.value + epsilon)) { + to + } else { + this + } + + public fun max( + a: Power, + b: Power, + ): Power = if (a.value > b.value) a else b + + public fun min( + a: Power, + b: Power, + ): Power = if (a.value < b.value) a else b + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Unit Specific Operations + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public operator fun times(timeDelta: TimeDelta): Energy = Energy.ofWh(toWatts() * timeDelta.toHours()) + + public operator fun times(duration: Duration): Energy = this * duration.toTimeDelta() + + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Companion + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public companion object : UnitId { + @JvmStatic override val zero: Power = Power(.0) + + @JvmStatic override val max: Power = Power(Double.MAX_VALUE) + + @JvmStatic override val min: Power = Power(Double.MIN_VALUE) + + public operator fun Number.times(unit: Power): Power = unit * this @JvmStatic @JvmName("ofWatts") @@ -74,9 +186,13 @@ public value class Power private constructor( @JvmName("ofKWatts") public fun ofKWatts(kWatts: Number): Power = Power(kWatts.toDouble() * 1000.0) + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Serializer + // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** * Serializer for [Power] value class. It needs to be a compile - * time constant in order to be used as serializer automatically, + * time constant to be used as serializer automatically, * hence `object :` instead of class instantiation. * * ```json diff --git a/opendc-common/src/main/kotlin/org/opendc/common/units/Time.kt b/opendc-common/src/main/kotlin/org/opendc/common/units/Time.kt deleted file mode 100644 index 9d72ddfc..00000000 --- a/opendc-common/src/main/kotlin/org/opendc/common/units/Time.kt +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2024 AtLarge Research - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -@file:OptIn(InternalUse::class) - -package org.opendc.common.units - -import kotlinx.serialization.Serializable -import org.opendc.common.annotations.InternalUse -import org.opendc.common.utils.ifNeg0thenPos0 -import java.time.Duration -import java.time.Instant -import kotlin.text.RegexOption.IGNORE_CASE - -/** - * Represents time values. - * @see[Unit] - */ -@JvmInline -@Serializable(with = Time.Companion.TimeSerializer::class) -public value class Time private constructor( - // In milliseconds. - public override val value: Double, -) : Unit