Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | package kotlinx.coroutines.experimental |
| 6 | |
| 7 | import kotlin.coroutines.experimental.Continuation |
| 8 | |
| 9 | @PublishedApi internal const val MODE_ATOMIC_DEFAULT = 0 // schedule non-cancellable dispatch for suspendCoroutine |
| 10 | @PublishedApi internal const val MODE_CANCELLABLE = 1 // schedule cancellable dispatch for suspendCancellableCoroutine |
| 11 | @PublishedApi internal const val MODE_DIRECT = 2 // when the context is right just invoke the delegate continuation direct |
| 12 | @PublishedApi internal const val MODE_UNDISPATCHED = 3 // when the thread is right, but need to mark it with current coroutine |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 13 | @PublishedApi internal const val MODE_IGNORE = 4 // don't do anything |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 14 | |
Roman Elizarov | ac48070 | 2017-12-28 01:09:43 +0300 | [diff] [blame] | 15 | internal val Int.isCancellableMode get() = this == MODE_CANCELLABLE |
| 16 | internal val Int.isDispatchedMode get() = this == MODE_ATOMIC_DEFAULT || this == MODE_CANCELLABLE |
| 17 | |
Roman Elizarov | e1c0b65 | 2017-12-01 14:02:57 +0300 | [diff] [blame] | 18 | internal fun <T> Continuation<T>.resumeMode(value: T, mode: Int) { |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 19 | when (mode) { |
| 20 | MODE_ATOMIC_DEFAULT -> resume(value) |
| 21 | MODE_CANCELLABLE -> resumeCancellable(value) |
| 22 | MODE_DIRECT -> resumeDirect(value) |
| 23 | MODE_UNDISPATCHED -> (this as DispatchedContinuation).resumeUndispatched(value) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 24 | MODE_IGNORE -> {} |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 25 | else -> error("Invalid mode $mode") |
| 26 | } |
| 27 | } |
| 28 | |
Roman Elizarov | e1c0b65 | 2017-12-01 14:02:57 +0300 | [diff] [blame] | 29 | internal fun <T> Continuation<T>.resumeWithExceptionMode(exception: Throwable, mode: Int) { |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 30 | when (mode) { |
| 31 | MODE_ATOMIC_DEFAULT -> resumeWithException(exception) |
| 32 | MODE_CANCELLABLE -> resumeCancellableWithException(exception) |
| 33 | MODE_DIRECT -> resumeDirectWithException(exception) |
| 34 | MODE_UNDISPATCHED -> (this as DispatchedContinuation).resumeUndispatchedWithException(exception) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 35 | MODE_IGNORE -> {} |
Roman Elizarov | e22f14a | 2017-06-22 19:04:52 +0300 | [diff] [blame] | 36 | else -> error("Invalid mode $mode") |
| 37 | } |
| 38 | } |