Scoop API

scoop:scoop.std:0.1.0

src/text/decimal_magnitude.scoop

Selected production source · src/text/decimal_magnitude.scoop

1package scoop.text
3// Only the exact decimal-to-binary conversion uses these unsigned base-2^32 limbs.
4internal class DecimalMagnitude internal constructor() {
5 private val words: ArrayList<UInt> = ArrayList<UInt>()
7 internal val bitLength: Long get() {
8 if (words.size == 0L) return 0L
9 var top = words[words.size - 1L]
10 var bits = (words.size - 1L) * 32L
11 while (top != 0u) { top = top shr 1L; bits += 1L }
12 return bits
13 }
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 = 0L
19 while (index < words.size) {
20 val product = words[index].toULong() * multiplier.toULong() + carry
21 words[index] = product.toUInt()
22 carry = product shr 32L
23 index += 1L
24 }
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 result
31 var index = 0L
32 while (index < bits / 32L) { result.words.add(0u); index += 1L }
33 var carry = 0uL
34 index = 0L
35 while (index < words.size) {
36 val value = (words[index].toULong() shl (bits % 32L)) or carry
37 result.words.add(value.toUInt())
38 carry = value shr 32L
39 index += 1L
40 }
41 if (carry != 0uL) result.words.add(carry.toUInt())
42 return result
43 }
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 / 32L
50 val shift = bits % 32L
51 val low = word(position) shl shift
52 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 = bitLength
57 val rightBits = other.bitLength + bits
58 if (leftBits != rightBits) return if (leftBits < rightBits) -1L else 1L
59 var index = words.size
60 while (index > 0L) {
61 index -= 1L
62 val right = other.shiftedWord(index, bits)
63 if (words[index] != right) return if (words[index] < right) -1L else 1L
64 }
65 return 0L
66 }
68 // Called only after comparison establishes a nonnegative difference.
69 internal fun subtractShifted(other: DecimalMagnitude, bits: Long) {
70 var borrow = 0uL
71 var index = 0L
72 while (index < words.size) {
73 val left = words[index].toULong()
74 val right = other.shiftedWord(index, bits).toULong() + borrow
75 words[index] = (left - right).toUInt()
76 borrow = if (left < right) 1uL else 0uL
77 index += 1L
78 }
79 while (words.size > 0L && words[words.size - 1L] == 0u) words.removeAt(words.size - 1L)
80 }