public fun utf8OffsetToUtf16Offset()

in kotlin-desktop-toolkit/src/main/kotlin/org/jetbrains/desktop/linux/Converters.kt [72:95]


public fun utf8OffsetToUtf16Offset(string: CharSequence, offset: Int): Int {
    if (offset == 0) {
        return 0
    }
    var utf8Offset = offset
    var utf16Offset = 0
    for (codePoint in string.codePoints()) {
        utf8Offset -= when {
            codePoint < 128 -> 1
            codePoint < 2048 -> 2
            codePoint < 65536 -> 3
            else -> 4
        }

        utf16Offset += 1
        // Code points from the supplementary planes are encoded as a surrogate pair in utf-16,
        // meaning we'll have one extra utf-16 code unit for every code point in this range.
        if (codePoint >= 65536) utf16Offset += 1

        if (utf8Offset <= 0) break
    }

    return utf16Offset
}