1
0
mirror of https://github.com/systemd/systemd synced 2024-07-01 07:34:28 +00:00

basic/utf8: modernize utf8_is_valid_n a bit

This commit is contained in:
Mike Yuan 2024-05-09 21:55:09 +08:00
parent d4d90ef900
commit 7ff7161044
No known key found for this signature in database
GPG Key ID: 417471C0A40F58B3
2 changed files with 9 additions and 9 deletions

View File

@ -130,24 +130,24 @@ bool utf8_is_printable_newline(const char* str, size_t length, bool allow_newlin
return true;
}
char *utf8_is_valid_n(const char *str, size_t len_bytes) {
char* utf8_is_valid_n(const char *str, size_t len_bytes) {
/* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after
* len_bytes. Otherwise, stop at NUL. */
assert(str);
for (const char *p = str; len_bytes != SIZE_MAX ? (size_t) (p - str) < len_bytes : *p != '\0'; ) {
for (size_t i = 0; len_bytes != SIZE_MAX ? i < len_bytes : str[i] != '\0'; ) {
int len;
if (_unlikely_(*p == '\0') && len_bytes != SIZE_MAX)
if (_unlikely_(str[i] == '\0'))
return NULL; /* embedded NUL */
len = utf8_encoded_valid_unichar(p,
len_bytes != SIZE_MAX ? len_bytes - (p - str) : SIZE_MAX);
len = utf8_encoded_valid_unichar(str + i,
len_bytes != SIZE_MAX ? len_bytes - i : SIZE_MAX);
if (_unlikely_(len < 0))
return NULL; /* invalid character */
p += len;
i += len;
}
return (char*) str;

View File

@ -14,9 +14,9 @@
bool unichar_is_valid(char32_t c);
char *utf8_is_valid_n(const char *str, size_t len_bytes) _pure_;
static inline char *utf8_is_valid(const char *s) {
return utf8_is_valid_n(s, SIZE_MAX);
char* utf8_is_valid_n(const char *str, size_t len_bytes) _pure_;
static inline char* utf8_is_valid(const char *str) {
return utf8_is_valid_n(str, SIZE_MAX);
}
char *ascii_is_valid(const char *s) _pure_;
char *ascii_is_valid_n(const char *str, size_t len);