scoop:scoop.asyncio:0.1.0
src/loop/loop_mailbox.scoop
Selected production source · src/loop/loop_mailbox.scoop
1
package scoop.asyncio3
internal class LoopMailbox(private val owner: LoopOwner) {4
private val lock: IoLock = IoLock()5
private var accepting: Boolean = true6
private var closeRequested: Boolean = false7
private var closed: Boolean = false8
private var messages: ArrayList<CoroutineScope.() -> Unit> =9
ArrayList<CoroutineScope.() -> Unit>()10
private var waiting: Continuation<Unit>? = None12
val isClosed: Boolean get() = lock.withLock { closed }14
fun post(block: CoroutineScope.() -> Unit): Boolean {15
val accepted =16
lock.withLock {17
if (!accepting)18
false19
else {20
messages.add(block);21
true22
}23
}24
if (accepted)25
owner.post { signal() }26
return accepted27
}29
fun requestClose() {30
val first =31
lock.withLock {32
if (!accepting)33
false34
else {35
accepting = false36
closeRequested = true37
messages = ArrayList<CoroutineScope.() -> Unit>()38
true39
}40
}41
if (first)42
owner.post { owner.cancelRoot() }43
}45
fun signal() {46
when (waiting) {47
case Some(val continuation) -> {48
waiting = None49
owner.enqueueReady { continuation.resume(Unit) }50
}51
case None -> {}52
}53
}55
suspend fun run(scope: CoroutineScope) {56
owner.bindRoot(scope.job)57
val subscription = scope.job.invokeOnCancellation { owner.post { signal() } }58
try {59
while (true) {60
suspendCoroutine<Unit> { continuation -> waiting = Some(continuation) }61
scope.job.ensureActive()62
val batch =63
lock.withLock {64
val pending = messages65
messages = ArrayList<CoroutineScope.() -> Unit>()66
pending67
}68
for (block in batch) {69
if (!lock.withLock { accepting })70
break71
scope.job.ensureActive()72
block(scope)73
}74
}75
} finally {76
stop()77
subscription.dispose()78
}79
}81
private fun stop() {82
lock.withLock {83
accepting = false84
messages = ArrayList<CoroutineScope.() -> Unit>()85
}86
}88
fun finish(error: Throwable?) {89
stop()90
val requested = lock.withLock { closeRequested }91
val result =92
when (error) {93
case Some(val value) -> if (requested && value is CancellationException)94
None95
else96
error97
case None -> None98
}99
owner.finishRoot(result)100
}102
fun didClose() {103
lock.withLock { closed = true }104
}105
}107
internal class SessionCompletion(private val mailbox: LoopMailbox): Continuation<Unit> {108
public override fun resume(value: Unit) {109
mailbox.finish(None)110
}111
public override fun resumeWithException(exception: Throwable) {112
mailbox.finish(Some(exception))113
}114
}