scoop:scoop.std:0.1.0
src/time/duration_parts.scoop
Selected production source · src/time/duration_parts.scoop
1
package scoop.time3
internal struct DurationParts(val negative: Boolean, val seconds: ULong, val nanos: Int) {4
internal fun negated(): DurationParts = DurationParts(!negative, seconds, nanos)5
}7
internal fun normalizeDuration(seconds: Long, adjustment: Long): (Long, Int) {8
var extra = adjustment / 1000000000L9
var nanos = adjustment % 1000000000L10
if (nanos < 0L) {11
extra -= 1L;12
nanos += 1000000000L13
}14
val result = seconds + extra15
if (((seconds xor result) and (extra xor result)) < 0L)16
throw ArithmeticException()17
return (result, nanos.toInt())18
}20
internal fun durationParts(value: Duration): DurationParts {21
if (value.floorSeconds >= 0L)22
return DurationParts(false, value.floorSeconds.toULong(), value.nanosecondsOfSecond)23
if (value.nanosecondsOfSecond == 0)24
return DurationParts(true, -value.floorSeconds.toULong(), 0)25
return DurationParts(26
true,27
-(value.floorSeconds + 1L).toULong(),28
1000000000 - value.nanosecondsOfSecond29
)30
}32
internal fun durationWholeUnits(parts: DurationParts, unitsPerSecond: ULong): Long {33
val limit =34
if (parts.negative)35
0x8000000000000000uL36
else37
0x7fffffffffffffffuL38
val fraction = parts.nanos.toULong() / (1000000000uL / unitsPerSecond)39
if (parts.seconds > (limit - fraction) / unitsPerSecond)40
throw ArithmeticException()41
val value = parts.seconds * unitsPerSecond + fraction42
return (43
if (parts.negative)44
-value45
else46
value47
).toLong()48
}