[PATCH v2 3/4] utf8: respect string boundaries after skipping ANSI escape sequences
- From
Dirk Gouders <dirk@gouders.net>
- Date
- Nov 18, 2026, 21:08 UTC
- Message-ID
- <20261118-master-v2-3-3f2aaec15d31@gouders.net>
- In-Reply-To
- <20261118-master-v2-0-3f2aaec15d31@gouders.net>
utf8_strnwidth() can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.
Check for such situations before proceeding and calling utf8_width().
Add tests that test such corner cases.
Signed-off-by: Dirk Gouders <dirk@gouders.net> --- t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 12 ++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-)
diff --git a/t/unit-tests/u-utf8-width.c b/t/unit-tests/u-utf8-width.c index 86e09c3574..5e2b636db9 100644 --- a/t/unit-tests/u-utf8-width.c +++ b/t/unit-tests/u-utf8-width.c @@ -2,6 +2,17 @@ #include "utf8.h" #include "strbuf.h" +/* + * Test utf8_strnwidth for strings with SGR sequences and corner case length + * arguments. + */ +void test_utf8_width__strnwidth_ansi(void) +{ + cl_assert_equal_i(3, utf8_strnwidth("\033[31mhello", 4, 1)); + cl_assert_equal_i(0, utf8_strnwidth("\033[31mhello", 5, 1)); + cl_assert_equal_i(1, utf8_strnwidth("\033[31mhello", 6, 1)); +} + /* * Test utf8_strnwidth with various Chinese strings * Chinese characters typically have a width of 2 columns when displayed diff --git a/utf8.c b/utf8.c index b43f84a03d..1b88324ea3 100644 --- a/utf8.c +++ b/utf8.c @@ -230,10 +230,14 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) int glyph_width; size_t skip; - while (skip_ansi && - (skip = display_mode_esc_sequence_len_counted(string, - orig + len - string)) != 0) - string += skip; + if (skip_ansi ) { + while ((skip = display_mode_esc_sequence_len_counted(string, + orig + len - string)) != 0) + string += skip; + + if (string >= orig + len) + break; + } glyph_width = utf8_width(&string, NULL); if (glyph_width > 0)
-- 2.55.0