Skip to content

Commit 8a9391e

Browse files
geofftgitster
authored andcommitted
utf8: add utf8_strwidth()
I'm about to use this pattern more than once, so make it a common function. Signed-off-by: Geoffrey Thomas <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent b296e8f commit 8a9391e

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

utf8.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,25 @@ int utf8_width(const char **start, size_t *remainder_p)
246246
return git_wcwidth(ch);
247247
}
248248

249+
/*
250+
* Returns the total number of columns required by a null-terminated
251+
* string, assuming that the string is utf8. Returns strlen() instead
252+
* if the string does not look like a valid utf8 string.
253+
*/
254+
int utf8_strwidth(const char *string)
255+
{
256+
int width = 0;
257+
const char *orig = string;
258+
259+
while (1) {
260+
if (!string)
261+
return strlen(orig);
262+
if (!*string)
263+
return width;
264+
width += utf8_width(&string, NULL);
265+
}
266+
}
267+
249268
int is_utf8(const char *text)
250269
{
251270
while (*text) {

utf8.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ typedef unsigned int ucs_char_t; /* assuming 32bit int */
55

66
ucs_char_t pick_one_utf8_char(const char **start, size_t *remainder_p);
77
int utf8_width(const char **start, size_t *remainder_p);
8+
int utf8_strwidth(const char *string);
89
int is_utf8(const char *text);
910
int is_encoding_utf8(const char *name);
1011

0 commit comments

Comments
 (0)