add kotlin API

This commit is contained in:
jiahua.liu 2020-04-05 23:26:52 +08:00
parent a02f0ff4ee
commit 88b1576417

View File

@ -1,23 +1,57 @@
package net.mamoe.mirai.console.utils package net.mamoe.mirai.console.utils
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/** /**
* 执行N次 builder * 执行N次 builder
* 成功一次就会结束 * 成功一次就会结束
* 否则就会throw * 否则就会throw
*/ */
inline fun <T> tryNTimes(n:Int = 2, builder: () -> T):T { @OptIn(ExperimentalContracts::class)
var lastException: Exception? = null @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "RESULT_CLASS_IN_RETURN_TYPE")
@kotlin.internal.InlineOnly
inline fun <R> retryCatching(n: Int, block: () -> R): Result<R> {
contract {
callsInPlace(block, InvocationKind.AT_LEAST_ONCE)
}
require(n >= 0) { "param n for retryCatching must not be negative" }
var exception: Throwable? = null
repeat(n){ repeat(n){
try { try {
return builder.invoke() return Result.success(block())
} catch (e: Exception) { } catch (e: Throwable) {
lastException = e exception?.addSuppressedMirai(e)
exception = e
}
}
return Result.failure(exception!!)
}
@OptIn(ExperimentalContracts::class)
inline fun <T> tryNTimes(n: Int, block: () -> T):T {
contract {
callsInPlace(block, InvocationKind.AT_LEAST_ONCE)
}
require(n >= 0) { "param n for tryNTimes must not be negative" }
var last:Exception? = null
repeat(n){
try {
return block.invoke()
}catch (e:Exception){
last = e
} }
} }
throw lastException!! throw last!!
} }
@PublishedApi
internal fun Throwable.addSuppressedMirai(e: Throwable) {
if (e === this) {
return
}
kotlin.runCatching {
this.addSuppressed(e)
}
}