From: Dirk Gouders Date: Tue, 17 Nov 2026 17:57:08 GMT Subject: Re: [PATCH 1/2] utf8: respect bounds in utf8_strnwidth() Message-ID: In-Reply-To: On Tue, Nov 17 2026, Junio C Hamano wrote: > Junio C Hamano writes: > >> The problem is well spotted, but isn't the blame slightly misplaced? >> ... >> Even if display_mode_esc_sequence_len() were updated to take the >> remaining number of bytes in string (which I think *is* a good >> change, by the way), ... > > An update to display_mode_esc_sequence_len() to take the length > limit, including its fallout, is shown below, and it does not look > too bad. Not even compile-tested, but it should be sufficient as an > illustration of the idea. > > This does not make your "after display_mode_esc_sequence_len() > skips, make sure if we still have remaining string to grab one UTF-8 > character" change unnecessary, as I said. My v2 would have introduced two new functions (see attached) to replace display_mode_esc_sequence_len(): • size_t ansi_sgr_nlen(const char *str, size_t len); • size_t ansi_sgr_nlen_multi(const char *s, size_t len); The latter one to help (most of all) users who want to eat *all* leading SGR sequences so that they don't need loops. But I saw you already posted a patch and that is also fine, of course. Dirk diff --git a/utf8.c b/utf8.c index 96460cc414..1e3887480f 100644 --- a/utf8.c +++ b/utf8.c @@ -30,6 +30,44 @@ size_t display_mode_esc_sequence_len(const char *s) return p - s; } +size_t ansi_sgr_nlen(const char *str, size_t len) +{ + const char *p = str; + const char *p_max = str + len; + + if (len < 3) + return 0; + + if (*p++ != '\033') + return 0; + if (*p++ != '[') + return 0; + + while (p < p_max && (isdigit(*p) || *p == ';')) + p++; + + if (p == p_max || *p != 'm') + return 0; + + return p - str; +} + +size_t ansi_sgr_nlen_multi(const char *s, size_t len) +{ + size_t sgr_len = 0; + + while (sgr_len < len) { + size_t count = ansi_sgr_nlen(s + sgr_len, len - sgr_len); + + if (!count) + break; + + sgr_len += count; + } + + return sgr_len; +} + /* auxiliary function for binary search in interval table */ static int bisearch(ucs_char_t ucs, const struct interval *table, int max) {