Scoop API

scoop:scoop.math:0.1.0

src/scalar/integer_ulong.scoop

Selected production source · src/scalar/integer_ulong.scoop

1package scoop.math
3/** Returns the smaller value. */
4public fun min(a: ULong, b: ULong): ULong = if (a <= b) a else b
6/** Returns the larger value. */
7public fun max(a: ULong, b: ULong): ULong = if (a >= b) a else b
9/** Clamps to inclusive bounds; reversed bounds throw IllegalArgumentException. */
10public fun clamp(value: ULong, min: ULong, max: ULong): ULong {
11 if (min > max) throw IllegalArgumentException(Some("reversed math bounds"))
12 return if (value < min) min else if (value > max) max else value
15/** Computes the exact result, throwing ArithmeticException on overflow. */
16public fun addExact(a: ULong, b: ULong): ULong {
17 val result = a + b
18 if (result < a) mathOverflow()
19 return result
22/** Computes the exact result, throwing ArithmeticException on overflow. */
23public fun subtractExact(a: ULong, b: ULong): ULong {
24 val result = a - b
25 if (a < b) mathOverflow()
26 return result
29/** Multiplies exactly, throwing ArithmeticException on overflow. */
30public fun multiplyExact(a: ULong, b: ULong): ULong {
31 if (b == 0u) return 0u
32 if (a > ULong.MAX_VALUE / b) mathOverflow()
33 val result = a * b
34 return result
37/** Adds one with overflow checking. */
38public fun incrementExact(value: ULong): ULong = addExact(value, 1u)
40/** Subtracts one with overflow checking. */
41public fun decrementExact(value: ULong): ULong = subtractExact(value, 1u)
43/** Raises to a nonnegative power with overflow checking; zero to zero is one. */
44public fun powExact(value: ULong, exponent: Long): ULong {
45 if (exponent < 0L) throw ArithmeticException()
46 var result: ULong = 1u
47 var factor = value
48 var remaining = exponent
49 while (remaining != 0L) {
50 if ((remaining and 1L) != 0L) result = multiplyExact(result, factor)
51 remaining = remaining shr 1L
52 if (remaining != 0L) factor = multiplyExact(factor, factor)
53 }
54 return result