scoop:scoop.platform:0.1.0
src/system/os_string_utf16.scoop
Selected production source · src/system/os_string_utf16.scoop
1
package scoop.platform.system3
import scoop.bytes.ByteArrayBuilder5
internal fun encodeOsUtf16(units: List<UShort>): Array<Byte> {6
val result = ByteArrayBuilder()7
var index = 0L8
while (index < units.size) {9
var point = units[index].toInt()10
index += 1L11
if (point >= 0xd800 && point <= 0xdbff && index < units.size) {12
val next = units[index].toInt()13
if (next >= 0xdc00 && next <= 0xdfff) {14
point = 0x10000 + (point - 0xd800) * 1024 + next - 0xdc0015
index += 1L16
}17
}18
if (point < 0x80) {19
result.append(point.toByte())20
} else21
if (point < 0x800) {22
result.append((0xc0 or (point shr 6)).toByte())23
result.append((0x80 or (point and 0x3f)).toByte())24
} else25
if (point < 0x10000) {26
result.append((0xe0 or (point shr 12)).toByte())27
result.append((0x80 or ((point shr 6) and 0x3f)).toByte())28
result.append((0x80 or (point and 0x3f)).toByte())29
} else {30
result.append((0xf0 or (point shr 18)).toByte())31
result.append((0x80 or ((point shr 12) and 0x3f)).toByte())32
result.append((0x80 or ((point shr 6) and 0x3f)).toByte())33
result.append((0x80 or (point and 0x3f)).toByte())34
}35
}36
return result.toByteArray()37
}39
internal fun decodeOsUtf16(bytes: Array<Byte>): Array<UShort> {40
val result = ArrayList<UShort>()41
var index = 0L42
var previousHigh = -1L43
while (index < bytes.size) {44
val start = index45
val first = bytes[index].toUByte().toInt()46
val(width, minimum, initial) =47
if (first < 0x80) {48
(1L, 0, first)49
} else50
if (first >= 0xc2 && first <= 0xdf) {51
(2L, 0x80, first and 0x1f)52
} else53
if (first >= 0xe0 && first <= 0xef) {54
(3L, 0x800, first and 0x0f)55
} else56
if (first >= 0xf0 && first <= 0xf4) {57
(4L, 0x10000, first and 0x07)58
} else {59
throw CharacterCodingException(start)60
}61
var point = initial62
if (bytes.size - start < width)63
throw CharacterCodingException(start)64
index += 1L65
while (index < start + width) {66
val next = bytes[index].toUByte().toInt()67
if (next < 0x80 || next > 0xbf)68
throw CharacterCodingException(start)69
point = (point shl 6) or (next and 0x3f)70
index += 1L71
}72
if (point < minimum || point > 0x10ffff)73
throw CharacterCodingException(start)74
// Adjacent surrogate byte sequences must use the scalar's four-byte encoding.75
if (previousHigh >= 0L && point >= 0xdc00 && point <= 0xdfff)76
throw CharacterCodingException(previousHigh)77
previousHigh =78
if (point >= 0xd800 && point <= 0xdbff)79
start80
else81
-1L82
if (point < 0x10000) {83
result.add(point.toUShort())84
} else {85
result.add((0xd800 + ((point - 0x10000) shr 10)).toUShort())86
result.add((0xdc00 + ((point - 0x10000) and 0x3ff)).toUShort())87
}88
}89
return result.toArray()90
}