scoop:scoop.math:0.1.0
src/scalar/integer_uint.scoop
Selected production source · src/scalar/integer_uint.scoop
1
package scoop.math3
/** Returns the smaller value. */4
public fun min(a: UInt, b: UInt): UInt = if (a <= b) a else b6
/** Returns the larger value. */7
public fun max(a: UInt, b: UInt): UInt = if (a >= b) a else b9
/** Clamps to inclusive bounds; reversed bounds throw IllegalArgumentException. */10
public 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 value13
}15
/** Computes the exact result, throwing ArithmeticException on overflow. */16
public fun addExact(a: UInt, b: UInt): UInt {17
val result = a + b18
if (result < a) mathOverflow()19
return result20
}22
/** Computes the exact result, throwing ArithmeticException on overflow. */23
public fun subtractExact(a: UInt, b: UInt): UInt {24
val result = a - b25
if (a < b) mathOverflow()26
return result27
}29
/** Multiplies exactly, throwing ArithmeticException on overflow. */30
public fun multiplyExact(a: UInt, b: UInt): UInt {31
if (b == 0u) return 0u32
if (a > UInt.MAX_VALUE / b) mathOverflow()33
val result = a * b34
return result35
}37
/** Adds one with overflow checking. */38
public fun incrementExact(value: UInt): UInt = addExact(value, 1u)40
/** Subtracts one with overflow checking. */41
public fun decrementExact(value: UInt): UInt = subtractExact(value, 1u)43
/** Raises to a nonnegative power with overflow checking; zero to zero is one. */44
public fun powExact(value: UInt, exponent: Long): UInt {45
if (exponent < 0L) throw ArithmeticException()46
var result: UInt = 1u47
var factor = value48
var remaining = exponent49
while (remaining != 0L) {50
if ((remaining and 1L) != 0L) result = multiplyExact(result, factor)51
remaining = remaining shr 1L52
if (remaining != 0L) factor = multiplyExact(factor, factor)53
}54
return result55
}