Scoop API

scoop:scoop.std:0.1.0

src/time/duration_scaling.scoop

Selected production source · src/time/duration_scaling.scoop

1package scoop.time
3internal fun multiplyDurationParts(parts: DurationParts, factor: Long): DurationParts {
4 val magnitude = if (factor < 0L) -factor.toULong() else factor.toULong()
5 if (magnitude == 0uL) return DurationParts(false, 0uL, 0)
6 val limit = 0x8000000000000000uL
7 if (parts.seconds > limit / magnitude) throw ArithmeticException()
8 val fraction = parts.nanos.toULong() * (magnitude % 1000000000uL)
9 val extra = parts.nanos.toULong() * (magnitude / 1000000000uL) + fraction / 1000000000uL
10 val whole = parts.seconds * magnitude
11 if (whole > limit - extra) throw ArithmeticException()
12 return DurationParts(parts.negative != (factor < 0L), whole + extra, (fraction % 1000000000uL).toInt())
15internal fun divideDurationParts(parts: DurationParts, divisor: Long): DurationParts {
16 if (divisor == 0L) throw ArithmeticException()
17 val magnitude = if (divisor < 0L) -divisor.toULong() else divisor.toULong()
18 val fraction = divideDurationFraction(parts.seconds % magnitude, parts.nanos, magnitude)
19 return DurationParts(parts.negative != (divisor < 0L), parts.seconds / magnitude, fraction)
22// The numerator is (remainder * 1e9 + nanos), at most 94 bits.
23// The quotient is below 1e9; the running remainder is below a divisor <= 2^63.
24private fun divideDurationFraction(remainder: ULong, nanos: Int, divisor: ULong): Int {
25 val bottom = (remainder and 0xffffffffuL) * 1000000000uL + nanos.toULong()
26 val top = (remainder shr 32L) * 1000000000uL + (bottom shr 32L)
27 val high = top shr 32L
28 val low = (top shl 32L) or (bottom and 0xffffffffuL)
29 var rest = 0uL
30 var quotient = 0uL
31 var bit = 96L
32 while (bit > 0L) {
33 bit -= 1L
34 val digit = if (bit >= 64L) (high shr (bit - 64L)) and 1uL else (low shr bit) and 1uL
35 rest = (rest shl 1L) or digit
36 quotient = quotient shl 1L
37 if (rest >= divisor) { rest -= divisor; quotient = quotient or 1uL }
38 }
39 return quotient.toInt()