• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package kotlinx.coroutines
2 
3 import kotlinx.atomicfu.*
4 import kotlinx.coroutines.internal.*
5 import kotlin.coroutines.*
6 import kotlin.jvm.*
7 
<lambda>null8 internal fun <T> Result<T>.toState(): Any? = getOrElse { CompletedExceptionally(it) }
9 
toStatenull10 internal fun <T> Result<T>.toState(caller: CancellableContinuation<*>): Any? =
11     getOrElse { CompletedExceptionally(recoverStackTrace(it, caller)) }
12 
13 @Suppress("RESULT_CLASS_IN_RETURN_TYPE", "UNCHECKED_CAST")
recoverResultnull14 internal fun <T> recoverResult(state: Any?, uCont: Continuation<T>): Result<T> =
15     if (state is CompletedExceptionally)
16         Result.failure(recoverStackTrace(state.cause, uCont))
17     else
18         Result.success(state as T)
19 
20 /**
21  * Class for an internal state of a job that was cancelled (completed exceptionally).
22  *
23  * @param cause the exceptional completion cause. It's either original exceptional cause
24  *        or artificial [CancellationException] if no cause was provided
25  */
26 internal open class CompletedExceptionally(
27     @JvmField val cause: Throwable,
28     handled: Boolean = false
29 ) {
30     private val _handled = atomic(handled)
31     val handled: Boolean get() = _handled.value
32     fun makeHandled(): Boolean = _handled.compareAndSet(false, true)
33     override fun toString(): String = "$classSimpleName[$cause]"
34 }
35 
36 /**
37  * A specific subclass of [CompletedExceptionally] for cancelled [AbstractContinuation].
38  *
39  * @param continuation the continuation that was cancelled.
40  * @param cause the exceptional completion cause. If `cause` is null, then a [CancellationException]
41  *        if created on first access to [exception] property.
42  */
43 internal class CancelledContinuation(
44     continuation: Continuation<*>,
45     cause: Throwable?,
46     handled: Boolean
47 ) : CompletedExceptionally(cause ?: CancellationException("Continuation $continuation was cancelled normally"), handled) {
48     private val _resumed = atomic(false)
makeResumednull49     fun makeResumed(): Boolean = _resumed.compareAndSet(false, true)
50 }
51