Add draft of multiplatform DeferScope

This commit is contained in:
Iaroslav Postovalov 2021-01-16 20:00:00 +07:00
parent 758508ba96
commit 0b784474b4
No known key found for this signature in database
GPG Key ID: 46E15E4A31B3BCD7
4 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,7 @@
package kscience.kmath.memory
public expect class DeferScope {
public inline fun defer(crossinline block: () -> Unit)
}
public expect inline fun <R> withDeferScope(block: DeferScope.() -> R): R

View File

@ -0,0 +1,30 @@
package kscience.kmath.memory
private typealias Deferred = () -> Unit
public actual class DeferScope {
@PublishedApi
internal val deferred: MutableList<Deferred> = mutableListOf()
@PublishedApi
internal fun executeAllDeferred() {
deferred.forEach(Deferred::invoke)
deferred.clear()
}
public actual inline fun defer(crossinline block: () -> Unit) {
deferred += {
try {
block()
} catch (ignored: Throwable) {
}
}
}
}
public actual inline fun <R> withDeferScope(block: DeferScope.() -> R): R {
val ds = DeferScope()
val r = ds.block()
ds.executeAllDeferred()
return r
}

View File

@ -0,0 +1,30 @@
package kscience.kmath.memory
private typealias Deferred = () -> Unit
public actual class DeferScope {
@PublishedApi
internal val deferred: MutableList<Deferred> = mutableListOf()
@PublishedApi
internal fun executeAllDeferred() {
deferred.forEach(Deferred::invoke)
deferred.clear()
}
public actual inline fun defer(crossinline block: () -> Unit) {
deferred += {
try {
block()
} catch (ignored: Throwable) {
}
}
}
}
public actual inline fun <R> withDeferScope(block: DeferScope.() -> R): R {
val ds = DeferScope()
val r = ds.block()
ds.executeAllDeferred()
return r
}

View File

@ -0,0 +1,7 @@
package kscience.kmath.memory
import kotlinx.cinterop.memScoped
public actual typealias DeferScope = kotlinx.cinterop.DeferScope
public actual inline fun <R> withDeferScope(block: DeferScope.() -> R): R = memScoped(block)