udev: String substitutions can be done in ENV, too
[systemd_ALT.git] / src / basic / utf8.c
blob9d9e76904ee103518e47f4a79abd331d7c4ef2f0
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 /* Parts of this file are based on the GLIB utf8 validation functions. The
4 * original license text follows. */
6 /* gutf8.c - Operations on UTF-8 strings.
8 * Copyright (C) 1999 Tom Tromey
9 * Copyright (C) 2000 Red Hat, Inc.
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include <errno.h>
27 #include <stdbool.h>
28 #include <stdlib.h>
30 #include "alloc-util.h"
31 #include "gunicode.h"
32 #include "hexdecoct.h"
33 #include "macro.h"
34 #include "string-util.h"
35 #include "utf8.h"
37 bool unichar_is_valid(char32_t ch) {
39 if (ch >= 0x110000) /* End of unicode space */
40 return false;
41 if ((ch & 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
42 return false;
43 if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) /* Reserved */
44 return false;
45 if ((ch & 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
46 return false;
48 return true;
51 static bool unichar_is_control(char32_t ch) {
54 0 to ' '-1 is the C0 range.
55 DEL=0x7F, and DEL+1 to 0x9F is C1 range.
56 '\t' is in C0 range, but more or less harmless and commonly used.
59 return (ch < ' ' && !IN_SET(ch, '\t', '\n')) ||
60 (0x7F <= ch && ch <= 0x9F);
63 /* count of characters used to encode one unicode char */
64 static size_t utf8_encoded_expected_len(uint8_t c) {
65 if (c < 0x80)
66 return 1;
67 if ((c & 0xe0) == 0xc0)
68 return 2;
69 if ((c & 0xf0) == 0xe0)
70 return 3;
71 if ((c & 0xf8) == 0xf0)
72 return 4;
73 if ((c & 0xfc) == 0xf8)
74 return 5;
75 if ((c & 0xfe) == 0xfc)
76 return 6;
78 return 0;
81 /* decode one unicode char */
82 int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar) {
83 char32_t unichar;
84 size_t len;
86 assert(str);
88 len = utf8_encoded_expected_len(str[0]);
90 switch (len) {
91 case 1:
92 *ret_unichar = (char32_t)str[0];
93 return 1;
94 case 2:
95 unichar = str[0] & 0x1f;
96 break;
97 case 3:
98 unichar = (char32_t)str[0] & 0x0f;
99 break;
100 case 4:
101 unichar = (char32_t)str[0] & 0x07;
102 break;
103 case 5:
104 unichar = (char32_t)str[0] & 0x03;
105 break;
106 case 6:
107 unichar = (char32_t)str[0] & 0x01;
108 break;
109 default:
110 return -EINVAL;
113 for (size_t i = 1; i < len; i++) {
114 if (((char32_t)str[i] & 0xc0) != 0x80)
115 return -EINVAL;
117 unichar <<= 6;
118 unichar |= (char32_t)str[i] & 0x3f;
121 *ret_unichar = unichar;
122 return len;
125 bool utf8_is_printable_newline(const char* str, size_t length, bool allow_newline) {
126 assert(str);
128 for (const char *p = str; length > 0;) {
129 int encoded_len;
130 char32_t val;
132 encoded_len = utf8_encoded_valid_unichar(p, length);
133 if (encoded_len < 0)
134 return false;
135 assert(encoded_len > 0 && (size_t) encoded_len <= length);
137 if (utf8_encoded_to_unichar(p, &val) < 0 ||
138 unichar_is_control(val) ||
139 (!allow_newline && val == '\n'))
140 return false;
142 length -= encoded_len;
143 p += encoded_len;
146 return true;
149 char *utf8_is_valid_n(const char *str, size_t len_bytes) {
150 /* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after
151 * len_bytes. Otherwise, stop at NUL. */
153 assert(str);
155 for (const char *p = str; len_bytes != SIZE_MAX ? (size_t) (p - str) < len_bytes : *p != '\0'; ) {
156 int len;
158 if (_unlikely_(*p == '\0') && len_bytes != SIZE_MAX)
159 return NULL; /* embedded NUL */
161 len = utf8_encoded_valid_unichar(p,
162 len_bytes != SIZE_MAX ? len_bytes - (p - str) : SIZE_MAX);
163 if (_unlikely_(len < 0))
164 return NULL; /* invalid character */
166 p += len;
169 return (char*) str;
172 char *utf8_escape_invalid(const char *str) {
173 char *p, *s;
175 assert(str);
177 p = s = malloc(strlen(str) * 4 + 1);
178 if (!p)
179 return NULL;
181 while (*str) {
182 int len;
184 len = utf8_encoded_valid_unichar(str, SIZE_MAX);
185 if (len > 0) {
186 s = mempcpy(s, str, len);
187 str += len;
188 } else {
189 s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER);
190 str += 1;
194 *s = '\0';
195 return str_realloc(p);
198 static int utf8_char_console_width(const char *str) {
199 char32_t c;
200 int r;
202 r = utf8_encoded_to_unichar(str, &c);
203 if (r < 0)
204 return r;
206 /* TODO: we should detect combining characters */
208 return unichar_iswide(c) ? 2 : 1;
211 char *utf8_escape_non_printable_full(const char *str, size_t console_width, bool force_ellipsis) {
212 char *p, *s, *prev_s;
213 size_t n = 0; /* estimated print width */
215 assert(str);
217 if (console_width == 0)
218 return strdup("");
220 p = s = prev_s = malloc(strlen(str) * 4 + 1);
221 if (!p)
222 return NULL;
224 for (;;) {
225 int len;
226 char *saved_s = s;
228 if (!*str) { /* done! */
229 if (force_ellipsis)
230 goto truncation;
231 else
232 goto finish;
235 len = utf8_encoded_valid_unichar(str, SIZE_MAX);
236 if (len > 0) {
237 if (utf8_is_printable(str, len)) {
238 int w;
240 w = utf8_char_console_width(str);
241 assert(w >= 0);
242 if (n + w > console_width)
243 goto truncation;
245 s = mempcpy(s, str, len);
246 str += len;
247 n += w;
249 } else {
250 for (; len > 0; len--) {
251 if (n + 4 > console_width)
252 goto truncation;
254 *(s++) = '\\';
255 *(s++) = 'x';
256 *(s++) = hexchar((int) *str >> 4);
257 *(s++) = hexchar((int) *str);
259 str += 1;
260 n += 4;
263 } else {
264 if (n + 1 > console_width)
265 goto truncation;
267 s = mempcpy(s, UTF8_REPLACEMENT_CHARACTER, strlen(UTF8_REPLACEMENT_CHARACTER));
268 str += 1;
269 n += 1;
272 prev_s = saved_s;
275 truncation:
276 /* Try to go back one if we don't have enough space for the ellipsis */
277 if (n + 1 > console_width)
278 s = prev_s;
280 s = mempcpy(s, "…", strlen("…"));
282 finish:
283 *s = '\0';
284 return str_realloc(p);
287 char *ascii_is_valid(const char *str) {
288 /* Check whether the string consists of valid ASCII bytes,
289 * i.e values between 0 and 127, inclusive. */
291 assert(str);
293 for (const char *p = str; *p; p++)
294 if ((unsigned char) *p >= 128)
295 return NULL;
297 return (char*) str;
300 char *ascii_is_valid_n(const char *str, size_t len) {
301 /* Very similar to ascii_is_valid(), but checks exactly len
302 * bytes and rejects any NULs in that range. */
304 assert(str);
306 for (size_t i = 0; i < len; i++)
307 if ((unsigned char) str[i] >= 128 || str[i] == 0)
308 return NULL;
310 return (char*) str;
313 int utf8_to_ascii(const char *str, char replacement_char, char **ret) {
314 /* Convert to a string that has only ASCII chars, replacing anything that is not ASCII
315 * by replacement_char. */
317 _cleanup_free_ char *ans = new(char, strlen(str) + 1);
318 if (!ans)
319 return -ENOMEM;
321 char *q = ans;
323 for (const char *p = str; *p; q++) {
324 int l;
326 l = utf8_encoded_valid_unichar(p, SIZE_MAX);
327 if (l < 0) /* Non-UTF-8, let's not even try to propagate the garbage */
328 return l;
330 if (l == 1)
331 *q = *p;
332 else
333 /* non-ASCII, we need to replace it */
334 *q = replacement_char;
336 p += l;
338 *q = '\0';
340 *ret = TAKE_PTR(ans);
341 return 0;
345 * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
346 * @out_utf8: output buffer of at least 4 bytes or NULL
347 * @g: UCS-4 character to encode
349 * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
350 * The length of the character is returned. It is not zero-terminated! If the
351 * output buffer is NULL, only the length is returned.
353 * Returns: The length in bytes that the UTF-8 representation does or would
354 * occupy.
356 size_t utf8_encode_unichar(char *out_utf8, char32_t g) {
358 if (g < (1 << 7)) {
359 if (out_utf8)
360 out_utf8[0] = g & 0x7f;
361 return 1;
362 } else if (g < (1 << 11)) {
363 if (out_utf8) {
364 out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f);
365 out_utf8[1] = 0x80 | (g & 0x3f);
367 return 2;
368 } else if (g < (1 << 16)) {
369 if (out_utf8) {
370 out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f);
371 out_utf8[1] = 0x80 | ((g >> 6) & 0x3f);
372 out_utf8[2] = 0x80 | (g & 0x3f);
374 return 3;
375 } else if (g < (1 << 21)) {
376 if (out_utf8) {
377 out_utf8[0] = 0xf0 | ((g >> 18) & 0x07);
378 out_utf8[1] = 0x80 | ((g >> 12) & 0x3f);
379 out_utf8[2] = 0x80 | ((g >> 6) & 0x3f);
380 out_utf8[3] = 0x80 | (g & 0x3f);
382 return 4;
385 return 0;
388 char *utf16_to_utf8(const char16_t *s, size_t length /* bytes! */) {
389 const uint8_t *f;
390 char *r, *t;
392 assert(s);
394 /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may
395 * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */
396 if (length * 2 < length)
397 return NULL; /* overflow */
399 r = new(char, length * 2 + 1);
400 if (!r)
401 return NULL;
403 f = (const uint8_t*) s;
404 t = r;
406 while (f + 1 < (const uint8_t*) s + length) {
407 char16_t w1, w2;
409 /* see RFC 2781 section 2.2 */
411 w1 = f[1] << 8 | f[0];
412 f += 2;
414 if (!utf16_is_surrogate(w1)) {
415 t += utf8_encode_unichar(t, w1);
416 continue;
419 if (utf16_is_trailing_surrogate(w1))
420 continue; /* spurious trailing surrogate, ignore */
422 if (f + 1 >= (const uint8_t*) s + length)
423 break;
425 w2 = f[1] << 8 | f[0];
426 f += 2;
428 if (!utf16_is_trailing_surrogate(w2)) {
429 f -= 2;
430 continue; /* surrogate missing its trailing surrogate, ignore */
433 t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2));
436 *t = 0;
437 return r;
440 size_t utf16_encode_unichar(char16_t *out, char32_t c) {
442 /* Note that this encodes as little-endian. */
444 switch (c) {
446 case 0 ... 0xd7ffU:
447 case 0xe000U ... 0xffffU:
448 out[0] = htole16(c);
449 return 1;
451 case 0x10000U ... 0x10ffffU:
452 c -= 0x10000U;
453 out[0] = htole16((c >> 10) + 0xd800U);
454 out[1] = htole16((c & 0x3ffU) + 0xdc00U);
455 return 2;
457 default: /* A surrogate (invalid) */
458 return 0;
462 char16_t *utf8_to_utf16(const char *s, size_t length) {
463 char16_t *n, *p;
464 int r;
466 assert(s);
468 n = new(char16_t, length + 1);
469 if (!n)
470 return NULL;
472 p = n;
474 for (size_t i = 0; i < length;) {
475 char32_t unichar;
476 size_t e;
478 e = utf8_encoded_expected_len(s[i]);
479 if (e <= 1) /* Invalid and single byte characters are copied as they are */
480 goto copy;
482 if (i + e > length) /* sequence longer than input buffer, then copy as-is */
483 goto copy;
485 r = utf8_encoded_to_unichar(s + i, &unichar);
486 if (r < 0) /* sequence invalid, then copy as-is */
487 goto copy;
489 p += utf16_encode_unichar(p, unichar);
490 i += e;
491 continue;
493 copy:
494 *(p++) = htole16(s[i++]);
497 *p = 0;
498 return n;
501 size_t char16_strlen(const char16_t *s) {
502 size_t n = 0;
504 assert(s);
506 while (*s != 0)
507 n++, s++;
509 return n;
512 /* expected size used to encode one unicode char */
513 static int utf8_unichar_to_encoded_len(char32_t unichar) {
515 if (unichar < 0x80)
516 return 1;
517 if (unichar < 0x800)
518 return 2;
519 if (unichar < 0x10000)
520 return 3;
521 if (unichar < 0x200000)
522 return 4;
523 if (unichar < 0x4000000)
524 return 5;
526 return 6;
529 /* validate one encoded unicode char and return its length */
530 int utf8_encoded_valid_unichar(const char *str, size_t length /* bytes */) {
531 char32_t unichar;
532 size_t len;
533 int r;
535 assert(str);
536 assert(length > 0);
538 /* We read until NUL, at most length bytes. SIZE_MAX may be used to disable the length check. */
540 len = utf8_encoded_expected_len(str[0]);
541 if (len == 0)
542 return -EINVAL;
544 /* Do we have a truncated multi-byte character? */
545 if (len > length)
546 return -EINVAL;
548 /* ascii is valid */
549 if (len == 1)
550 return 1;
552 /* check if expected encoded chars are available */
553 for (size_t i = 0; i < len; i++)
554 if ((str[i] & 0x80) != 0x80)
555 return -EINVAL;
557 r = utf8_encoded_to_unichar(str, &unichar);
558 if (r < 0)
559 return r;
561 /* check if encoded length matches encoded value */
562 if (utf8_unichar_to_encoded_len(unichar) != (int) len)
563 return -EINVAL;
565 /* check if value has valid range */
566 if (!unichar_is_valid(unichar))
567 return -EINVAL;
569 return (int) len;
572 size_t utf8_n_codepoints(const char *str) {
573 size_t n = 0;
575 /* Returns the number of UTF-8 codepoints in this string, or SIZE_MAX if the string is not valid UTF-8. */
577 while (*str != 0) {
578 int k;
580 k = utf8_encoded_valid_unichar(str, SIZE_MAX);
581 if (k < 0)
582 return SIZE_MAX;
584 str += k;
585 n++;
588 return n;
591 size_t utf8_console_width(const char *str) {
592 size_t n = 0;
594 /* Returns the approximate width a string will take on screen when printed on a character cell
595 * terminal/console. */
597 while (*str) {
598 int w;
600 w = utf8_char_console_width(str);
601 if (w < 0)
602 return SIZE_MAX;
604 n += w;
605 str = utf8_next_char(str);
608 return n;