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