withUseIfNotClosed

This commit is contained in:
Andrew Golovashevich 2025-09-15 01:39:27 +03:00
parent 8fc08d3e26
commit 5e9e741b51
2 changed files with 25 additions and 1 deletions

View File

@ -15,7 +15,7 @@ buildscript {
}
group = "ru.landgrafhomyak.utility"
version = "1.2"
version = "1.3"
repositories {
mavenCentral()

View File

@ -91,3 +91,27 @@ public inline fun CloseableState.ExternallySynchronized.tryFinishUsageThenClose(
onSuccess = { this.finishUsage(needClose) }
)
}
@OptIn(ManualStateManipulation::class)
@JvmName("withUseIfNotClosed\$kt")
public inline fun <R> 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 <R> 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() })
}