Scoop API

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.
3internal fun coreLongToString(value: Long): String {
4 var storage = (0u, 0u, 0u, 0u, 0u)
5 @Unsafe
6 {
7 val bytes = addressOf(storage).cast<Byte>()
8 val length = coreWriteSignedDecimal(value, bytes)
9 return coreStringCopyUtf8Unchecked(bytes + (20L - length), length)
10 }
13internal fun coreULongToString(value: ULong): String {
14 var storage = (0u, 0u, 0u, 0u, 0u)
15 @Unsafe
16 {
17 val bytes = addressOf(storage).cast<Byte>()
18 val length = coreWriteUnsignedDecimal(value, bytes)
19 return coreStringCopyUtf8Unchecked(bytes + (20L - length), length)
20 }
23@Unsafe
24internal 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 += 1L
34 bytes.store(20L - length, 45.toByte())
35 }
36 return length
39@Unsafe
40internal fun coreWriteUnsignedDecimal(input: ULong, bytes: Ptr<Byte>): Long {
41 var value = input
42 var cursor = 20L
43 while (value >= 100000000uL) {
44 val quotient = value / 100000000uL
45 val remainder = (value - quotient * 100000000uL).toUInt()
46 val low = remainder % 10000u
47 val high = remainder / 10000u
48 cursor -= 8L
49 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 = quotient
54 }
55 var tail = value.toUInt()
56 while (tail >= 100u) {
57 val quotient = tail / 100u
58 cursor -= 2L
59 coreWriteDecimalPair(bytes, cursor, tail - quotient * 100u)
60 tail = quotient
61 }
62 if (tail < 10u) {
63 cursor -= 1L
64 bytes.store(cursor, (48u + tail).toByte())
65 } else {
66 cursor -= 2L
67 coreWriteDecimalPair(bytes, cursor, tail)
68 }
69 return 20L - cursor
72@Unsafe
73internal fun coreWriteDecimalPair(bytes: Ptr<Byte>, cursor: Long, value: UInt) {
74 val pairs =
75 "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"
76 val index = value.toLong() * 2L
77 bytes.store(cursor, coreStringByteAt(pairs, index))
78 bytes.store(cursor + 1L, coreStringByteAt(pairs, index + 1L))