1 /* SPDX-License-Identifier: LGPL-2.1+ */
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
30 #include "alloc-util.h"
32 #include "hexdecoct.h"
34 #include "string-util.h"
37 bool unichar_is_valid(char32_t ch
) {
39 if (ch
>= 0x110000) /* End of unicode space */
41 if ((ch
& 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */
43 if ((ch
>= 0xFDD0) && (ch
<= 0xFDEF)) /* Reserved */
45 if ((ch
& 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */
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
) {
67 if ((c
& 0xe0) == 0xc0)
69 if ((c
& 0xf0) == 0xe0)
71 if ((c
& 0xf8) == 0xf0)
73 if ((c
& 0xfc) == 0xf8)
75 if ((c
& 0xfe) == 0xfc)
81 /* decode one unicode char */
82 int utf8_encoded_to_unichar(const char *str
, char32_t
*ret_unichar
) {
88 len
= utf8_encoded_expected_len(str
[0]);
92 *ret_unichar
= (char32_t
)str
[0];
95 unichar
= str
[0] & 0x1f;
98 unichar
= (char32_t
)str
[0] & 0x0f;
101 unichar
= (char32_t
)str
[0] & 0x07;
104 unichar
= (char32_t
)str
[0] & 0x03;
107 unichar
= (char32_t
)str
[0] & 0x01;
113 for (i
= 1; i
< len
; i
++) {
114 if (((char32_t
)str
[i
] & 0xc0) != 0x80)
118 unichar
|= (char32_t
)str
[i
] & 0x3f;
121 *ret_unichar
= unichar
;
126 bool utf8_is_printable_newline(const char* str
, size_t length
, bool allow_newline
) {
131 for (p
= str
; length
> 0;) {
135 encoded_len
= utf8_encoded_valid_unichar(p
, length
);
138 assert(encoded_len
> 0 && (size_t) encoded_len
<= length
);
140 r
= utf8_encoded_to_unichar(p
, &val
);
142 unichar_is_control(val
) ||
143 (!allow_newline
&& val
== '\n'))
146 length
-= encoded_len
;
153 char *utf8_is_valid_n(const char *str
, size_t len_bytes
) {
154 /* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after
155 * len_bytes. Otherwise, stop at NUL. */
159 for (const char *p
= str
; len_bytes
!= (size_t) -1 ? (size_t) (p
- str
) < len_bytes
: *p
!= '\0'; ) {
162 if (_unlikely_(*p
== '\0') && len_bytes
!= (size_t) -1)
163 return NULL
; /* embedded NUL */
165 len
= utf8_encoded_valid_unichar(p
,
166 len_bytes
!= (size_t) -1 ? len_bytes
- (p
- str
) : (size_t) -1);
167 if (_unlikely_(len
< 0))
168 return NULL
; /* invalid character */
176 char *utf8_escape_invalid(const char *str
) {
181 p
= s
= malloc(strlen(str
) * 4 + 1);
188 len
= utf8_encoded_valid_unichar(str
, (size_t) -1);
190 s
= mempcpy(s
, str
, len
);
193 s
= stpcpy(s
, UTF8_REPLACEMENT_CHARACTER
);
199 (void) str_realloc(&p
);
203 static int utf8_char_console_width(const char *str
) {
207 r
= utf8_encoded_to_unichar(str
, &c
);
211 /* TODO: we should detect combining characters */
213 return unichar_iswide(c
) ? 2 : 1;
216 char *utf8_escape_non_printable_full(const char *str
, size_t console_width
) {
217 char *p
, *s
, *prev_s
;
218 size_t n
= 0; /* estimated print width */
222 if (console_width
== 0)
225 p
= s
= prev_s
= malloc(strlen(str
) * 4 + 1);
233 if (!*str
) /* done! */
236 len
= utf8_encoded_valid_unichar(str
, (size_t) -1);
238 if (utf8_is_printable(str
, len
)) {
241 w
= utf8_char_console_width(str
);
243 if (n
+ w
> console_width
)
246 s
= mempcpy(s
, str
, len
);
251 for (; len
> 0; len
--) {
252 if (n
+ 4 > console_width
)
257 *(s
++) = hexchar((int) *str
>> 4);
258 *(s
++) = hexchar((int) *str
);
265 if (n
+ 1 > console_width
)
268 s
= mempcpy(s
, UTF8_REPLACEMENT_CHARACTER
, strlen(UTF8_REPLACEMENT_CHARACTER
));
277 /* Try to go back one if we don't have enough space for the ellipsis */
278 if (n
+ 1 >= console_width
)
281 s
= mempcpy(s
, "…", strlen("…"));
285 (void) str_realloc(&p
);
289 char *ascii_is_valid(const char *str
) {
292 /* Check whether the string consists of valid ASCII bytes,
293 * i.e values between 0 and 127, inclusive. */
297 for (p
= str
; *p
; p
++)
298 if ((unsigned char) *p
>= 128)
304 char *ascii_is_valid_n(const char *str
, size_t len
) {
307 /* Very similar to ascii_is_valid(), but checks exactly len
308 * bytes and rejects any NULs in that range. */
312 for (i
= 0; i
< len
; i
++)
313 if ((unsigned char) str
[i
] >= 128 || str
[i
] == 0)
320 * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
321 * @out_utf8: output buffer of at least 4 bytes or NULL
322 * @g: UCS-4 character to encode
324 * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8.
325 * The length of the character is returned. It is not zero-terminated! If the
326 * output buffer is NULL, only the length is returned.
328 * Returns: The length in bytes that the UTF-8 representation does or would
331 size_t utf8_encode_unichar(char *out_utf8
, char32_t g
) {
335 out_utf8
[0] = g
& 0x7f;
337 } else if (g
< (1 << 11)) {
339 out_utf8
[0] = 0xc0 | ((g
>> 6) & 0x1f);
340 out_utf8
[1] = 0x80 | (g
& 0x3f);
343 } else if (g
< (1 << 16)) {
345 out_utf8
[0] = 0xe0 | ((g
>> 12) & 0x0f);
346 out_utf8
[1] = 0x80 | ((g
>> 6) & 0x3f);
347 out_utf8
[2] = 0x80 | (g
& 0x3f);
350 } else if (g
< (1 << 21)) {
352 out_utf8
[0] = 0xf0 | ((g
>> 18) & 0x07);
353 out_utf8
[1] = 0x80 | ((g
>> 12) & 0x3f);
354 out_utf8
[2] = 0x80 | ((g
>> 6) & 0x3f);
355 out_utf8
[3] = 0x80 | (g
& 0x3f);
363 char *utf16_to_utf8(const char16_t
*s
, size_t length
/* bytes! */) {
369 /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may
370 * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */
371 if (length
* 2 < length
)
372 return NULL
; /* overflow */
374 r
= new(char, length
* 2 + 1);
378 f
= (const uint8_t*) s
;
381 while (f
+ 1 < (const uint8_t*) s
+ length
) {
384 /* see RFC 2781 section 2.2 */
386 w1
= f
[1] << 8 | f
[0];
389 if (!utf16_is_surrogate(w1
)) {
390 t
+= utf8_encode_unichar(t
, w1
);
394 if (utf16_is_trailing_surrogate(w1
))
395 continue; /* spurious trailing surrogate, ignore */
397 if (f
+ 1 >= (const uint8_t*) s
+ length
)
400 w2
= f
[1] << 8 | f
[0];
403 if (!utf16_is_trailing_surrogate(w2
)) {
405 continue; /* surrogate missing its trailing surrogate, ignore */
408 t
+= utf8_encode_unichar(t
, utf16_surrogate_pair_to_unichar(w1
, w2
));
415 size_t utf16_encode_unichar(char16_t
*out
, char32_t c
) {
417 /* Note that this encodes as little-endian. */
422 case 0xe000U
... 0xffffU
:
426 case 0x10000U
... 0x10ffffU
:
428 out
[0] = htole16((c
>> 10) + 0xd800U
);
429 out
[1] = htole16((c
& 0x3ffU
) + 0xdc00U
);
432 default: /* A surrogate (invalid) */
437 char16_t
*utf8_to_utf16(const char *s
, size_t length
) {
444 n
= new(char16_t
, length
+ 1);
450 for (i
= 0; i
< length
;) {
454 e
= utf8_encoded_expected_len(s
[i
]);
455 if (e
<= 1) /* Invalid and single byte characters are copied as they are */
458 if (i
+ e
> length
) /* sequence longer than input buffer, then copy as-is */
461 r
= utf8_encoded_to_unichar(s
+ i
, &unichar
);
462 if (r
< 0) /* sequence invalid, then copy as-is */
465 p
+= utf16_encode_unichar(p
, unichar
);
470 *(p
++) = htole16(s
[i
++]);
477 size_t char16_strlen(const char16_t
*s
) {
488 /* expected size used to encode one unicode char */
489 static int utf8_unichar_to_encoded_len(char32_t unichar
) {
495 if (unichar
< 0x10000)
497 if (unichar
< 0x200000)
499 if (unichar
< 0x4000000)
505 /* validate one encoded unicode char and return its length */
506 int utf8_encoded_valid_unichar(const char *str
, size_t length
/* bytes */) {
514 /* We read until NUL, at most length bytes. (size_t) -1 may be used to disable the length check. */
516 len
= utf8_encoded_expected_len(str
[0]);
520 /* Do we have a truncated multi-byte character? */
528 /* check if expected encoded chars are available */
529 for (i
= 0; i
< len
; i
++)
530 if ((str
[i
] & 0x80) != 0x80)
533 r
= utf8_encoded_to_unichar(str
, &unichar
);
537 /* check if encoded length matches encoded value */
538 if (utf8_unichar_to_encoded_len(unichar
) != (int) len
)
541 /* check if value has valid range */
542 if (!unichar_is_valid(unichar
))
548 size_t utf8_n_codepoints(const char *str
) {
551 /* Returns the number of UTF-8 codepoints in this string, or (size_t) -1 if the string is not valid UTF-8. */
556 k
= utf8_encoded_valid_unichar(str
, (size_t) -1);
567 size_t utf8_console_width(const char *str
) {
570 /* Returns the approximate width a string will take on screen when printed on a character cell
571 * terminal/console. */
576 w
= utf8_char_console_width(str
);
581 str
= utf8_next_char(str
);