scoop:scoop.core:0.1.0
src/integer_decimal.scoop
Selected production source · src/integer_decimal.scoop
1
// Decimal formatting writes once into a twenty-byte GC-free local place.2
// Pair lookup and eight-digit chunks follow the vendored Ryu digit writer.3
internal fun coreLongToString(value: Long): String {4
var storage = (0u, 0u, 0u, 0u, 0u)5
@Unsafe6
{7
val bytes = addressOf(storage).cast<Byte>()8
val length = coreWriteSignedDecimal(value, bytes)9
return coreStringCopyUtf8Unchecked(bytes + (20L - length), length)10
}11
}13
internal fun coreULongToString(value: ULong): String {14
var storage = (0u, 0u, 0u, 0u, 0u)15
@Unsafe16
{17
val bytes = addressOf(storage).cast<Byte>()18
val length = coreWriteUnsignedDecimal(value, bytes)19
return coreStringCopyUtf8Unchecked(bytes + (20L - length), length)20
}21
}23
@Unsafe24
internal fun coreWriteSignedDecimal(value: Long, bytes: Ptr<Byte>): Long {25
val magnitude =26
if (value < 0L) {27
0uL - value.toULong()28
} else {29
value.toULong()30
}31
var length = coreWriteUnsignedDecimal(magnitude, bytes)32
if (value < 0L) {33
length += 1L34
bytes.store(20L - length, 45.toByte())35
}36
return length37
}39
@Unsafe40
internal fun coreWriteUnsignedDecimal(input: ULong, bytes: Ptr<Byte>): Long {41
var value = input42
var cursor = 20L43
while (value >= 100000000uL) {44
val quotient = value / 100000000uL45
val remainder = (value - quotient * 100000000uL).toUInt()46
val low = remainder % 10000u47
val high = remainder / 10000u48
cursor -= 8L49
coreWriteDecimalPair(bytes, cursor + 6L, low % 100u)50
coreWriteDecimalPair(bytes, cursor + 4L, low / 100u)51
coreWriteDecimalPair(bytes, cursor + 2L, high % 100u)52
coreWriteDecimalPair(bytes, cursor, high / 100u)53
value = quotient54
}55
var tail = value.toUInt()56
while (tail >= 100u) {57
val quotient = tail / 100u58
cursor -= 2L59
coreWriteDecimalPair(bytes, cursor, tail - quotient * 100u)60
tail = quotient61
}62
if (tail < 10u) {63
cursor -= 1L64
bytes.store(cursor, (48u + tail).toByte())65
} else {66
cursor -= 2L67
coreWriteDecimalPair(bytes, cursor, tail)68
}69
return 20L - cursor70
}72
@Unsafe73
internal fun coreWriteDecimalPair(bytes: Ptr<Byte>, cursor: Long, value: UInt) {74
val pairs =75
"00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"76
val index = value.toLong() * 2L77
bytes.store(cursor, coreStringByteAt(pairs, index))78
bytes.store(cursor + 1L, coreStringByteAt(pairs, index + 1L))79
}