scoop:scoop.std:0.1.0
src/text/decimal_magnitude.scoop
Selected production source · src/text/decimal_magnitude.scoop
1
package scoop.text3
// Only the exact decimal-to-binary conversion uses these unsigned base-2^32 limbs.4
internal class DecimalMagnitude internal constructor() {5
private val words: ArrayList<UInt> = ArrayList<UInt>()7
internal val bitLength: Long get() {8
if (words.size == 0L) return 0L9
var top = words[words.size - 1L]10
var bits = (words.size - 1L) * 32L11
while (top != 0u) { top = top shr 1L; bits += 1L }12
return bits13
}15
// The caller only accumulates base-ten digits or multiplies by ten.16
internal fun multiplyAdd(multiplier: UInt, digit: UInt) {17
var carry = digit.toULong()18
var index = 0L19
while (index < words.size) {20
val product = words[index].toULong() * multiplier.toULong() + carry21
words[index] = product.toUInt()22
carry = product shr 32L23
index += 1L24
}25
if (carry != 0uL) words.add(carry.toUInt())26
}28
internal fun shifted(bits: Long): DecimalMagnitude {29
val result = DecimalMagnitude()30
if (words.size == 0L) return result31
var index = 0L32
while (index < bits / 32L) { result.words.add(0u); index += 1L }33
var carry = 0uL34
index = 0L35
while (index < words.size) {36
val value = (words[index].toULong() shl (bits % 32L)) or carry37
result.words.add(value.toUInt())38
carry = value shr 32L39
index += 1L40
}41
if (carry != 0uL) result.words.add(carry.toUInt())42
return result43
}45
private fun word(index: Long): UInt =46
if (index < 0L || index >= words.size) 0u else words[index]48
private fun shiftedWord(index: Long, bits: Long): UInt {49
val position = index - bits / 32L50
val shift = bits % 32L51
val low = word(position) shl shift52
return if (shift == 0L) low else low or (word(position - 1L) shr (32L - shift))53
}55
internal fun compareShifted(other: DecimalMagnitude, bits: Long): Long {56
val leftBits = bitLength57
val rightBits = other.bitLength + bits58
if (leftBits != rightBits) return if (leftBits < rightBits) -1L else 1L59
var index = words.size60
while (index > 0L) {61
index -= 1L62
val right = other.shiftedWord(index, bits)63
if (words[index] != right) return if (words[index] < right) -1L else 1L64
}65
return 0L66
}68
// Called only after comparison establishes a nonnegative difference.69
internal fun subtractShifted(other: DecimalMagnitude, bits: Long) {70
var borrow = 0uL71
var index = 0L72
while (index < words.size) {73
val left = words[index].toULong()74
val right = other.shiftedWord(index, bits).toULong() + borrow75
words[index] = (left - right).toUInt()76
borrow = if (left < right) 1uL else 0uL77
index += 1L78
}79
while (words.size > 0L && words[words.size - 1L] == 0u) words.removeAt(words.size - 1L)80
}81
}