scoop:scoop.core:0.1.0
src/utf8_encoding.scoop
Selected production source · src/utf8_encoding.scoop
1
@NoGC2
internal fun coreUtf8Width(code: UInt): Long =3
if (code < 128u) 1L else if (code < 2048u) 2L else if (code < 65536u) 3L else 4L5
// Pack a scalar's UTF-8 bytes least-significant first. Both supported ABIs6
// use little-endian storage; callers write only coreUtf8Width(code) bytes.7
@NoGC8
internal fun coreUtf8Word(code: UInt): UInt {9
if (code < 128u) { return code }10
if (code < 2048u) {11
return (192u.or(code.shr(6L))).or((128u.or(code.and(63u))).shl(8L))12
}13
if (code < 65536u) {14
return (224u.or(code.shr(12L))).or((128u.or(code.shr(6L).and(63u))).shl(8L))15
.or((128u.or(code.and(63u))).shl(16L))16
}17
return (240u.or(code.shr(18L))).or((128u.or(code.shr(12L).and(63u))).shl(8L))18
.or((128u.or(code.shr(6L).and(63u))).shl(16L))19
.or((128u.or(code.and(63u))).shl(24L))20
}22
internal fun coreStringAddLength(length: Long, extra: Long): Long {23
if (length > 9223372036854775776L - extra) { coreAllocationOverflow() }24
return length + extra25
}27
internal fun coreStringFromChars(value: Array<Char>): String {28
val count = value.size29
var length = 0L30
var index = 0L31
while (index < count) {32
length = coreStringAddLength(length, coreUtf8Width(value[index].code.toUInt()))33
index += 1L34
}35
val result = coreStringAllocateZeroed(length)36
index = 0L37
var cursor = 0L38
while (index < count) {39
val code = value[index].code.toUInt()40
val word = coreUtf8Word(code)41
val width = coreUtf8Width(code)42
@Unsafe {43
coreStringSetByteUnchecked(result, cursor, word.toByte())44
if (width > 1L) { coreStringSetByteUnchecked(result, cursor + 1L, word.shr(8L).toByte()) }45
if (width > 2L) { coreStringSetByteUnchecked(result, cursor + 2L, word.shr(16L).toByte()) }46
if (width > 3L) { coreStringSetByteUnchecked(result, cursor + 3L, word.shr(24L).toByte()) }47
}48
cursor += width49
index += 1L50
}51
return result52
}