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 count2
// in one malformed maximal subpart. At most four bytes are inspected.3
@NoGC @Unsafe4
internal fun coreUtf8Step(bytes: Ptr<UInt8>, remaining: Long): Long {5
val first = bytes.load().toInt()6
if (first <= 127) { return 1L }7
var width = 0L8
var minimum = 1289
var maximum = 19110
if (first >= 194 && first <= 223) {11
width = 2L12
} else if (first >= 224 && first <= 239) {13
width = 3L14
if (first == 224) { minimum = 160 }15
if (first == 237) { maximum = 159 }16
} else if (first >= 240 && first <= 244) {17
width = 4L18
if (first == 240) { minimum = 144 }19
if (first == 244) { maximum = 143 }20
} else { return -1L }21
var index = 1L22
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 = 12827
maximum = 19128
index += 1L29
}30
return width31
}33
@Unsafe34
internal fun coreStringDecodeUtf8(pointer: Ptr<UInt8>, length: Long): (String?, Long) {35
var cursor = 0L36
while (cursor < length) {37
val step = coreUtf8Step(pointer + cursor, length - cursor)38
if (step < 0L) { return (None, cursor) }39
cursor += step40
}41
return (Some(coreStringCopyUtf8Unchecked(pointer.cast<Byte>(), length)), -1L)42
}44
@Unsafe45
internal fun coreStringDecodeUtf8Lossy(pointer: Ptr<UInt8>, length: Long): String {46
var cursor = 0L47
var size = 0L48
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 -step52
}53
val result = coreStringAllocateZeroed(size)54
cursor = 0L55
var output = 0L56
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 += step64
cursor += step65
} else {66
coreStringSetByteUnchecked(result, output, 239.toByte())67
coreStringSetByteUnchecked(result, output + 1L, 191.toByte())68
coreStringSetByteUnchecked(result, output + 2L, 189.toByte())69
output += 3L70
cursor -= step71
}72
}73
return result74
}