Scoop API

scoop:scoop.math:0.1.0

src/scalar/integer_uint.scoop

Selected production source · src/scalar/integer_uint.scoop

1package scoop.math
3/** Returns the smaller value. */
4public fun min(a: UInt, b: UInt): UInt = if (a <= b) a else b
6/** Returns the larger value. */
7public fun max(a: UInt, b: UInt): UInt = if (a >= b) a else b
9/** Clamps to inclusive bounds; reversed bounds throw IllegalArgumentException. */
10public fun clamp(value: UInt, min: UInt, max: UInt): UInt {
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: UInt, b: UInt): UInt {
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: UInt, b: UInt): UInt {
24 val result = a - b
25 if (a < b) mathOverflow()
26 return result
29/** Multiplies exactly, throwing ArithmeticException on overflow. */
30public fun multiplyExact(a: UInt, b: UInt): UInt {
31 if (b == 0u) return 0u
32 if (a > UInt.MAX_VALUE / b) mathOverflow()
33 val result = a * b
34 return result
37/** Adds one with overflow checking. */
38public fun incrementExact(value: UInt): UInt = addExact(value, 1u)
40/** Subtracts one with overflow checking. */
41public fun decrementExact(value: UInt): UInt = subtractExact(value, 1u)
43/** Raises to a nonnegative power with overflow checking; zero to zero is one. */
44public fun powExact(value: UInt, exponent: Long): UInt {
45 if (exponent < 0L) throw ArithmeticException()
46 var result: UInt = 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