scoop:scoop.math:0.1.0
src/scalar/wide.scoop
Selected production source · src/scalar/wide.scoop
1
package scoop.math3
internal fun mathOverflow(): Nothing = throw ArithmeticException()5
/** Narrows a Long exactly, throwing ArithmeticException outside Int range. */6
public 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. */12
public fun multiplyFull(a: Int, b: Int): Long = a.toLong() * b.toLong()14
/** Returns the complete unsigned product. */15
public fun multiplyFull(a: UInt, b: UInt): ULong = a.toULong() * b.toULong()17
/** Returns the high word of the unsigned 128-bit product. */18
public fun multiplyHigh(a: ULong, b: ULong): ULong {19
val a0 = a and 0xffffffffuL20
val a1 = a shr 32L21
val b0 = b and 0xffffffffuL22
val b1 = b shr 32L23
val low = a0 * b024
val middle = a1 * b0 + (low shr 32L)25
val carry = (middle and 0xffffffffuL) + a0 * b126
return a1 * b1 + (middle shr 32L) + (carry shr 32L)27
}29
/** Returns the signed high word of the signed 128-bit product. */30
public 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)33
}