commonMain.io.github.lyxnx.util.Standard.kt Maven / Gradle / Ivy
package io.github.lyxnx.util
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.coroutines.cancellation.CancellationException
import kotlin.jvm.JvmSynthetic
/**
* Returns this value if it satisfies the given [predicate] or throws an [IllegalArgumentException] otherwise
*
* @see takeIf
*/
@JvmSynthetic
public inline fun T.takeIfOrError(predicate: (T) -> Boolean): T {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else throw IllegalArgumentException("Predicate not satisfied")
}
/**
* Returns this value if it does not satisfy the given [predicate] or throws an [IllegalArgumentException] otherwise
*
* @see takeUnless
*/
@JvmSynthetic
public inline fun T.takeUnlessOrError(predicate: (T) -> Boolean): T {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else throw IllegalArgumentException("Predicate is satisfied")
}
/**
* Throws an [IllegalArgumentException] if the [value] is false or returns this otherwise
*
* @see require
*/
@JvmSynthetic
public infix fun T.requiring(value: Boolean): T {
contract {
returns() implies value
}
return if (value) this else throw IllegalArgumentException()
}
/**
* Throws an [IllegalArgumentException] with the result of calling [lazyMessage] if the value is false or returns this
* otherwise
*
* @see require
*/
@JvmSynthetic
public inline fun T.requiring(value: Boolean, lazyMessage: () -> Any): T {
contract {
callsInPlace(lazyMessage, InvocationKind.AT_MOST_ONCE)
}
return if (value) this else throw IllegalArgumentException(lazyMessage().toString())
}
/**
* Executes [block] and returns its result if it was successful whilst catching any [Exception]s that are thrown from
* the block and returning null otherwise
*
* Note that this function does not catch [Throwable]s as they should not be caught in normal business code.
* [CancellationException]s are also rethrown for compatibility with coroutines
*/
@JvmSynthetic
public inline fun tryOrNull(block: () -> T): T? {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return try {
block()
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
/**
* Executes [block] and returns its result if it was successful whilst catching any [Exception]s that are thrown from
* the block and returning the result of [orElse] otherwise
*
* Note that this function does not catch [Throwable]s as they should not be caught in normal business code.
* [CancellationException]s are also rethrown for compatibility with coroutines
*/
@JvmSynthetic
public inline fun tryOrElse(block: () -> T, orElse: (Exception) -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
callsInPlace(orElse, InvocationKind.AT_MOST_ONCE)
}
return try {
block()
} catch (e: Exception) {
if (e is CancellationException) throw e
orElse(e)
}
}