From: Dirk Gouders Date: Wed, 18 Nov 2026 21:08:53 GMT Subject: [PATCH v2 4/4] utf8: respect boundaries in utf8_strnwidth() Message-ID: <20261118-master-v2-4-3f2aaec15d31@gouders.net> In-Reply-To: <20261118-master-v2-0-3f2aaec15d31@gouders.net> utf8_strnwidth() can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases. But, utf8_width is used without its optional boundary argument and will thus work beyond the given boundary. Fix this by using the boundary argument for utf8_width. Add some tests that cover such situations. Signed-off-by: Dirk Gouders --- t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/t/unit-tests/u-utf8-width.c b/t/unit-tests/u-utf8-width.c index 5e2b636db9..c4df4dd6a6 100644 --- a/t/unit-tests/u-utf8-width.c +++ b/t/unit-tests/u-utf8-width.c @@ -2,6 +2,15 @@ #include "utf8.h" #include "strbuf.h" +/* + * Test utf8_strnwidth for cjk characters invalidated by len argument. + */ +void test_utf8_width__strnwidth_cjk_chopped(void) +{ + cl_assert_equal_i(1, utf8_strnwidth("三bytes long, 二columns wide", 1, 1)); + cl_assert_equal_i(2, utf8_strnwidth("三bytes long, 二columns wide", 3, 1)); +} + /* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments. diff --git a/utf8.c b/utf8.c index 1b88324ea3..8d4b159e1d 100644 --- a/utf8.c +++ b/utf8.c @@ -229,6 +229,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) while (string && string < orig + len) { int glyph_width; size_t skip; + size_t remainder; if (skip_ansi ) { while ((skip = display_mode_esc_sequence_len_counted(string, @@ -239,7 +240,9 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) break; } - glyph_width = utf8_width(&string, NULL); + remainder = orig + len - string; + + glyph_width = utf8_width(&string, &remainder); if (glyph_width > 0) width += glyph_width; } -- 2.55.0