# UTF-8 escape-sequence helper gets bounds; Dirk Gouders prepares a v2

_A bounds fix for display_mode_esc_sequence_len() has gone through several drafts, with Junio Hamano settling on a counted variant alongside a NUL-terminated wrapper._

Section: Patches. Edition of 2026-11-18. Written by an AI editor from the thread "[PATCH] utf8: make display_mode_esc_sequence_len() take a length" (15 messages): https://gitlist.dev/t/66864

The function scans for an ANSI display-mode escape sequence such as ESC [ 1 ; 31 m and stops only at NUL, even though some callers, notably utf8_strnwidth(), work on counted buffers and must not read past a given length. The issue surfaced when Dirk Gouders looked at the function while preparing two utf8 fixes: utf8_strnwidth() ignored its len argument for proper strings, and its comment misdescribed the return value.

Junio Hamano first sent an illustration patch changing the function to take a length and updating its callers. Later versions in the thread instead add display_mode_esc_sequence_len_counted() taking a pointer and length, and keep display_mode_esc_sequence_len() as a thin wrapper for NUL-terminated strings. The counted variant is used in utf8_strnwidth(), strbuf_utf8_replace() and strbuf_add_wrapped_text(), the last computing the end once instead of calling strlen() repeatedly. Hamano said that a two-function arrangement is better for maintainability, since other proposed topics would add more callers.

Dirk Gouders had planned a different pair, ansi_sgr_nlen() and ansi_sgr_nlen_multi(), the second to consume all leading SGR sequences without a loop at the caller. He accepted Hamano's patch as fine and said he is preparing a v2, giving it time to avoid errors in his workflow. He suggested an early return when len is below 3, since the shortest SGR sequence is ESC [ m, and asked for tests, noting that his untested sketch had an off-by-one error. Hamano doubted the early return has measurable performance value and had no benchmarks. He offered to reuse Gouders's work, and Gouders said he was welcome to.

Andy Koppe asked that colons be added as accepted characters, citing ECMA-48 sub-separators and xterm's acceptance of colons in SGR sequences. Hamano asked whether Git actually generates such sequences, saying the code counts the width of strings Git itself has painted in a buffer rather than user-supplied text. That question is unanswered.
