blob: 5d5a9c4b27df51ae27684a8ca22df0e1213c27e2 [file] [log] [blame]
Roman Elizarove22f14a2017-06-22 19:04:52 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package kotlinx.coroutines.experimental
18
19import kotlin.coroutines.experimental.Continuation
20
21@PublishedApi internal const val MODE_ATOMIC_DEFAULT = 0 // schedule non-cancellable dispatch for suspendCoroutine
22@PublishedApi internal const val MODE_CANCELLABLE = 1 // schedule cancellable dispatch for suspendCancellableCoroutine
23@PublishedApi internal const val MODE_DIRECT = 2 // when the context is right just invoke the delegate continuation direct
24@PublishedApi internal const val MODE_UNDISPATCHED = 3 // when the thread is right, but need to mark it with current coroutine
Roman Elizarov8b38fa22017-09-27 17:44:31 +030025@PublishedApi internal const val MODE_IGNORE = 4 // don't do anything
Roman Elizarove22f14a2017-06-22 19:04:52 +030026
Roman Elizarovac480702017-12-28 01:09:43 +030027internal val Int.isCancellableMode get() = this == MODE_CANCELLABLE
28internal val Int.isDispatchedMode get() = this == MODE_ATOMIC_DEFAULT || this == MODE_CANCELLABLE
29
Roman Elizarove1c0b652017-12-01 14:02:57 +030030internal fun <T> Continuation<T>.resumeMode(value: T, mode: Int) {
Roman Elizarove22f14a2017-06-22 19:04:52 +030031 when (mode) {
32 MODE_ATOMIC_DEFAULT -> resume(value)
33 MODE_CANCELLABLE -> resumeCancellable(value)
34 MODE_DIRECT -> resumeDirect(value)
35 MODE_UNDISPATCHED -> (this as DispatchedContinuation).resumeUndispatched(value)
Roman Elizarov8b38fa22017-09-27 17:44:31 +030036 MODE_IGNORE -> {}
Roman Elizarove22f14a2017-06-22 19:04:52 +030037 else -> error("Invalid mode $mode")
38 }
39}
40
Roman Elizarove1c0b652017-12-01 14:02:57 +030041internal fun <T> Continuation<T>.resumeWithExceptionMode(exception: Throwable, mode: Int) {
Roman Elizarove22f14a2017-06-22 19:04:52 +030042 when (mode) {
43 MODE_ATOMIC_DEFAULT -> resumeWithException(exception)
44 MODE_CANCELLABLE -> resumeCancellableWithException(exception)
45 MODE_DIRECT -> resumeDirectWithException(exception)
46 MODE_UNDISPATCHED -> (this as DispatchedContinuation).resumeUndispatchedWithException(exception)
Roman Elizarov8b38fa22017-09-27 17:44:31 +030047 MODE_IGNORE -> {}
Roman Elizarove22f14a2017-06-22 19:04:52 +030048 else -> error("Invalid mode $mode")
49 }
50}