From: Lennart Poettering Date: Wed, 11 Apr 2018 17:50:53 +0000 (+0200) Subject: utf8: add helper call for counting display width of strings X-Git-Tag: v239~393^2~9 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=3f536d5baeb28ac96f4e18151c1452d9d2f76826;p=thirdparty%2Fsystemd.git utf8: add helper call for counting display width of strings --- diff --git a/src/basic/utf8.c b/src/basic/utf8.c index 0dc76eba21d..670a98a6a9c 100644 --- a/src/basic/utf8.c +++ b/src/basic/utf8.c @@ -35,6 +35,7 @@ #include #include "alloc-util.h" +#include "gunicode.h" #include "hexdecoct.h" #include "macro.h" #include "utf8.h" @@ -414,3 +415,23 @@ size_t utf8_n_codepoints(const char *str) { return n; } + +size_t utf8_console_width(const char *str) { + size_t n = 0; + + /* Returns the approximate width a string will take on screen when printed on a character cell + * terminal/console. */ + + while (*str != 0) { + char32_t c; + + if (utf8_encoded_to_unichar(str, &c) < 0) + return (size_t) -1; + + str = utf8_next_char(str); + + n += unichar_iswide(c) ? 2 : 1; + } + + return n; +} diff --git a/src/basic/utf8.h b/src/basic/utf8.h index c3a7d7b96c8..7d68105a085 100644 --- a/src/basic/utf8.h +++ b/src/basic/utf8.h @@ -48,3 +48,4 @@ static inline char32_t utf16_surrogate_pair_to_unichar(char16_t lead, char16_t t } size_t utf8_n_codepoints(const char *str); +size_t utf8_console_width(const char *str);