From 4b91eb717554aeaab8f366a1608276acb5f88479 Mon Sep 17 00:00:00 2001 From: Kae <80987908+Novaenia@users.noreply.github.com> Date: Wed, 28 Jun 2023 20:07:22 +1000 Subject: [PATCH] Fix StringView::substr --- source/core/StarStringView.cpp | 31 +++++++++++++------------------ source/core/StarUnicode.hpp | 4 ++++ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/source/core/StarStringView.cpp b/source/core/StarStringView.cpp index 36ad9b2..8090515 100644 --- a/source/core/StarStringView.cpp +++ b/source/core/StarStringView.cpp @@ -338,27 +338,22 @@ bool StringView::equalsIgnoreCase(StringView s) const { } StringView StringView::substr(size_t position, size_t n) const { - auto len = size(); - if (position > len) - throw OutOfRangeException(strf("out of range in StringView::substr({}, {})", position, n)); - - if (position == 0 && n >= len) - return *this; - - String ret; - ret.reserve(std::min(n, len - position)); - + StringView ret; + auto it_end = end(); auto it = begin(); - std::advance(it, position); - - for (size_t i = 0; i < n; ++i) { - if (it == end()) - break; - ret.append(*it); - ++it; + for (size_t i = 0; i != position; ++i) { + if (++it == it_end) + throw OutOfRangeException(strf("out of range in StringView::substr({}, {})", position, n)); } - return ret; + const char* start = &*it.base(); + + for (size_t i = 0; i != n; ++i) { + if (it++ == it_end) + return StringView(start, &*it.base() - start - 1); + } + + return StringView(start, &*it.base() - start); } int StringView::compare(size_t selfOffset, size_t selfLen, StringView other, diff --git a/source/core/StarUnicode.hpp b/source/core/StarUnicode.hpp index 845259f..9abff3e 100644 --- a/source/core/StarUnicode.hpp +++ b/source/core/StarUnicode.hpp @@ -49,6 +49,10 @@ public: U8ToU32Iterator(BaseIterator b) : m_position(b), m_value(pending_read) {} + BaseIterator const& base() const { + return m_position; + } + U32Type const& operator*() const { if (m_value == pending_read) extract_current();