Skip to content

Commit ea0a30b

Browse files
committed
Add callsInPlace to ReceiveChannel.consume
Fixes #941
1 parent dcb51f9 commit ea0a30b

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

kotlinx-coroutines-core/common/src/channels/Channels.common.kt

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
/*
2-
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44
@file:JvmMultifileClass
55
@file:JvmName("ChannelsKt")
66
@file:Suppress("DEPRECATION_ERROR")
7+
@file:OptIn(ExperimentalContracts::class)
78

89
package kotlinx.coroutines.channels
910

1011
import kotlinx.coroutines.*
1112
import kotlinx.coroutines.selects.*
13+
import kotlin.contracts.*
1214
import kotlin.coroutines.*
1315
import kotlin.jvm.*
1416

@@ -164,6 +166,9 @@ public fun consumesAll(vararg channels: ReceiveChannel<*>): CompletionHandler =
164166
* The operation is _terminal_.
165167
*/
166168
public inline fun <E, R> ReceiveChannel<E>.consume(block: ReceiveChannel<E>.() -> R): R {
169+
contract {
170+
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
171+
}
167172
var cause: Throwable? = null
168173
try {
169174
return block()

kotlinx-coroutines-core/common/test/BuilderContractsTest.kt

+13-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
/*
2-
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

55
package kotlinx.coroutines
66

7+
import kotlinx.coroutines.channels.*
78
import kotlinx.coroutines.selects.*
89
import kotlin.test.*
910

@@ -44,9 +45,18 @@ class BuilderContractsTest : TestBase() {
4445
Job().apply { complete() }.onJoin {}
4546
}
4647
consume(s)
48+
49+
50+
val ch: Int
51+
val i = Channel<Int>()
52+
i.consume {
53+
ch = 321
54+
}
55+
consume(ch)
4756
}
4857

4958
private fun consume(a: Int) {
50-
a.hashCode() // BE codegen verification
59+
assertNotEquals(0, a)
60+
assertEquals(a.hashCode(), a)
5161
}
52-
}
62+
}

0 commit comments

Comments
 (0)