All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.maryk.rocksdb.useAutoClosable.kt Maven / Gradle / Ivy

package maryk.rocksdb

/**
 * Executes the given [block] function on this resource and then closes it down correctly whether an exception
 * is thrown or not.
 *
 * @param block a function to process this [Closeable] resource.
 * @return the result of [block] function invoked on this resource.
 */
inline fun  T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        this.closeFinally(exception)
    }
}

/**
 * Closes this [Closeable], suppressing possible exception or error thrown by [Closeable.close] function when
 * it's being closed due to some other [cause] exception occurred.
 *
 * The suppressed exception is added to the list of suppressed exceptions of [cause] exception, when it's supported.
 */
fun AutoCloseable?.closeFinally(cause: Throwable?) = when {
    this == null -> {}
    cause == null -> close()
    else ->
        try {
            close()
        } catch (closeException: Throwable) {
            // Ignored
            // cause.addSuppressed(closeException)
        }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy