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