Saturate overflowing values when adjusting time marks
KT-46132
This commit is contained in:
@@ -5,23 +5,21 @@
|
||||
|
||||
package kotlin.time
|
||||
|
||||
import kotlin.time.Duration.Companion.nanoseconds
|
||||
|
||||
@SinceKotlin("1.3")
|
||||
@ExperimentalTime
|
||||
internal actual object MonotonicTimeSource : TimeSource {
|
||||
private fun read(): Long = System.nanoTime()
|
||||
private val zero: Long = System.nanoTime()
|
||||
private fun read(): Long = System.nanoTime() - zero
|
||||
override fun toString(): String = "TimeSource(System.nanoTime())"
|
||||
|
||||
actual override fun markNow(): DefaultTimeMark = DefaultTimeMark(read())
|
||||
actual fun elapsedFrom(timeMark: DefaultTimeMark): Duration = (read() - timeMark.reading).nanoseconds
|
||||
actual fun elapsedFrom(timeMark: DefaultTimeMark): Duration =
|
||||
saturatingDiff(read(), timeMark.reading)
|
||||
|
||||
// may have questionable contract
|
||||
actual fun adjustReading(timeMark: DefaultTimeMark, duration: Duration): DefaultTimeMark =
|
||||
DefaultTimeMark(timeMark.reading + duration.inWholeNanoseconds)
|
||||
DefaultTimeMark(saturatingAdd(timeMark.reading, duration))
|
||||
}
|
||||
|
||||
|
||||
@Suppress("ACTUAL_WITHOUT_EXPECT") // visibility
|
||||
internal actual typealias DefaultTimeMarkReading = Long
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2010-2022 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.
|
||||
*/
|
||||
|
||||
package test.time
|
||||
|
||||
import kotlin.test.*
|
||||
import kotlin.time.*
|
||||
import kotlin.time.Duration.Companion.nanoseconds
|
||||
|
||||
@OptIn(ExperimentalTime::class)
|
||||
class TimeMarkJVMTest {
|
||||
|
||||
@Test
|
||||
fun longDurationElapsed() {
|
||||
TimeMarkTest().testLongDisplacement(TimeSource.Monotonic, { waitDuration -> Thread.sleep(waitDuration.inWholeMilliseconds) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun defaultTimeMarkAdjustmentInfinite() {
|
||||
val baseMark = TimeSource.Monotonic.markNow()
|
||||
val longDuration = Long.MAX_VALUE.nanoseconds
|
||||
|
||||
val pastMark = baseMark - longDuration
|
||||
val infiniteFutureMark1 = pastMark + longDuration * 3
|
||||
|
||||
assertEquals(-Duration.INFINITE, infiniteFutureMark1.elapsedNow())
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user