2 * charset conversion utils
4 * Copyright (c) 2017 Rob Clark
6 * SPDX-License-Identifier: GPL-2.0+
13 * utf8/utf16 conversion mostly lifted from grub
16 size_t utf16_strlen(const uint16_t *in)
19 for (i = 0; in[i]; i++);
23 size_t utf16_strnlen(const uint16_t *in, size_t count)
26 for (i = 0; count-- && in[i]; i++);
30 uint16_t *utf16_strcpy(uint16_t *dest, const uint16_t *src)
34 while ((*dest++ = *src++) != '\0')
40 uint16_t *utf16_strdup(const uint16_t *s)
43 if (!s || !(new = malloc((utf16_strlen(s) + 1) * 2)))
49 /* Convert UTF-16 to UTF-8. */
50 uint8_t *utf16_to_utf8(uint8_t *dest, const uint16_t *src, size_t size)
52 uint32_t code_high = 0;
55 uint32_t code = *src++;
58 if (code >= 0xDC00 && code <= 0xDFFF) {
60 code = ((code_high - 0xD800) << 10) + (code - 0xDC00) + 0x10000;
62 *dest++ = (code >> 18) | 0xF0;
63 *dest++ = ((code >> 12) & 0x3F) | 0x80;
64 *dest++ = ((code >> 6) & 0x3F) | 0x80;
65 *dest++ = (code & 0x3F) | 0x80;
69 /* *src may be valid. Don't eat it. */
77 } else if (code <= 0x07FF) {
78 *dest++ = (code >> 6) | 0xC0;
79 *dest++ = (code & 0x3F) | 0x80;
80 } else if (code >= 0xD800 && code <= 0xDBFF) {
83 } else if (code >= 0xDC00 && code <= 0xDFFF) {
86 } else if (code < 0x10000) {
87 *dest++ = (code >> 12) | 0xE0;
88 *dest++ = ((code >> 6) & 0x3F) | 0x80;
89 *dest++ = (code & 0x3F) | 0x80;
91 *dest++ = (code >> 18) | 0xF0;
92 *dest++ = ((code >> 12) & 0x3F) | 0x80;
93 *dest++ = ((code >> 6) & 0x3F) | 0x80;
94 *dest++ = (code & 0x3F) | 0x80;
102 uint16_t *utf8_to_utf16(uint16_t *dest, const uint8_t *src, size_t size)
111 /* Exit on zero byte */
114 } else if (*src <= 0xbf) {
117 } else if (*src <= 0xdf) {
118 code = *src++ & 0x1f;
120 } else if (*src <= 0xef) {
121 code = *src++ & 0x0f;
123 } else if (*src <= 0xf7) {
124 code = *src++ & 0x07;
131 for (; extension_bytes && size; --size, --extension_bytes) {
132 if ((*src & 0xc0) == 0x80) {
134 code |= *src++ & 0x3f;
144 if (code < 0x10000) {
148 * Simplified expression for
149 * (((code - 0x10000) >> 10) & 0x3ff) | 0xd800
151 *dest++ = (code >> 10) + 0xd7c0;
152 *dest++ = (code & 0x3ff) | 0xdc00;