diff options
author | Lennart Poettering <lennart@poettering.net> | 2018-02-14 18:41:03 +0100 |
---|---|---|
committer | Sven Eden <yamakuzure@gmx.net> | 2018-05-30 07:58:56 +0200 |
commit | 69efcf51adbe0382c11d83d04e14279fe010d2b2 (patch) | |
tree | 677a32a254ff26140649520f9c4dfa55b5c68442 | |
parent | 18344601acc263daef6008a4a0f2e8791fd20db7 (diff) |
utf8: add utf8_n_codepoints() for counting complete utf8 codepoints in a string
-rw-r--r-- | src/basic/utf8.c | 19 | ||||
-rw-r--r-- | src/basic/utf8.h | 2 |
2 files changed, 21 insertions, 0 deletions
diff --git a/src/basic/utf8.c b/src/basic/utf8.c index 4da9a405c..b17f42026 100644 --- a/src/basic/utf8.c +++ b/src/basic/utf8.c @@ -408,3 +408,22 @@ int utf8_encoded_valid_unichar(const char *str) { return len; } + +size_t utf8_n_codepoints(const char *str) { + size_t n = 0; + + /* Returns the number of UTF-8 codepoints in this string, or (size_t) -1 if the string is not valid UTF-8. */ + + while (*str != 0) { + int k; + + k = utf8_encoded_valid_unichar(str); + if (k < 0) + return (size_t) -1; + + str += k; + n++; + } + + return n; +} diff --git a/src/basic/utf8.h b/src/basic/utf8.h index b0a7485ae..712861518 100644 --- a/src/basic/utf8.h +++ b/src/basic/utf8.h @@ -59,3 +59,5 @@ static inline bool utf16_is_trailing_surrogate(char16_t c) { static inline char32_t utf16_surrogate_pair_to_unichar(char16_t lead, char16_t trail) { return ((lead - 0xd800) << 10) + (trail - 0xdc00) + 0x10000; } + +size_t utf8_n_codepoints(const char *str); |