From c38027f0b8568cbf5d2f60ef56c5c5e076ebb0bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerd=20M=C3=B6llmann?= Date: Sat, 26 Apr 2025 21:20:22 +0200 Subject: [PATCH] Don't optimize prematurely in text_index_charpos_to_bytepos * src/text-index.c (text_index_bytepos_to_charpos): Add a const. (bytepos_of_head): Removed. (text_index_charpos_to_bytepos): Don't be clever about choosing to scan forward or backward. (bytepos_forward_to_charpos): Use char_start_bytepos. --- src/text-index.c | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/src/text-index.c b/src/text-index.c index edb2f0d592f..a04d7e39419 100644 --- a/src/text-index.c +++ b/src/text-index.c @@ -457,7 +457,7 @@ bytepos_forward_to_charpos (struct buffer *b, const struct text_pos from, ptrdiff_t to_charpos) { eassert (from.charpos < to_charpos); - ptrdiff_t bytepos = from.bytepos; + ptrdiff_t bytepos = char_start_bytepos (b, from.bytepos); ptrdiff_t charpos = from.charpos; while (charpos < to_charpos) { @@ -620,7 +620,7 @@ buf_bytepos_to_charpos (struct buffer *b, const ptrdiff_t bytepos) /* Scan forward if the distance to the previous known position is smaller than the distance to the next known position. */ - ptrdiff_t charpos + const ptrdiff_t charpos = (bytepos - prev.bytepos < next.bytepos - bytepos) ? charpos_forward_to_bytepos (b, prev, bytepos) : charpos_backward_to_bytepos (b, next, bytepos); @@ -629,14 +629,6 @@ buf_bytepos_to_charpos (struct buffer *b, const ptrdiff_t bytepos) return charpos; } -static ptrdiff_t -bytepos_of_head (struct buffer *b, ptrdiff_t bytepos) -{ - while (!CHAR_HEAD_P (BUF_FETCH_BYTE (b, bytepos))) - --bytepos; - return bytepos; -} - /* Return the byte position in buffer B corresponding to character position CHARPOS. */ @@ -684,14 +676,12 @@ buf_charpos_to_bytepos (struct buffer *b, const ptrdiff_t charpos) return prev.bytepos + (charpos - prev.charpos); /* ASCII-only! */ } - /* Don't scan forward if CHARPOS is exactly on the previous known - position because the index bytepos can be in the middle of a - character, which is found by scanning backwards. */ - ptrdiff_t bytepos - = (charpos == prev.charpos ? bytepos_of_head (b, prev.bytepos) - : (charpos - prev.charpos < next.charpos - charpos - ? bytepos_forward_to_charpos (b, prev, charpos) - : bytepos_backward_to_charpos (b, next, charpos))); + /* Scan forward if the distance to the previous known position is + smaller than the distance to the next known position. */ + const ptrdiff_t bytepos + = (charpos - prev.charpos < next.charpos - charpos + ? bytepos_forward_to_charpos (b, prev, charpos) + : bytepos_backward_to_charpos (b, next, charpos)); cache (ti, charpos, bytepos); return bytepos;