From 294f826364b1b4e01e73d0c473bb48918fe8adc4 Mon Sep 17 00:00:00 2001 From: frosch Date: Fri, 4 Apr 2025 21:43:46 +0200 Subject: [PATCH] Codechange: Replace last usage of Utf8CharLen with Utf8View. --- src/string_func.h | 17 ----------------- src/textbuf.cpp | 32 +++++++++++++++++++------------- 2 files changed, 19 insertions(+), 30 deletions(-) diff --git a/src/string_func.h b/src/string_func.h index f692ff7b1a..0952993855 100644 --- a/src/string_func.h +++ b/src/string_func.h @@ -106,23 +106,6 @@ inline char32_t Utf8Consume(Titr &s) return c; } -/** - * Return the length of a UTF-8 encoded character. - * @param c Unicode character. - * @return Length of UTF-8 encoding for character. - */ -inline int8_t Utf8CharLen(char32_t c) -{ - if (c < 0x80) return 1; - if (c < 0x800) return 2; - if (c < 0x10000) return 3; - if (c < 0x110000) return 4; - - /* Invalid valid, we encode as a '?' */ - return 1; -} - - /** * Return the length of an UTF-8 encoded value based on a single char. This * char should be the first byte of the UTF-8 encoding. If not, or encoding diff --git a/src/textbuf.cpp b/src/textbuf.cpp index 111be15df0..25d2481b60 100644 --- a/src/textbuf.cpp +++ b/src/textbuf.cpp @@ -170,24 +170,30 @@ bool Textbuf::InsertString(const char *str, bool marked, const char *caret, cons if (str == nullptr) return false; - uint16_t bytes = 0, chars = 0; - char32_t c; - for (const char *ptr = str; (c = Utf8Consume(&ptr)) != '\0';) { - if (!IsValidChar(c, this->afilter)) break; + uint16_t chars = 0; + uint16_t bytes; + { + Utf8View view(str); + auto cur = view.begin(); + const auto end = view.end(); + while (cur != end) { + if (!IsValidChar(*cur, this->afilter)) break; - uint8_t len = Utf8CharLen(c); - if (this->buf.size() + bytes + len >= this->max_bytes) break; - if (this->chars + chars + 1 > this->max_chars) break; + auto next = cur; + ++next; + if (this->buf.size() + next.GetByteOffset() >= this->max_bytes) break; + if (this->chars + chars + 1 > this->max_chars) break; - bytes += len; - chars++; - - /* Move caret if needed. */ - if (ptr == caret) this->caretpos = insertpos + bytes; + cur = next; + chars++; + } + bytes = static_cast(cur.GetByteOffset()); } - if (bytes == 0) return false; + /* Move caret if needed. */ + if (str <= caret && caret <= str + bytes) this->caretpos = insertpos + (caret - str); + if (marked) { this->markpos = insertpos; this->markend = insertpos + bytes;