@@ -6,28 +6,45 @@ package kotlinx.coroutines.time
66import kotlinx.coroutines.CoroutineScope
77import kotlinx.coroutines.selects.SelectBuilder
88import java.time.Duration
9- import java.util.concurrent.TimeUnit
9+ import java.time.temporal.ChronoUnit
1010
1111/* *
1212 * "java.time" adapter method for [kotlinx.coroutines.delay]
1313 */
1414public suspend fun delay (duration : Duration ) =
15- kotlinx.coroutines.delay(duration.toMillis ())
15+ kotlinx.coroutines.delay(duration.toMillisDelay ())
1616
1717/* *
1818 * "java.time" adapter method for [SelectBuilder.onTimeout]
1919 */
2020public fun <R > SelectBuilder<R>.onTimeout (duration : Duration , block : suspend () -> R ) =
21- onTimeout(duration.toMillis (), block)
21+ onTimeout(duration.toMillisDelay (), block)
2222
2323/* *
2424 * "java.time" adapter method for [kotlinx.coroutines.withTimeout]
2525 */
2626public suspend fun <T > withTimeout (duration : Duration , block : suspend CoroutineScope .() -> T ): T =
27- kotlinx.coroutines.withTimeout(duration.toMillis (), block)
27+ kotlinx.coroutines.withTimeout(duration.toMillisDelay (), block)
2828
2929/* *
3030 * "java.time" adapter method for [kotlinx.coroutines.withTimeoutOrNull]
3131 */
3232public suspend fun <T > withTimeoutOrNull (duration : Duration , block : suspend CoroutineScope .() -> T ): T ? =
33- kotlinx.coroutines.withTimeoutOrNull(duration.toMillis(), block)
33+ kotlinx.coroutines.withTimeoutOrNull(duration.toMillisDelay(), block)
34+
35+ /* *
36+ * Convert the [Duration] to millisecond delay.
37+ *
38+ * @return strictly positive duration is coerced to 1..[Long.MAX_VALUE] ms, `0` otherwise.
39+ */
40+ private fun Duration.toMillisDelay (): Long =
41+ if (this <= ChronoUnit .MILLIS .duration) {
42+ if (this <= Duration .ZERO ) 0
43+ else 1
44+ } else {
45+ // values of Duration.ofMillis(Long.MAX_VALUE)
46+ val maxSeconds = 9223372036854775
47+ val maxNanos = 807000000
48+ if (seconds < maxSeconds || seconds == maxSeconds && nano < maxNanos) toMillis()
49+ else Long .MAX_VALUE
50+ }
0 commit comments