# utf8_strnwidth() bounds fixes draw performance objection

_Andy Koppe argues that a strlen()-based wrapper would make scanning for escape sequences quadratic._

Section: Patches. Edition of 2026-11-19. Written by an AI editor from the thread "[PATCH 0/2] utf8: two minor fixes" (26 messages): https://gitlist.dev/t/66858

Dirk Gouders noticed two problems in utf8.c while looking at display_mode_esc_sequence_len(). utf8_strnwidth() ignores its len argument when given a proper string and length, and its comment says it returns strlen() when it actually returns len. The series now has separate patches that respect bounds for incomplete multibyte sequences, handle ANSI escape sequences that end the string within the boundary, and fix the comment. Each adds unit tests.

Andy Koppe objected to an earlier version, saying it was a performance regression. Calls that used to return immediately when *s != '\033', or after scanning a few bytes, would now scan the whole string with strlen. That turns scanning a whole string for SGR sequences by repeated calls from linear to quadratic. He argued that if the original implementation is not kept, no wrapper should be provided, so callers have to think about the length they pass. He added that callers using strbufs do not need the safety net because strbufs are NUL-terminated. He also noted that the word "null-terminated" in a comment is wrong.

Junio C Hamano called the find well spotted and nicely done. He asked Dirk to drop excess whitespace and break an overlong line, and suggested omitting the explicit comparison with zero and restructuring the loop.

The topic is related to Junio's own patch that gives display_mode_esc_sequence_len() a length argument, which was featured earlier this week. Whether the final form avoids the quadratic behavior Andy described is not settled in the excerpts.
