blob: 3ffcf7e34c57cc9ef90c2536894a65fb966cce83 [file] [log] [blame]
Kenny Rootba0165b2010-11-09 14:37:23 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyncfd5b082016-10-17 14:28:00 -070017#define LOG_TAG "unicode"
18
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -070019#include <android-base/macros.h>
Sergio Giro9de67762016-07-20 20:01:33 +010020#include <limits.h>
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -070021#include <utils/Unicode.h>
Kenny Rootba0165b2010-11-09 14:37:23 -080022
Mark Salyzyn30f991f2017-01-10 13:19:54 -080023#include <log/log.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070024
Kenny Rootba0165b2010-11-09 14:37:23 -080025extern "C" {
26
27static const char32_t kByteMask = 0x000000BF;
28static const char32_t kByteMark = 0x00000080;
29
30// Surrogates aren't valid for UTF-32 characters, so define some
31// constants that will let us screen them out.
32static const char32_t kUnicodeSurrogateHighStart = 0x0000D800;
Andreas Gampea53c8152014-11-24 09:42:07 -080033// Unused, here for completeness:
34// static const char32_t kUnicodeSurrogateHighEnd = 0x0000DBFF;
35// static const char32_t kUnicodeSurrogateLowStart = 0x0000DC00;
Kenny Rootba0165b2010-11-09 14:37:23 -080036static const char32_t kUnicodeSurrogateLowEnd = 0x0000DFFF;
37static const char32_t kUnicodeSurrogateStart = kUnicodeSurrogateHighStart;
38static const char32_t kUnicodeSurrogateEnd = kUnicodeSurrogateLowEnd;
39static const char32_t kUnicodeMaxCodepoint = 0x0010FFFF;
40
41// Mask used to set appropriate bits in first byte of UTF-8 sequence,
42// indexed by number of bytes in the sequence.
43// 0xxxxxxx
44// -> (00-7f) 7bit. Bit mask for the first byte is 0x00000000
45// 110yyyyx 10xxxxxx
46// -> (c0-df)(80-bf) 11bit. Bit mask is 0x000000C0
47// 1110yyyy 10yxxxxx 10xxxxxx
48// -> (e0-ef)(80-bf)(80-bf) 16bit. Bit mask is 0x000000E0
49// 11110yyy 10yyxxxx 10xxxxxx 10xxxxxx
50// -> (f0-f7)(80-bf)(80-bf)(80-bf) 21bit. Bit mask is 0x000000F0
51static const char32_t kFirstByteMark[] = {
52 0x00000000, 0x00000000, 0x000000C0, 0x000000E0, 0x000000F0
53};
54
55// --------------------------------------------------------------------------
56// UTF-32
57// --------------------------------------------------------------------------
58
59/**
60 * Return number of UTF-8 bytes required for the character. If the character
61 * is invalid, return size of 0.
62 */
63static inline size_t utf32_codepoint_utf8_length(char32_t srcChar)
64{
65 // Figure out how many bytes the result will require.
66 if (srcChar < 0x00000080) {
67 return 1;
68 } else if (srcChar < 0x00000800) {
69 return 2;
70 } else if (srcChar < 0x00010000) {
71 if ((srcChar < kUnicodeSurrogateStart) || (srcChar > kUnicodeSurrogateEnd)) {
72 return 3;
73 } else {
74 // Surrogates are invalid UTF-32 characters.
75 return 0;
76 }
77 }
78 // Max code point for Unicode is 0x0010FFFF.
79 else if (srcChar <= kUnicodeMaxCodepoint) {
80 return 4;
81 } else {
82 // Invalid UTF-32 character.
83 return 0;
84 }
85}
86
87// Write out the source character to <dstP>.
88
89static inline void utf32_codepoint_to_utf8(uint8_t* dstP, char32_t srcChar, size_t bytes)
90{
91 dstP += bytes;
92 switch (bytes)
93 { /* note: everything falls through. */
94 case 4: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -070095 FALLTHROUGH_INTENDED;
Kenny Rootba0165b2010-11-09 14:37:23 -080096 case 3: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -070097 FALLTHROUGH_INTENDED;
Kenny Rootba0165b2010-11-09 14:37:23 -080098 case 2: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
Chih-Hung Hsieh502f4862018-09-13 11:08:41 -070099 FALLTHROUGH_INTENDED;
Kenny Rootba0165b2010-11-09 14:37:23 -0800100 case 1: *--dstP = (uint8_t)(srcChar | kFirstByteMark[bytes]);
101 }
102}
103
Kenny Rootba0165b2010-11-09 14:37:23 -0800104static inline int32_t utf32_at_internal(const char* cur, size_t *num_read)
105{
106 const char first_char = *cur;
107 if ((first_char & 0x80) == 0) { // ASCII
108 *num_read = 1;
109 return *cur;
110 }
111 cur++;
112 char32_t mask, to_ignore_mask;
113 size_t num_to_read = 0;
114 char32_t utf32 = first_char;
115 for (num_to_read = 1, mask = 0x40, to_ignore_mask = 0xFFFFFF80;
116 (first_char & mask);
117 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
118 // 0x3F == 00111111
119 utf32 = (utf32 << 6) + (*cur++ & 0x3F);
120 }
121 to_ignore_mask |= mask;
122 utf32 &= ~(to_ignore_mask << (6 * (num_to_read - 1)));
123
124 *num_read = num_to_read;
125 return static_cast<int32_t>(utf32);
126}
127
128int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index)
129{
130 if (index >= src_len) {
131 return -1;
132 }
Dan Albertac4500e2020-07-27 14:03:56 -0700133 size_t unused_index;
Yi Konge1731a42018-07-16 18:11:34 -0700134 if (next_index == nullptr) {
Dan Albertac4500e2020-07-27 14:03:56 -0700135 next_index = &unused_index;
Kenny Rootba0165b2010-11-09 14:37:23 -0800136 }
137 size_t num_read;
138 int32_t ret = utf32_at_internal(src + index, &num_read);
139 if (ret >= 0) {
140 *next_index = index + num_read;
141 }
142
143 return ret;
144}
145
146ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len)
147{
Yi Konge1731a42018-07-16 18:11:34 -0700148 if (src == nullptr || src_len == 0) {
Kenny Rootba0165b2010-11-09 14:37:23 -0800149 return -1;
150 }
151
152 size_t ret = 0;
153 const char32_t *end = src + src_len;
154 while (src < end) {
Adam Vartanian47efc672017-08-14 15:51:29 +0100155 size_t char_len = utf32_codepoint_utf8_length(*src++);
156 if (SSIZE_MAX - char_len < ret) {
157 // If this happens, we would overflow the ssize_t type when
158 // returning from this function, so we cannot express how
159 // long this string is in an ssize_t.
160 android_errorWriteLog(0x534e4554, "37723026");
161 return -1;
162 }
163 ret += char_len;
Kenny Rootba0165b2010-11-09 14:37:23 -0800164 }
165 return ret;
166}
167
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100168void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len)
Kenny Rootba0165b2010-11-09 14:37:23 -0800169{
Yi Konge1731a42018-07-16 18:11:34 -0700170 if (src == nullptr || src_len == 0 || dst == nullptr) {
Kenny Rootba0165b2010-11-09 14:37:23 -0800171 return;
172 }
173
174 const char32_t *cur_utf32 = src;
175 const char32_t *end_utf32 = src + src_len;
176 char *cur = dst;
177 while (cur_utf32 < end_utf32) {
178 size_t len = utf32_codepoint_utf8_length(*cur_utf32);
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100179 LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len);
Kenny Rootba0165b2010-11-09 14:37:23 -0800180 utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len);
181 cur += len;
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100182 dst_len -= len;
Kenny Rootba0165b2010-11-09 14:37:23 -0800183 }
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100184 LOG_ALWAYS_FATAL_IF(dst_len < 1, "dst_len < 1: %zu < 1", dst_len);
Kenny Rootba0165b2010-11-09 14:37:23 -0800185 *cur = '\0';
186}
187
188// --------------------------------------------------------------------------
189// UTF-16
190// --------------------------------------------------------------------------
191
192int strcmp16(const char16_t *s1, const char16_t *s2)
193{
194 char16_t ch;
195 int d = 0;
196
197 while ( 1 ) {
198 d = (int)(ch = *s1++) - (int)*s2++;
199 if ( d || !ch )
200 break;
201 }
202
203 return d;
204}
205
206int strncmp16(const char16_t *s1, const char16_t *s2, size_t n)
207{
208 char16_t ch;
209 int d = 0;
210
Michael Wright5bacef32016-05-09 14:43:31 +0100211 if (n == 0) {
212 return 0;
Kenny Rootba0165b2010-11-09 14:37:23 -0800213 }
214
Michael Wright5bacef32016-05-09 14:43:31 +0100215 do {
216 d = (int)(ch = *s1++) - (int)*s2++;
217 if ( d || !ch ) {
218 break;
219 }
220 } while (--n);
221
Kenny Rootba0165b2010-11-09 14:37:23 -0800222 return d;
223}
224
Kenny Rootba0165b2010-11-09 14:37:23 -0800225size_t strlen16(const char16_t *s)
226{
227 const char16_t *ss = s;
228 while ( *ss )
229 ss++;
230 return ss-s;
231}
232
Kenny Rootba0165b2010-11-09 14:37:23 -0800233size_t strnlen16(const char16_t *s, size_t maxlen)
234{
235 const char16_t *ss = s;
236
237 /* Important: the maxlen test must precede the reference through ss;
238 since the byte beyond the maximum may segfault */
239 while ((maxlen > 0) && *ss) {
240 ss++;
241 maxlen--;
242 }
243 return ss-s;
244}
245
Michael Wright5bacef32016-05-09 14:43:31 +0100246char16_t* strstr16(const char16_t* src, const char16_t* target)
247{
Branislav Rankovbf3fff12017-10-12 15:08:42 +0200248 const char16_t needle = *target;
249 if (needle == '\0') return (char16_t*)src;
250
251 const size_t target_len = strlen16(++target);
252 do {
Michael Wright5bacef32016-05-09 14:43:31 +0100253 do {
Branislav Rankovbf3fff12017-10-12 15:08:42 +0200254 if (*src == '\0') {
255 return nullptr;
256 }
Michael Wright5bacef32016-05-09 14:43:31 +0100257 } while (*src++ != needle);
Branislav Rankovbf3fff12017-10-12 15:08:42 +0200258 } while (strncmp16(src, target, target_len) != 0);
259 src--;
Michael Wright5bacef32016-05-09 14:43:31 +0100260
261 return (char16_t*)src;
262}
263
Kenny Rootba0165b2010-11-09 14:37:23 -0800264int strzcmp16(const char16_t *s1, size_t n1, const char16_t *s2, size_t n2)
265{
266 const char16_t* e1 = s1+n1;
267 const char16_t* e2 = s2+n2;
268
269 while (s1 < e1 && s2 < e2) {
270 const int d = (int)*s1++ - (int)*s2++;
271 if (d) {
272 return d;
273 }
274 }
275
276 return n1 < n2
277 ? (0 - (int)*s2)
278 : (n1 > n2
279 ? ((int)*s1 - 0)
280 : 0);
281}
282
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100283void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len)
Kenny Rootba0165b2010-11-09 14:37:23 -0800284{
Yi Konge1731a42018-07-16 18:11:34 -0700285 if (src == nullptr || src_len == 0 || dst == nullptr) {
Kenny Rootba0165b2010-11-09 14:37:23 -0800286 return;
287 }
288
289 const char16_t* cur_utf16 = src;
290 const char16_t* const end_utf16 = src + src_len;
291 char *cur = dst;
292 while (cur_utf16 < end_utf16) {
293 char32_t utf32;
294 // surrogate pairs
Cylen Yao72299bf2014-06-04 19:11:27 +0800295 if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16
296 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) {
Kenny Rootba0165b2010-11-09 14:37:23 -0800297 utf32 = (*cur_utf16++ - 0xD800) << 10;
298 utf32 |= *cur_utf16++ - 0xDC00;
299 utf32 += 0x10000;
300 } else {
301 utf32 = (char32_t) *cur_utf16++;
302 }
303 const size_t len = utf32_codepoint_utf8_length(utf32);
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100304 LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len);
Kenny Rootba0165b2010-11-09 14:37:23 -0800305 utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len);
306 cur += len;
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100307 dst_len -= len;
Kenny Rootba0165b2010-11-09 14:37:23 -0800308 }
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100309 LOG_ALWAYS_FATAL_IF(dst_len < 1, "%zu < 1", dst_len);
Kenny Rootba0165b2010-11-09 14:37:23 -0800310 *cur = '\0';
311}
312
313// --------------------------------------------------------------------------
314// UTF-8
315// --------------------------------------------------------------------------
316
Kenny Rootba0165b2010-11-09 14:37:23 -0800317ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len)
318{
Yi Konge1731a42018-07-16 18:11:34 -0700319 if (src == nullptr || src_len == 0) {
Kenny Rootba0165b2010-11-09 14:37:23 -0800320 return -1;
321 }
322
323 size_t ret = 0;
324 const char16_t* const end = src + src_len;
325 while (src < end) {
Adam Vartanian47efc672017-08-14 15:51:29 +0100326 size_t char_len;
Kenny Rootba0165b2010-11-09 14:37:23 -0800327 if ((*src & 0xFC00) == 0xD800 && (src + 1) < end
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100328 && (*(src + 1) & 0xFC00) == 0xDC00) {
Kenny Rootba0165b2010-11-09 14:37:23 -0800329 // surrogate pairs are always 4 bytes.
Adam Vartanian47efc672017-08-14 15:51:29 +0100330 char_len = 4;
Sergio Giro1cfa56d2016-06-28 18:02:29 +0100331 src += 2;
Kenny Rootba0165b2010-11-09 14:37:23 -0800332 } else {
Adam Vartanian47efc672017-08-14 15:51:29 +0100333 char_len = utf32_codepoint_utf8_length((char32_t)*src++);
Kenny Rootba0165b2010-11-09 14:37:23 -0800334 }
Adam Vartanian47efc672017-08-14 15:51:29 +0100335 if (SSIZE_MAX - char_len < ret) {
336 // If this happens, we would overflow the ssize_t type when
337 // returning from this function, so we cannot express how
338 // long this string is in an ssize_t.
339 android_errorWriteLog(0x534e4554, "37723026");
340 return -1;
341 }
342 ret += char_len;
Kenny Rootba0165b2010-11-09 14:37:23 -0800343 }
344 return ret;
345}
346
347/**
348 * Returns 1-4 based on the number of leading bits.
349 *
350 * 1111 -> 4
351 * 1110 -> 3
352 * 110x -> 2
353 * 10xx -> 1
354 * 0xxx -> 1
355 */
356static inline size_t utf8_codepoint_len(uint8_t ch)
357{
358 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
359}
360
361static inline void utf8_shift_and_mask(uint32_t* codePoint, const uint8_t byte)
362{
363 *codePoint <<= 6;
364 *codePoint |= 0x3F & byte;
365}
366
Kenny Rootba0165b2010-11-09 14:37:23 -0800367static inline uint32_t utf8_to_utf32_codepoint(const uint8_t *src, size_t length)
368{
369 uint32_t unicode;
370
371 switch (length)
372 {
373 case 1:
374 return src[0];
375 case 2:
376 unicode = src[0] & 0x1f;
377 utf8_shift_and_mask(&unicode, src[1]);
378 return unicode;
379 case 3:
380 unicode = src[0] & 0x0f;
381 utf8_shift_and_mask(&unicode, src[1]);
382 utf8_shift_and_mask(&unicode, src[2]);
383 return unicode;
384 case 4:
385 unicode = src[0] & 0x07;
386 utf8_shift_and_mask(&unicode, src[1]);
387 utf8_shift_and_mask(&unicode, src[2]);
388 utf8_shift_and_mask(&unicode, src[3]);
389 return unicode;
390 default:
391 return 0xffff;
392 }
393
394 //printf("Char at %p: len=%d, utf-16=%p\n", src, length, (void*)result);
395}
396
Sergio Giro9de67762016-07-20 20:01:33 +0100397ssize_t utf8_to_utf16_length(const uint8_t* u8str, size_t u8len, bool overreadIsFatal)
Kenny Rootba0165b2010-11-09 14:37:23 -0800398{
399 const uint8_t* const u8end = u8str + u8len;
400 const uint8_t* u8cur = u8str;
401
402 /* Validate that the UTF-8 is the correct len */
403 size_t u16measuredLen = 0;
404 while (u8cur < u8end) {
405 u16measuredLen++;
406 int u8charLen = utf8_codepoint_len(*u8cur);
Sergio Giro9de67762016-07-20 20:01:33 +0100407 // Malformed utf8, some characters are beyond the end.
408 // Cases:
409 // If u8charLen == 1, this becomes u8cur >= u8end, which cannot happen as u8cur < u8end,
410 // then this condition fail and we continue, as expected.
411 // If u8charLen == 2, this becomes u8cur + 1 >= u8end, which fails only if
412 // u8cur == u8end - 1, that is, there was only one remaining character to read but we need
413 // 2 of them. This condition holds and we return -1, as expected.
414 if (u8cur + u8charLen - 1 >= u8end) {
415 if (overreadIsFatal) {
416 LOG_ALWAYS_FATAL("Attempt to overread computing length of utf8 string");
417 } else {
418 return -1;
419 }
420 }
Kenny Rootba0165b2010-11-09 14:37:23 -0800421 uint32_t codepoint = utf8_to_utf32_codepoint(u8cur, u8charLen);
422 if (codepoint > 0xFFFF) u16measuredLen++; // this will be a surrogate pair in utf16
423 u8cur += u8charLen;
424 }
425
426 /**
427 * Make sure that we ended where we thought we would and the output UTF-16
428 * will be exactly how long we were told it would be.
429 */
430 if (u8cur != u8end) {
431 return -1;
432 }
433
434 return u16measuredLen;
435}
436
Sergio Giro9de67762016-07-20 20:01:33 +0100437char16_t* utf8_to_utf16(const uint8_t* u8str, size_t u8len, char16_t* u16str, size_t u16len) {
438 // A value > SSIZE_MAX is probably a negative value returned as an error and casted.
439 LOG_ALWAYS_FATAL_IF(u16len == 0 || u16len > SSIZE_MAX, "u16len is %zu", u16len);
440 char16_t* end = utf8_to_utf16_no_null_terminator(u8str, u8len, u16str, u16len - 1);
Jeff Brownaa983c92011-10-07 13:28:18 -0700441 *end = 0;
Sergio Giro9de67762016-07-20 20:01:33 +0100442 return end;
Kenny Rootba0165b2010-11-09 14:37:23 -0800443}
444
Sergio Giro9de67762016-07-20 20:01:33 +0100445char16_t* utf8_to_utf16_no_null_terminator(
446 const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen) {
447 if (dstLen == 0) {
448 return dst;
449 }
450 // A value > SSIZE_MAX is probably a negative value returned as an error and casted.
451 LOG_ALWAYS_FATAL_IF(dstLen > SSIZE_MAX, "dstLen is %zu", dstLen);
Dianne Hackborn0f10d0a2013-07-31 16:04:39 -0700452 const uint8_t* const u8end = src + srcLen;
453 const uint8_t* u8cur = src;
Mark Salyzyn5bed8032014-04-30 11:10:46 -0700454 const char16_t* const u16end = dst + dstLen;
Dianne Hackborn0f10d0a2013-07-31 16:04:39 -0700455 char16_t* u16cur = dst;
456
457 while (u8cur < u8end && u16cur < u16end) {
458 size_t u8len = utf8_codepoint_len(*u8cur);
459 uint32_t codepoint = utf8_to_utf32_codepoint(u8cur, u8len);
460
461 // Convert the UTF32 codepoint to one or more UTF16 codepoints
462 if (codepoint <= 0xFFFF) {
463 // Single UTF16 character
464 *u16cur++ = (char16_t) codepoint;
465 } else {
466 // Multiple UTF16 characters with surrogates
467 codepoint = codepoint - 0x10000;
468 *u16cur++ = (char16_t) ((codepoint >> 10) + 0xD800);
469 if (u16cur >= u16end) {
470 // Ooops... not enough room for this surrogate pair.
471 return u16cur-1;
472 }
473 *u16cur++ = (char16_t) ((codepoint & 0x3FF) + 0xDC00);
474 }
475
476 u8cur += u8len;
477 }
478 return u16cur;
479}
480
Kenny Rootba0165b2010-11-09 14:37:23 -0800481}