From 5e9e741b519f248d8881cefed040a7e2ef0d0d8c Mon Sep 17 00:00:00 2001 From: Andrew Golovashevich Date: Mon, 15 Sep 2025 01:39:27 +0300 Subject: [PATCH] withUseIfNotClosed --- build.gradle.kts | 2 +- .../utility/closeable_state_1/usage_scopes.kt | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index ef708cc..a5fed5c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -15,7 +15,7 @@ buildscript { } group = "ru.landgrafhomyak.utility" -version = "1.2" +version = "1.3" repositories { mavenCentral() diff --git a/src/commonMain/kotlin/ru/landgrafhomyak/utility/closeable_state_1/usage_scopes.kt b/src/commonMain/kotlin/ru/landgrafhomyak/utility/closeable_state_1/usage_scopes.kt index a4ef50e..c8f7b70 100644 --- a/src/commonMain/kotlin/ru/landgrafhomyak/utility/closeable_state_1/usage_scopes.kt +++ b/src/commonMain/kotlin/ru/landgrafhomyak/utility/closeable_state_1/usage_scopes.kt @@ -91,3 +91,27 @@ public inline fun CloseableState.ExternallySynchronized.tryFinishUsageThenClose( onSuccess = { this.finishUsage(needClose) } ) } + + +@OptIn(ManualStateManipulation::class) +@JvmName("withUseIfNotClosed\$kt") +public inline fun CloseableState.withUseIfNotClosed(ifClosed: R, block: () -> R): R { + contract { + callsInPlace(block, InvocationKind.AT_MOST_ONCE) + } + if (this.startUsageIfNotClosed()) + return ifClosed + return safeAutoClose1(action = block, finally = { this.finishUsage() }) +} + +@OptIn(ManualStateManipulation::class) +@JvmName("withUseIfNotClosed\$kt") +public inline fun CloseableState.withUseIfNotClosed(ifClosed: () -> R, block: () -> R): R { + contract { + callsInPlace(ifClosed, InvocationKind.AT_MOST_ONCE) + callsInPlace(block, InvocationKind.AT_MOST_ONCE) + } + if (this.startUsageIfNotClosed()) + return ifClosed() + return safeAutoClose1(action = block, finally = { this.finishUsage() }) +} \ No newline at end of file