Truly independent web browser
AK: Validate lonely surrogates in a Utf8View without recursing
Shannon Boothcb47127b951b
diff --git a/AK/Utf8View.cpp b/AK/Utf8View.cppindex 7865d355209..35f4e55f88e 100644--- a/AK/Utf8View.cpp+++ b/AK/Utf8View.cpp@@ -179,20 +179,20 @@ Utf8View Utf8View::trim(Utf8View const& characters, TrimMode mode) constbool Utf8View::validate(size_t& valid_bytes, AllowLonelySurrogates allow_lonely_surrogates) const{- auto result = simdutf::validate_utf8_with_errors(m_string.characters_without_null_termination(), m_string.length());- valid_bytes = result.count;+ valid_bytes = 0;- if (result.error == simdutf::SURROGATE && allow_lonely_surrogates == AllowLonelySurrogates::Yes) {- valid_bytes += 3; // All surrogates have a UTF-8 byte length of 3.+ while (true) {+ auto remaining = m_string.substring_view(valid_bytes);+ auto result = simdutf::validate_utf8_with_errors(remaining.characters_without_null_termination(), remaining.length());+ valid_bytes += result.count;- size_t substring_valid_bytes = 0;- auto is_valid = substring_view(valid_bytes).validate(substring_valid_bytes, allow_lonely_surrogates);+ if (result.error == simdutf::SURROGATE && allow_lonely_surrogates == AllowLonelySurrogates::Yes) {+ valid_bytes += 3; // All surrogates have a UTF-8 byte length of 3.+ continue;+ }- valid_bytes += substring_valid_bytes;- return is_valid;+ return result.error == simdutf::SUCCESS;}-- return result.error == simdutf::SUCCESS;}Optional<u32> Utf8CodePointIterator::peek(size_t offset) constdiff --git a/Tests/AK/TestUtf8View.cpp b/Tests/AK/TestUtf8View.cppindex 839f50f271d..6b63aefabe4 100644--- a/Tests/AK/TestUtf8View.cpp+++ b/Tests/AK/TestUtf8View.cpp@@ -7,6 +7,7 @@#include <LibTest/TestCase.h>#include <AK/ByteBuffer.h>+#include <AK/StringBuilder.h>#include <AK/Utf8View.h>TEST_CASE(decode_ascii)@@ -99,6 +100,22 @@ TEST_CASE(validate_invalid_ut8)EXPECT(valid_bytes == 0);}+TEST_CASE(validate_many_lonely_surrogates)+{+ StringBuilder builder;+ for (size_t i = 0; i < 100'000; ++i)+ builder.append("\xed\xa0\x80"sv); // U+d800+ builder.append("a\xff"sv);++ size_t valid_bytes = 0;+ Utf8View view { builder.string_view() };+ EXPECT(!view.validate(valid_bytes, AllowLonelySurrogates::Yes));+ EXPECT_EQ(valid_bytes, 300'001uz);++ EXPECT(view.substring_view(0, 300'001).validate(valid_bytes, AllowLonelySurrogates::Yes));+ EXPECT_EQ(valid_bytes, 300'001uz);+}+TEST_CASE(validate_overlong_utf8){size_t valid_bytes = 0;