Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add callsInPlace to ReceiveChannel.consume #2496

Merged
merged 3 commits into from
Jan 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
qwwdfsad marked this conversation as resolved.
Show resolved Hide resolved
}
}
}