• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.coroutines
6 
7 import kotlinx.atomicfu.*
8 import kotlin.coroutines.*
9 import kotlin.jvm.*
10 
toStatenull11 internal fun <T> Result<T>.toState(): Any? =
12     if (isSuccess) getOrThrow() else CompletedExceptionally(exceptionOrNull()!!) // todo: need to do it better
13 
14 /**
15  * Class for an internal state of a job that was cancelled (completed exceptionally).
16  *
17  * @param cause the exceptional completion cause. It's either original exceptional cause
18  *        or artificial [CancellationException] if no cause was provided
19  */
20 internal open class CompletedExceptionally(
21     @JvmField public val cause: Throwable,
22     handled: Boolean = false
23 ) {
24     private val _handled = atomic(handled)
25     val handled: Boolean get() = _handled.value
26     fun makeHandled(): Boolean = _handled.compareAndSet(false, true)
27     override fun toString(): String = "$classSimpleName[$cause]"
28 }
29 
30 /**
31  * A specific subclass of [CompletedExceptionally] for cancelled [AbstractContinuation].
32  *
33  * @param continuation the continuation that was cancelled.
34  * @param cause the exceptional completion cause. If `cause` is null, then a [CancellationException]
35  *        if created on first access to [exception] property.
36  */
37 internal class CancelledContinuation(
38     continuation: Continuation<*>,
39     cause: Throwable?,
40     handled: Boolean
41 ) : CompletedExceptionally(cause ?: CancellationException("Continuation $continuation was cancelled normally"), handled) {
42     private val _resumed = atomic(false)
makeResumednull43     fun makeResumed(): Boolean = _resumed.compareAndSet(false, true)
44 }
45