Store Duration value as a multi-range Long

Now precision loss happens at bigger durations.

This changes the binary API due different underlying type of Duration.
This commit is contained in:
Ilya Gorbunov
2021-02-17 20:15:18 +03:00
parent 3f4fa7eb98
commit fa7460ba48
9 changed files with 596 additions and 182 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -49,3 +49,34 @@ internal actual fun convertDurationUnit(value: Double, sourceUnit: DurationUnit,
}
}
@SinceKotlin("1.5")
@ExperimentalTime
internal actual fun convertDurationUnitOverflow(value: Long, sourceUnit: DurationUnit, targetUnit: DurationUnit): Long {
val sourceCompareTarget = sourceUnit.scale.compareTo(targetUnit.scale)
return when {
sourceCompareTarget > 0 -> value * (sourceUnit.scale / targetUnit.scale).toLong()
sourceCompareTarget < 0 -> value / (targetUnit.scale / sourceUnit.scale).toLong()
else -> value
}
}
@SinceKotlin("1.5")
@ExperimentalTime
internal actual fun convertDurationUnit(value: Long, sourceUnit: DurationUnit, targetUnit: DurationUnit): Long {
val sourceCompareTarget = sourceUnit.scale.compareTo(targetUnit.scale)
return when {
sourceCompareTarget > 0 -> {
val scale = (sourceUnit.scale / targetUnit.scale).toLong()
val result = value * scale
when {
result / scale == value -> result
value > 0 -> Long.MAX_VALUE
else -> Long.MIN_VALUE
}
}
sourceCompareTarget < 0 -> value / (targetUnit.scale / sourceUnit.scale).toLong()
else -> value
}
}