Scoop API

scoop:scoop.core:0.1.0

src/utf8_encoding.scoop

Selected production source · src/utf8_encoding.scoop

1@NoGC
2internal fun coreUtf8Width(code: UInt): Long =
3 if (code < 128u) 1L else if (code < 2048u) 2L else if (code < 65536u) 3L else 4L
5// Pack a scalar's UTF-8 bytes least-significant first. Both supported ABIs
6// use little-endian storage; callers write only coreUtf8Width(code) bytes.
7@NoGC
8internal 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))
22internal fun coreStringAddLength(length: Long, extra: Long): Long {
23 if (length > 9223372036854775776L - extra) { coreAllocationOverflow() }
24 return length + extra
27internal fun coreStringFromChars(value: Array<Char>): String {
28 val count = value.size
29 var length = 0L
30 var index = 0L
31 while (index < count) {
32 length = coreStringAddLength(length, coreUtf8Width(value[index].code.toUInt()))
33 index += 1L
34 }
35 val result = coreStringAllocateZeroed(length)
36 index = 0L
37 var cursor = 0L
38 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 += width
49 index += 1L
50 }
51 return result