From daff65f220126a84f54d58a4bf249087a67e4542 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Fri, 29 Jul 2016 12:20:09 +0200 Subject: [PATCH] Minor: add infix utilities for overflow checked arithmetic. --- core/src/main/kotlin/com/r3corda/core/Utils.kt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/src/main/kotlin/com/r3corda/core/Utils.kt b/core/src/main/kotlin/com/r3corda/core/Utils.kt index 68ebed813f..353700e060 100644 --- a/core/src/main/kotlin/com/r3corda/core/Utils.kt +++ b/core/src/main/kotlin/com/r3corda/core/Utils.kt @@ -31,6 +31,11 @@ val Long.bd: BigDecimal get() = BigDecimal(this) fun String.abbreviate(maxWidth: Int): String = if (length <= maxWidth) this else take(maxWidth - 1) + "…" +/** Like the + operator but throws an exception in case of integer overflow. */ +infix fun Int.checkedAdd(b: Int) = Math.addExact(this, b) +/** Like the + operator but throws an exception in case of integer overflow. */ +infix fun Long.checkedAdd(b: Long) = Math.addExact(this, b) + /** * Returns a random positive long generated using a secure RNG. This function sacrifies a bit of entropy in order to * avoid potential bugs where the value is used in a context where negative numbers are not expected.