@@ -6,28 +6,45 @@ package kotlinx.coroutines.time
6
6
import kotlinx.coroutines.CoroutineScope
7
7
import kotlinx.coroutines.selects.SelectBuilder
8
8
import java.time.Duration
9
- import java.util.concurrent.TimeUnit
9
+ import java.time.temporal.ChronoUnit
10
10
11
11
/* *
12
12
* "java.time" adapter method for [kotlinx.coroutines.delay]
13
13
*/
14
14
public suspend fun delay (duration : Duration ) =
15
- kotlinx.coroutines.delay(duration.toMillis ())
15
+ kotlinx.coroutines.delay(duration.toMillisDelay ())
16
16
17
17
/* *
18
18
* "java.time" adapter method for [SelectBuilder.onTimeout]
19
19
*/
20
20
public fun <R > SelectBuilder<R>.onTimeout (duration : Duration , block : suspend () -> R ) =
21
- onTimeout(duration.toMillis (), block)
21
+ onTimeout(duration.toMillisDelay (), block)
22
22
23
23
/* *
24
24
* "java.time" adapter method for [kotlinx.coroutines.withTimeout]
25
25
*/
26
26
public 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)
28
28
29
29
/* *
30
30
* "java.time" adapter method for [kotlinx.coroutines.withTimeoutOrNull]
31
31
*/
32
32
public 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