utf8: add utf8_strwidth()
authorGeoffrey Thomas <geofft@mit.edu>
Fri, 30 Jan 2009 09:41:28 +0000 (04:41 -0500)
committerJunio C Hamano <gitster@pobox.com>
Thu, 5 Feb 2009 00:30:43 +0000 (16:30 -0800)
I'm about to use this pattern more than once, so make it a common function.

Signed-off-by: Geoffrey Thomas <geofft@mit.edu>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
utf8.c
utf8.h
diff --git a/utf8.c b/utf8.c
index dc3735364f85273c2a119b994ddb405c09dc395c..ddfdc5e2b88d346886f64e39a93ced85cc10a78e 100644 (file)
--- a/utf8.c
+++ b/utf8.c
@@ -246,6 +246,25 @@ int utf8_width(const char **start, size_t *remainder_p)
        return git_wcwidth(ch);
 }
 
+/*
+ * Returns the total number of columns required by a null-terminated
+ * string, assuming that the string is utf8.  Returns strlen() instead
+ * if the string does not look like a valid utf8 string.
+ */
+int utf8_strwidth(const char *string)
+{
+       int width = 0;
+       const char *orig = string;
+
+       while (1) {
+               if (!string)
+                       return strlen(orig);
+               if (!*string)
+                       return width;
+               width += utf8_width(&string, NULL);
+       }
+}
+
 int is_utf8(const char *text)
 {
        while (*text) {
diff --git a/utf8.h b/utf8.h
index 98cce1b038a908bec51ccd2f7e1c1f648cb429a1..2f1b14ff49ef3c73bee6f298ba396b96120c34b7 100644 (file)
--- a/utf8.h
+++ b/utf8.h
@@ -5,6 +5,7 @@ typedef unsigned int ucs_char_t;  /* assuming 32bit int */
 
 ucs_char_t pick_one_utf8_char(const char **start, size_t *remainder_p);
 int utf8_width(const char **start, size_t *remainder_p);
+int utf8_strwidth(const char *string);
 int is_utf8(const char *text);
 int is_encoding_utf8(const char *name);