-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathSimpleChannel.kt
98 lines (81 loc) · 2.61 KB
/
SimpleChannel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.tailcall
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
public abstract class SimpleChannel {
companion object {
const val NULL_SURROGATE: Int = -1
}
@JvmField
protected var producer: Continuation<Unit>? = null
@JvmField
protected var enqueuedValue: Int = NULL_SURROGATE
@JvmField
protected var consumer: Continuation<Int>? = null
suspend fun send(element: Int) {
require(element != NULL_SURROGATE)
if (offer(element)) {
return
}
return suspendSend(element)
}
private fun offer(element: Int): Boolean {
if (consumer == null) {
return false
}
consumer!!.resume(element)
consumer = null
return true
}
suspend fun receive(): Int {
// Cached value
if (enqueuedValue != NULL_SURROGATE) {
val result = enqueuedValue
enqueuedValue = NULL_SURROGATE
producer!!.resume(Unit)
return result
}
return suspendReceive()
}
abstract suspend fun suspendReceive(): Int
abstract suspend fun suspendSend(element: Int)
}
class NonCancellableChannel : SimpleChannel() {
override suspend fun suspendReceive(): Int = suspendCoroutineUninterceptedOrReturn {
consumer = it.intercepted()
COROUTINE_SUSPENDED
}
override suspend fun suspendSend(element: Int) = suspendCoroutineUninterceptedOrReturn<Unit> {
enqueuedValue = element
producer = it.intercepted()
COROUTINE_SUSPENDED
}
}
class CancellableChannel : SimpleChannel() {
override suspend fun suspendReceive(): Int = suspendCancellableCoroutine {
consumer = it.intercepted()
COROUTINE_SUSPENDED
}
override suspend fun suspendSend(element: Int) = suspendCancellableCoroutine<Unit> {
enqueuedValue = element
producer = it.intercepted()
COROUTINE_SUSPENDED
}
}
class CancellableReusableChannel : SimpleChannel() {
@Suppress("INVISIBLE_MEMBER")
override suspend fun suspendReceive(): Int = suspendCancellableCoroutineReusable {
consumer = it.intercepted()
COROUTINE_SUSPENDED
}
@Suppress("INVISIBLE_MEMBER")
override suspend fun suspendSend(element: Int) = suspendCancellableCoroutineReusable<Unit> {
enqueuedValue = element
producer = it.intercepted()
COROUTINE_SUSPENDED
}
}