Scoop API

scoop:scoop.math:0.1.0

src/scalar/wide.scoop

Selected production source · src/scalar/wide.scoop

1package scoop.math
3internal fun mathOverflow(): Nothing = throw ArithmeticException()
5/** Narrows a Long exactly, throwing ArithmeticException outside Int range. */
6public fun toIntExact(value: Long): Int {
7 if (value < Int.MIN_VALUE.toLong() || value > Int.MAX_VALUE.toLong()) mathOverflow()
8 return value.toInt()
9}
11/** Returns the complete signed product. */
12public fun multiplyFull(a: Int, b: Int): Long = a.toLong() * b.toLong()
14/** Returns the complete unsigned product. */
15public fun multiplyFull(a: UInt, b: UInt): ULong = a.toULong() * b.toULong()
17/** Returns the high word of the unsigned 128-bit product. */
18public fun multiplyHigh(a: ULong, b: ULong): ULong {
19 val a0 = a and 0xffffffffuL
20 val a1 = a shr 32L
21 val b0 = b and 0xffffffffuL
22 val b1 = b shr 32L
23 val low = a0 * b0
24 val middle = a1 * b0 + (low shr 32L)
25 val carry = (middle and 0xffffffffuL) + a0 * b1
26 return a1 * b1 + (middle shr 32L) + (carry shr 32L)
29/** Returns the signed high word of the signed 128-bit product. */
30public fun multiplyHigh(a: Long, b: Long): Long {
31 val high = multiplyHigh(a.toULong(), b.toULong()).toLong()
32 return high - (if (a < 0L) b else 0L) - (if (b < 0L) a else 0L)