1 /* SPDX-License-Identifier: LGPL-2.0-or-later */
3 /* Parts of this file are based on the GLIB utf8 validation functions. The original copyright follows.
5 * gutf8.c - Operations on UTF-8 strings.
6 * Copyright (C) 1999 Tom Tromey
7 * Copyright (C) 2000 Red Hat, Inc.
10 #include "alloc-util.h"
12 #include "hexdecoct.h"
13 #include "string-util.h"
16 bool unichar_is_valid(char32_t ch
) {
18 if (ch
>= 0x110000) /* End of unicode space */
20 if ((ch
& 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
22 if ((ch
>= 0xFDD0) && (ch
<= 0xFDEF)) /* Reserved */
24 if ((ch
& 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
30 static bool unichar_is_control(char32_t ch
) {
33 0 to ' '-1 is the C0 range.
34 DEL=0x7F, and DEL+1 to 0x9F is C1 range.
35 '\t' is in C0 range, but more or less harmless and commonly used.
38 return (ch
< ' ' && !IN_SET(ch
, '\t', '\n')) ||
39 (0x7F <= ch
&& ch
<= 0x9F);
42 /* count of characters used to encode one unicode char */
43 static size_t utf8_encoded_expected_len(uint8_t c
) {
46 if ((c
& 0xe0) == 0xc0)
48 if ((c
& 0xf0) == 0xe0)
50 if ((c
& 0xf8) == 0xf0)
52 if ((c
& 0xfc) == 0xf8)
54 if ((c
& 0xfe) == 0xfc)
60 /* decode one unicode char */
61 int utf8_encoded_to_unichar(const char *str
, char32_t *ret_unichar
) {
68 len
= utf8_encoded_expected_len(str
[0]);
72 *ret_unichar
= (char32_t)str
[0];
75 unichar
= str
[0] & 0x1f;
78 unichar
= (char32_t)str
[0] & 0x0f;
81 unichar
= (char32_t)str
[0] & 0x07;
84 unichar
= (char32_t)str
[0] & 0x03;
87 unichar
= (char32_t)str
[0] & 0x01;
93 for (size_t i
= 1; i
< len
; i
++) {
94 if (((char32_t)str
[i
] & 0xc0) != 0x80)
98 unichar
|= (char32_t)str
[i
] & 0x3f;
101 *ret_unichar
= unichar
;
105 bool utf8_is_printable_newline(const char* str
, size_t length
, bool allow_newline
) {
108 for (const char *p
= str
; length
> 0;) {
112 encoded_len
= utf8_encoded_valid_unichar(p
, length
);
115 assert(encoded_len
> 0 && (size_t) encoded_len
<= length
);
117 if (utf8_encoded_to_unichar(p
, &val
) < 0 ||
118 unichar_is_control(val
) ||
119 (!allow_newline
&& val
== '\n'))
122 length
-= encoded_len
;
129 char* utf8_is_valid_n(const char *str
, size_t len_bytes
) {
130 /* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after
131 * len_bytes. Otherwise, stop at NUL. */
135 for (size_t i
= 0; len_bytes
!= SIZE_MAX
? i
< len_bytes
: str
[i
] != '\0'; ) {
138 if (_unlikely_(str
[i
] == '\0'))
139 return NULL
; /* embedded NUL */
141 len
= utf8_encoded_valid_unichar(str
+ i
,
142 len_bytes
!= SIZE_MAX
? len_bytes
- i
: SIZE_MAX
);
143 if (_unlikely_(len
< 0))
144 return NULL
; /* invalid character */
152 char* utf8_escape_invalid(const char *str
) {
157 p
= s
= malloc(strlen(str
) * 4 + 1);
164 len
= utf8_encoded_valid_unichar(str
, SIZE_MAX
);
166 s
= mempcpy(s
, str
, len
);
169 s
= stpcpy(s
, UTF8_REPLACEMENT_CHARACTER
);
175 return str_realloc(p
);
178 int utf8_char_console_width(const char *str
) {
184 r
= utf8_encoded_to_unichar(str
, &c
);
188 return unichar_console_width(c
);
191 int unichar_console_width(char32_t c
) {
193 return 8; /* Assume a tab width of 8 */
195 /* TODO: we should detect combining characters */
197 return unichar_iswide(c
) ? 2 : 1;
200 char* utf8_escape_non_printable_full(const char *str
, size_t console_width
, bool force_ellipsis
) {
201 char *p
, *s
, *prev_s
;
202 size_t n
= 0; /* estimated print width */
206 if (console_width
== 0)
209 size_t body
= strlen(str
) * 4;
210 p
= s
= prev_s
= malloc(body
+ STRLEN("…") + 1);
218 if (!*str
) { /* done! */
225 len
= utf8_encoded_valid_unichar(str
, SIZE_MAX
);
227 if (utf8_is_printable(str
, len
)) {
230 w
= utf8_char_console_width(str
);
232 if (n
+ w
> console_width
)
235 s
= mempcpy(s
, str
, len
);
240 for (; len
> 0; len
--) {
241 if (n
+ 4 > console_width
)
246 *(s
++) = hexchar((int) *str
>> 4);
247 *(s
++) = hexchar((int) *str
);
254 if (n
+ 1 > console_width
)
257 s
= mempcpy(s
, UTF8_REPLACEMENT_CHARACTER
, strlen(UTF8_REPLACEMENT_CHARACTER
));
266 /* Try to go back one if we don't have enough space for the ellipsis */
267 if (n
+ 1 > console_width
)
270 s
= mempcpy(s
, "…", strlen("…"));
274 return str_realloc(p
);
277 char* ascii_is_valid_n(const char *str
, size_t len
) {
278 /* Check whether the string consists of valid ASCII bytes, i.e values between 1 and 127, inclusive.
279 * Stops at len, or NUL byte if len is SIZE_MAX. */
283 for (size_t i
= 0; len
!= SIZE_MAX
? i
< len
: str
[i
] != '\0'; i
++)
284 if ((unsigned char) str
[i
] >= 128 || str
[i
] == '\0')
290 int utf8_to_ascii(const char *str
, char replacement_char
, char **ret
) {
291 /* Convert to a string that has only ASCII chars, replacing anything that is not ASCII
292 * by replacement_char. */
297 _cleanup_free_
char *ans
= new(char, strlen(str
) + 1);
303 for (const char *p
= str
; *p
; q
++) {
306 l
= utf8_encoded_valid_unichar(p
, SIZE_MAX
);
307 if (l
< 0) /* Non-UTF-8, let's not even try to propagate the garbage */
313 /* non-ASCII, we need to replace it */
314 *q
= replacement_char
;
320 *ret
= TAKE_PTR(ans
);
325 * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
326 * @out_utf8: output buffer of at least 4 bytes or NULL
327 * @g: UCS-4 character to encode
329 * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
330 * The length of the character is returned. It is not zero-terminated! If the
331 * output buffer is NULL, only the length is returned.
333 * Returns: The length in bytes that the UTF-8 representation does or would
336 size_t utf8_encode_unichar(char *out_utf8
, char32_t g
) {
340 out_utf8
[0] = g
& 0x7f;
342 } else if (g
< (1 << 11)) {
344 out_utf8
[0] = 0xc0 | ((g
>> 6) & 0x1f);
345 out_utf8
[1] = 0x80 | (g
& 0x3f);
348 } else if (g
< (1 << 16)) {
350 out_utf8
[0] = 0xe0 | ((g
>> 12) & 0x0f);
351 out_utf8
[1] = 0x80 | ((g
>> 6) & 0x3f);
352 out_utf8
[2] = 0x80 | (g
& 0x3f);
355 } else if (g
< (1 << 21)) {
357 out_utf8
[0] = 0xf0 | ((g
>> 18) & 0x07);
358 out_utf8
[1] = 0x80 | ((g
>> 12) & 0x3f);
359 out_utf8
[2] = 0x80 | ((g
>> 6) & 0x3f);
360 out_utf8
[3] = 0x80 | (g
& 0x3f);
368 char* utf16_to_utf8(const char16_t *s
, size_t length
/* bytes! */) {
373 return new0(char, 1);
377 if (length
== SIZE_MAX
) {
378 length
= char16_strlen(s
);
380 if (length
> SIZE_MAX
/2)
381 return NULL
; /* overflow */
386 /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may
387 * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */
388 if (length
> (SIZE_MAX
- 1) / 2)
389 return NULL
; /* overflow */
391 r
= new(char, length
* 2 + 1);
395 f
= (const uint8_t*) s
;
398 while (f
+ 1 < (const uint8_t*) s
+ length
) {
401 /* see RFC 2781 section 2.2 */
403 w1
= f
[1] << 8 | f
[0];
406 if (!utf16_is_surrogate(w1
)) {
407 t
+= utf8_encode_unichar(t
, w1
);
411 if (utf16_is_trailing_surrogate(w1
))
412 continue; /* spurious trailing surrogate, ignore */
414 if (f
+ 1 >= (const uint8_t*) s
+ length
)
417 w2
= f
[1] << 8 | f
[0];
420 if (!utf16_is_trailing_surrogate(w2
)) {
422 continue; /* surrogate missing its trailing surrogate, ignore */
425 t
+= utf8_encode_unichar(t
, utf16_surrogate_pair_to_unichar(w1
, w2
));
432 size_t utf16_encode_unichar(char16_t *out
, char32_t c
) {
435 /* Note that this encodes as little-endian. */
440 case 0xe000U
... 0xffffU
:
444 case 0x10000U
... 0x10ffffU
:
446 out
[0] = htole16((c
>> 10) + 0xd800U
);
447 out
[1] = htole16((c
& 0x3ffU
) + 0xdc00U
);
450 default: /* A surrogate (invalid) */
455 char16_t *utf8_to_utf16(const char *s
, size_t length
) {
460 return new0(char16_t, 1);
464 if (length
== SIZE_MAX
)
467 if (length
> SIZE_MAX
- 1)
468 return NULL
; /* overflow */
470 n
= new(char16_t, length
+ 1);
476 for (size_t i
= 0; i
< length
;) {
480 e
= utf8_encoded_expected_len(s
[i
]);
481 if (e
<= 1) /* Invalid and single byte characters are copied as they are */
484 if (i
+ e
> length
) /* sequence longer than input buffer, then copy as-is */
487 r
= utf8_encoded_to_unichar(s
+ i
, &unichar
);
488 if (r
< 0) /* sequence invalid, then copy as-is */
491 p
+= utf16_encode_unichar(p
, unichar
);
496 *(p
++) = htole16(s
[i
++]);
503 size_t char16_strlen(const char16_t *s
) {
514 size_t char16_strsize(const char16_t *s
) {
515 POINTER_MAY_BE_NULL(s
);
517 return s
? (char16_strlen(s
) + 1) * sizeof(*s
) : 0;
520 /* expected size used to encode one unicode char */
521 static int utf8_unichar_to_encoded_len(char32_t unichar
) {
527 if (unichar
< 0x10000)
529 if (unichar
< 0x200000)
531 if (unichar
< 0x4000000)
537 /* validate one encoded unicode char and return its length */
538 int utf8_encoded_valid_unichar(const char *str
, size_t length
/* bytes */) {
546 /* We read until NUL, at most length bytes. SIZE_MAX may be used to disable the length check. */
548 len
= utf8_encoded_expected_len(str
[0]);
552 /* Do we have a truncated multi-byte character? */
560 /* check if expected encoded chars are available */
561 for (size_t i
= 0; i
< len
; i
++)
562 if ((str
[i
] & 0x80) != 0x80)
565 r
= utf8_encoded_to_unichar(str
, &unichar
);
569 /* check if encoded length matches encoded value */
570 if (utf8_unichar_to_encoded_len(unichar
) != (int) len
)
573 /* check if value has valid range */
574 if (!unichar_is_valid(unichar
))
580 size_t utf8_n_codepoints(const char *str
) {
585 /* Returns the number of UTF-8 codepoints in this string, or SIZE_MAX if the string is not valid UTF-8. */
590 k
= utf8_encoded_valid_unichar(str
, SIZE_MAX
);
601 size_t utf8_console_width(const char *str
) {
602 POINTER_MAY_BE_NULL(str
);
607 /* Returns the approximate width a string will take on screen when printed on a character cell
608 * terminal/console. */
614 w
= utf8_char_console_width(str
);
619 str
= utf8_next_char(str
);
625 size_t utf8_last_length(const char *s
, size_t n
) {
633 /* Determines length in bytes of last UTF-8 codepoint in string. If the string is empty, returns
634 * zero. Treats invalid UTF-8 codepoints as 1 sized ones. */
636 for (size_t last
= 0;;) {
640 r
= utf8_encoded_valid_unichar(s
, n
);
642 r
= 1; /* treat invalid UTF-8 as byte-wide */