From 7744880ce7ffbb2992d6bb26887916e6bed62113 Mon Sep 17 00:00:00 2001 From: Roland Grinis Date: Fri, 9 Jul 2021 08:46:57 +0100 Subject: [PATCH] safe scopes --- .../kscience/kmath/noa/memory/NoaScope.kt | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/kmath-noa/src/main/kotlin/space/kscience/kmath/noa/memory/NoaScope.kt b/kmath-noa/src/main/kotlin/space/kscience/kmath/noa/memory/NoaScope.kt index a226fb212..08df2d79b 100644 --- a/kmath-noa/src/main/kotlin/space/kscience/kmath/noa/memory/NoaScope.kt +++ b/kmath-noa/src/main/kotlin/space/kscience/kmath/noa/memory/NoaScope.kt @@ -9,7 +9,7 @@ private typealias Disposable = () -> Unit public class NoaScope { - private val disposables: ArrayDeque = ArrayDeque(0) + internal val disposables: ArrayDeque = ArrayDeque(0) public fun disposeAll() { disposables.forEach(Disposable::invoke) @@ -20,15 +20,30 @@ public class NoaScope { disposables += { try { disposable() - } catch (ignored: Throwable) { + } catch (e: Throwable) { } } } + + internal fun addAll(scope: NoaScope) { + disposables.addAll(scope.disposables) + } } -internal inline fun withNoaScope(block: NoaScope.() -> R): R { +internal fun withNoaScope(block: NoaScope.() -> R): R? { val noaScope = NoaScope() - val result = noaScope.block() + val result = try { noaScope.block() } catch (e: Throwable) { null } noaScope.disposeAll() return result +} + +internal fun withNoaScope(scope: NoaScope, block: NoaScope.() -> R): R? { + val noaScope = NoaScope() + val result = try { noaScope.block() } catch (e: Throwable) { null } + if (result == null){ + noaScope.disposeAll() + } else { + scope.addAll(noaScope) + } + return result } \ No newline at end of file