Scoop API

scoop:scoop.core:0.1.0

src/utf8_validation.scoop

Selected production source · src/utf8_validation.scoop

1// Positive means a valid scalar's byte width; negative means the byte count
2// in one malformed maximal subpart. At most four bytes are inspected.
3@NoGC @Unsafe
4internal fun coreUtf8Step(bytes: Ptr<UInt8>, remaining: Long): Long {
5 val first = bytes.load().toInt()
6 if (first <= 127) { return 1L }
7 var width = 0L
8 var minimum = 128
9 var maximum = 191
10 if (first >= 194 && first <= 223) {
11 width = 2L
12 } else if (first >= 224 && first <= 239) {
13 width = 3L
14 if (first == 224) { minimum = 160 }
15 if (first == 237) { maximum = 159 }
16 } else if (first >= 240 && first <= 244) {
17 width = 4L
18 if (first == 240) { minimum = 144 }
19 if (first == 244) { maximum = 143 }
20 } else { return -1L }
21 var index = 1L
22 while (index < width) {
23 if (index >= remaining) { return -index }
24 val byte = bytes.load(index).toInt()
25 if (byte < minimum || byte > maximum) { return -index }
26 minimum = 128
27 maximum = 191
28 index += 1L
29 }
30 return width
33@Unsafe
34internal fun coreStringDecodeUtf8(pointer: Ptr<UInt8>, length: Long): (String?, Long) {
35 var cursor = 0L
36 while (cursor < length) {
37 val step = coreUtf8Step(pointer + cursor, length - cursor)
38 if (step < 0L) { return (None, cursor) }
39 cursor += step
40 }
41 return (Some(coreStringCopyUtf8Unchecked(pointer.cast<Byte>(), length)), -1L)
44@Unsafe
45internal fun coreStringDecodeUtf8Lossy(pointer: Ptr<UInt8>, length: Long): String {
46 var cursor = 0L
47 var size = 0L
48 while (cursor < length) {
49 val step = coreUtf8Step(pointer + cursor, length - cursor)
50 size = coreStringAddLength(size, if (step > 0L) step else 3L)
51 cursor += if (step > 0L) step else -step
52 }
53 val result = coreStringAllocateZeroed(size)
54 cursor = 0L
55 var output = 0L
56 while (cursor < length) {
57 val step = coreUtf8Step(pointer + cursor, length - cursor)
58 if (step > 0L) {
59 coreStringSetByteUnchecked(result, output, pointer.load(cursor).toByte())
60 if (step > 1L) { coreStringSetByteUnchecked(result, output + 1L, pointer.load(cursor + 1L).toByte()) }
61 if (step > 2L) { coreStringSetByteUnchecked(result, output + 2L, pointer.load(cursor + 2L).toByte()) }
62 if (step > 3L) { coreStringSetByteUnchecked(result, output + 3L, pointer.load(cursor + 3L).toByte()) }
63 output += step
64 cursor += step
65 } else {
66 coreStringSetByteUnchecked(result, output, 239.toByte())
67 coreStringSetByteUnchecked(result, output + 1L, 191.toByte())
68 coreStringSetByteUnchecked(result, output + 2L, 189.toByte())
69 output += 3L
70 cursor -= step
71 }
72 }
73 return result