Skip to content

Commit 3f536d5

Browse files
committed
utf8: add helper call for counting display width of strings
1 parent b77f5e2 commit 3f536d5

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/basic/utf8.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
#include <string.h>
3636

3737
#include "alloc-util.h"
38+
#include "gunicode.h"
3839
#include "hexdecoct.h"
3940
#include "macro.h"
4041
#include "utf8.h"
@@ -414,3 +415,23 @@ size_t utf8_n_codepoints(const char *str) {
414415

415416
return n;
416417
}
418+
419+
size_t utf8_console_width(const char *str) {
420+
size_t n = 0;
421+
422+
/* Returns the approximate width a string will take on screen when printed on a character cell
423+
* terminal/console. */
424+
425+
while (*str != 0) {
426+
char32_t c;
427+
428+
if (utf8_encoded_to_unichar(str, &c) < 0)
429+
return (size_t) -1;
430+
431+
str = utf8_next_char(str);
432+
433+
n += unichar_iswide(c) ? 2 : 1;
434+
}
435+
436+
return n;
437+
}

src/basic/utf8.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,4 @@ static inline char32_t utf16_surrogate_pair_to_unichar(char16_t lead, char16_t t
4848
}
4949

5050
size_t utf8_n_codepoints(const char *str);
51+
size_t utf8_console_width(const char *str);

0 commit comments

Comments
 (0)