Skip to content

Commit

Permalink
Add callsInPlace to ReceiveChannel.consume (#2496)
Browse files Browse the repository at this point in the history
Fixes #941
  • Loading branch information
qwwdfsad committed Jan 26, 2021
1 parent dcb51f9 commit 2ec1290
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("ChannelsKt")
@file:Suppress("DEPRECATION_ERROR")
@file:OptIn(ExperimentalContracts::class)

package kotlinx.coroutines.channels

import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import kotlin.contracts.*
import kotlin.coroutines.*
import kotlin.jvm.*

Expand Down Expand Up @@ -164,6 +166,9 @@ public fun consumesAll(vararg channels: ReceiveChannel<*>): CompletionHandler =
* The operation is _terminal_.
*/
public inline fun <E, R> ReceiveChannel<E>.consume(block: ReceiveChannel<E>.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
var cause: Throwable? = null
try {
return block()
Expand Down
20 changes: 17 additions & 3 deletions kotlinx-coroutines-core/common/test/BuilderContractsTest.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.coroutines

import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
import kotlin.test.*

Expand Down Expand Up @@ -44,9 +45,22 @@ class BuilderContractsTest : TestBase() {
Job().apply { complete() }.onJoin {}
}
consume(s)


val ch: Int
val i = Channel<Int>()
i.consume {
ch = 321
}
consume(ch)
}

private fun consume(a: Int) {
a.hashCode() // BE codegen verification
/*
* Verify the value is actually set correctly
* (non-zero, VerificationError is not triggered, can be read)
*/
assertNotEquals(0, a)
assertEquals(a.hashCode(), a)
}
}
}

0 comments on commit 2ec1290

Please sign in to comment.