diff --git a/kmath-memory/src/commonMain/kotlin/kscience/kmath/memory/DeferScope.kt b/kmath-memory/src/commonMain/kotlin/kscience/kmath/memory/DeferScope.kt new file mode 100644 index 000000000..df5040ee0 --- /dev/null +++ b/kmath-memory/src/commonMain/kotlin/kscience/kmath/memory/DeferScope.kt @@ -0,0 +1,7 @@ +package kscience.kmath.memory + +public expect class DeferScope { + public inline fun defer(crossinline block: () -> Unit) +} + +public expect inline fun withDeferScope(block: DeferScope.() -> R): R diff --git a/kmath-memory/src/jsMain/kotlin/kscience/kmath/memory/DeferScopeJS.kt b/kmath-memory/src/jsMain/kotlin/kscience/kmath/memory/DeferScopeJS.kt new file mode 100644 index 000000000..aeb699a39 --- /dev/null +++ b/kmath-memory/src/jsMain/kotlin/kscience/kmath/memory/DeferScopeJS.kt @@ -0,0 +1,30 @@ +package kscience.kmath.memory + +private typealias Deferred = () -> Unit + +public actual class DeferScope { + @PublishedApi + internal val deferred: MutableList = 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 withDeferScope(block: DeferScope.() -> R): R { + val ds = DeferScope() + val r = ds.block() + ds.executeAllDeferred() + return r +} diff --git a/kmath-memory/src/jvmMain/kotlin/kscience/kmath/memory/DeferScopeJvm.kt b/kmath-memory/src/jvmMain/kotlin/kscience/kmath/memory/DeferScopeJvm.kt new file mode 100644 index 000000000..aeb699a39 --- /dev/null +++ b/kmath-memory/src/jvmMain/kotlin/kscience/kmath/memory/DeferScopeJvm.kt @@ -0,0 +1,30 @@ +package kscience.kmath.memory + +private typealias Deferred = () -> Unit + +public actual class DeferScope { + @PublishedApi + internal val deferred: MutableList = 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 withDeferScope(block: DeferScope.() -> R): R { + val ds = DeferScope() + val r = ds.block() + ds.executeAllDeferred() + return r +} diff --git a/kmath-memory/src/nativeMain/kotlin/kscience/kmath/memory/DeferScopeNative.kt b/kmath-memory/src/nativeMain/kotlin/kscience/kmath/memory/DeferScopeNative.kt new file mode 100644 index 000000000..6809b18b3 --- /dev/null +++ b/kmath-memory/src/nativeMain/kotlin/kscience/kmath/memory/DeferScopeNative.kt @@ -0,0 +1,7 @@ +package kscience.kmath.memory + +import kotlinx.cinterop.memScoped + +public actual typealias DeferScope = kotlinx.cinterop.DeferScope + +public actual inline fun withDeferScope(block: DeferScope.() -> R): R = memScoped(block)