From 88b15764177c61de1634870a818afd4112bbce24 Mon Sep 17 00:00:00 2001 From: "jiahua.liu" Date: Sun, 5 Apr 2020 23:26:52 +0800 Subject: [PATCH] add kotlin API --- .../net/mamoe/mirai/console/utils/Utils.kt | 52 +++++++++++++++---- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/mirai-console/src/main/kotlin/net/mamoe/mirai/console/utils/Utils.kt b/mirai-console/src/main/kotlin/net/mamoe/mirai/console/utils/Utils.kt index 8b9db10e8..4e69c9474 100644 --- a/mirai-console/src/main/kotlin/net/mamoe/mirai/console/utils/Utils.kt +++ b/mirai-console/src/main/kotlin/net/mamoe/mirai/console/utils/Utils.kt @@ -1,23 +1,57 @@ package net.mamoe.mirai.console.utils +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract /** * 执行N次 builder * 成功一次就会结束 * 否则就会throw */ -inline fun tryNTimes(n:Int = 2, builder: () -> T):T { - var lastException: Exception? = null - +@OptIn(ExperimentalContracts::class) +@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "RESULT_CLASS_IN_RETURN_TYPE") +@kotlin.internal.InlineOnly +inline fun retryCatching(n: Int, block: () -> R): Result { + contract { + callsInPlace(block, InvocationKind.AT_LEAST_ONCE) + } + require(n >= 0) { "param n for retryCatching must not be negative" } + var exception: Throwable? = null repeat(n){ try { - return builder.invoke() - } catch (e: Exception) { - lastException = e + return Result.success(block()) + } catch (e: Throwable) { + exception?.addSuppressedMirai(e) + exception = e + } + } + return Result.failure(exception!!) +} + +@OptIn(ExperimentalContracts::class) +inline fun 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) + } +}