Skip to content

Commit 0cbb4a1

Browse files
[WTF] Make URLParser faster than Ada
* URLParser: scan runs of ordinary characters instead of dispatching per code point Adds table-driven run scanners for the scheme, authority, path, query, fragment and opaque-path states plus a straight-line pass over the common special-scheme://host/path?query#fragment shape that hands off to the state machine at the first character needing more than a copy. Host parsing only attempts IPv4 / ends-in-a-number when the last label could be a number, the parser writes into the caller's URL and borrows const input strings, and URL::invalidate is inline. * URLParser: rewrite IPv4/IPv6 host parsing over character pointers, avoid UTF-8 round trip for IDN hosts, cheaper isTabOrNewline * URLParser: SIMD scans for path, query, fragment and opaque path runs * URLParser: percent-encoded host path cleanups * URLParser: pointer scans for authority '@' search, non-special hosts, userinfo runs and ports * URLParser: branch-free upper-case detection in host validation * URLParser: narrow UTF-16 to bytes for SIMD classification and appends * URLParser: SIMD skip of plain host characters, fused percent-encoded host path, cheaper short UTF-16 appends * URLParser: header for parseIPv6Host signature * hasUnpairedSurrogate: use simdutf UTF-16 validation instead of iterating code points This is what every USVString conversion goes through; for 16-bit strings it was ~40% of URL.canParse. * URLParser: cheap early-out before the ends-in-a-number label scan * StringImpl::deref: skip the atomic read-modify-write when uniquely owned If the reference being dropped is the only one, no other thread can hold a reference from which to add another, so a relaxed load suffices before destroying. * URLParser: dotted-quad fast path, table-driven number-label check, SIMD to end of authority for non-plain hosts, leaner CodePointIterator * URLParser: inline the syntax-violation check and percentEncodeByte * URLParser: SIMD authority scan in AuthorityOrHost/Host states * URLParser: let path runs span '/' unless it may start a dot segment * URLParser: bulk-copy a 16-bit base URL prefix * URLParser: remove an incorrect assertion * URLParser: SIMD host scan in the FileHost state * URLParser: branch-free hex digit values in IPv6 parsing * URLParser: reject a host surrogate pair split by a tab like the old parser did; own the input string; one lastLabelMayBeANumber; update URLGLib.cpp - parseHostAndPort checked for unpaired surrogates after removing tabs and newlines, so a pair split by one was reunited and accepted. The old parser iterated code points over the raw host and saw two unpaired surrogates. Check before stripping. Adds a TestWTF case. - Replace the borrowed 'const String& m_inputString' + m_ownedInputString pair with one owned String that is moved into the result; same refcount traffic on the no-violation path, no self-referential member. - Hoist the three copies of the ends-in-a-number pre-check into one helper. - URL(GUri*) still used the removed URLParser(String&&)/result() API.
1 parent 592a255 commit 0cbb4a1

10 files changed

Lines changed: 1294 additions & 412 deletions

File tree

‎Source/WTF/wtf/URL.cpp‎

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -45,30 +45,16 @@
4545

4646
namespace WTF {
4747

48-
void URL::invalidate()
49-
{
50-
m_isValid = false;
51-
m_protocolIsInHTTPFamily = false;
52-
m_hasOpaquePath = false;
53-
m_schemeEnd = 0;
54-
m_userStart = 0;
55-
m_userEnd = 0;
56-
m_passwordEnd = 0;
57-
m_hostEnd = 0;
58-
m_portLength = 0;
59-
m_pathEnd = 0;
60-
m_pathAfterLastSlash = 0;
61-
m_queryEnd = 0;
62-
}
63-
6448
URL::URL(const URL& base, const String& relative, const URLTextEncoding* encoding)
6549
{
66-
*this = URLParser(String { relative }, base, encoding).result();
50+
invalidate();
51+
URLParser(*this, String { relative }, base, encoding);
6752
}
6853

6954
URL::URL(String&& absoluteURL, const URLTextEncoding* encoding)
7055
{
71-
*this = URLParser(WTF::move(absoluteURL), URL(), encoding).result();
56+
invalidate();
57+
URLParser(*this, WTF::move(absoluteURL), URL(), encoding);
7258
}
7359

7460
static bool NODELETE shouldTrimFromURL(char16_t character)
@@ -701,12 +687,16 @@ static String percentEncodeCharacters(const StringType& input, bool(*shouldEncod
701687

702688
void URL::parse(String&& string)
703689
{
704-
*this = URLParser(WTF::move(string)).result();
690+
URL result;
691+
URLParser(result, WTF::move(string));
692+
*this = WTF::move(result);
705693
}
706694

707695
void URL::parseAllowingC0AtEnd(String&& string)
708696
{
709-
*this = URLParser(WTF::move(string), { }, URLTextEncodingSentinelAllowingC0AtEnd).result();
697+
URL result;
698+
URLParser(result, WTF::move(string), { }, URLTextEncodingSentinelAllowingC0AtEnd);
699+
*this = WTF::move(result);
710700
}
711701

712702
void URL::remove(unsigned start, unsigned length)

‎Source/WTF/wtf/URL.h‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ class URL {
262262
private:
263263
friend class URLParser;
264264

265-
WTF_EXPORT_PRIVATE void NODELETE invalidate();
265+
void invalidate();
266266
unsigned NODELETE hostStart() const;
267267
unsigned NODELETE credentialsEnd() const;
268268
void remove(unsigned start, unsigned length);
@@ -363,6 +363,22 @@ inline URL::URL(HashTableDeletedValueType)
363363
{
364364
}
365365

366+
inline void URL::invalidate()
367+
{
368+
m_isValid = false;
369+
m_protocolIsInHTTPFamily = false;
370+
m_hasOpaquePath = false;
371+
m_portLength = 0;
372+
m_schemeEnd = 0;
373+
m_userStart = 0;
374+
m_userEnd = 0;
375+
m_passwordEnd = 0;
376+
m_hostEnd = 0;
377+
m_pathAfterLastSlash = 0;
378+
m_pathEnd = 0;
379+
m_queryEnd = 0;
380+
}
381+
366382
inline bool URL::isNull() const
367383
{
368384
return m_string.isNull();

‎Source/WTF/wtf/URLParser.cpp‎

Lines changed: 1217 additions & 358 deletions
Large diffs are not rendered by default.

‎Source/WTF/wtf/URLParser.h‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,13 @@ class URLParser {
7070
WTF_EXPORT_PRIVATE static std::optional<String> formURLDecode(StringView input);
7171

7272
private:
73-
URLParser(String&&, const URL& = { }, const URLTextEncoding* = nullptr);
74-
URL result() { return m_url; }
73+
// Parses into `result`, which must be a default-constructed URL.
74+
URLParser(URL& result, String&&, const URL& base = { }, const URLTextEncoding* = nullptr);
7575

7676
friend class URL;
7777

78-
URL m_url;
79-
Vector<Latin1Character> m_asciiBuffer;
78+
URL& m_url;
79+
Vector<Latin1Character, 256> m_asciiBuffer;
8080
bool m_urlIsSpecial { false };
8181
bool m_urlIsFile { false };
8282
bool m_hostHasPercentOrNonASCII { false };
@@ -101,6 +101,7 @@ class URLParser {
101101
void advance(CodePointIterator<CharacterType>&, const CodePointIterator<CharacterType>& iteratorForSyntaxViolationPosition);
102102
template<typename CharacterType> bool NODELETE takesTwoAdvancesUntilEnd(CodePointIterator<CharacterType>);
103103
template<typename CharacterType> void syntaxViolation(const CodePointIterator<CharacterType>&);
104+
template<typename CharacterType> void beginSyntaxViolation(const CodePointIterator<CharacterType>&);
104105
template<typename CharacterType> bool isPercentEncodedDot(CodePointIterator<CharacterType>);
105106
template<typename CharacterType> bool isWindowsDriveLetter(CodePointIterator<CharacterType>);
106107
template<typename CharacterType> bool isSingleDotPathSegment(CodePointIterator<CharacterType>);
@@ -113,17 +114,20 @@ class URLParser {
113114
template<typename CharacterType> void consumeDoubleDotPathSegment(CodePointIterator<CharacterType>&);
114115
template<typename CharacterType> void appendWindowsDriveLetter(CodePointIterator<CharacterType>&);
115116
template<typename CharacterType> size_t currentPosition(const CodePointIterator<CharacterType>&);
117+
template<typename CharacterType> size_t currentPosition(const CharacterType*);
116118
template<typename UnsignedIntegerType> void appendNumberToASCIIBuffer(UnsignedIntegerType);
117119
template<bool(*isInCodeSet)(char32_t), typename CharacterType> void utf8PercentEncode(const CodePointIterator<CharacterType>&);
118120
template<typename CharacterType> void utf8QueryEncode(const CodePointIterator<CharacterType>&);
119-
template<typename CharacterType> std::optional<Latin1Buffer> domainToASCII(StringImpl&, const CodePointIterator<CharacterType>& iteratorForSyntaxViolationPosition);
121+
template<typename CharacterType> std::optional<Latin1Buffer> domainToASCII(StringView, const CodePointIterator<CharacterType>& iteratorForSyntaxViolationPosition);
120122
template<typename SyntaxViolationHandler> static Latin1Buffer percentDecodeImpl(std::span<const Latin1Character>, SyntaxViolationHandler&&);
121123
template<typename CharacterType> Latin1Buffer percentDecode(std::span<const Latin1Character>, const CodePointIterator<CharacterType>& iteratorForSyntaxViolationPosition);
122124
static Latin1Buffer percentDecode(std::span<const Latin1Character>);
123125
bool NODELETE hasForbiddenHostCodePoint(const Latin1Buffer&);
124126
void percentEncodeByte(uint8_t);
125127
void appendToASCIIBuffer(char32_t);
126128
void appendToASCIIBuffer(std::span<const Latin1Character>);
129+
void appendToASCIIBuffer(std::span<const char16_t>);
130+
template<typename CharacterType> void appendToASCIIBufferLowercased(std::span<const CharacterType>);
127131
template<typename CharacterType> void encodeNonUTF8Query(const Vector<char16_t>& source, const URLTextEncoding&, CodePointIterator<CharacterType>);
128132
void copyASCIIStringUntil(const String&, size_t length);
129133
bool copyBaseWindowsDriveLetter(const URL&);
@@ -136,13 +140,11 @@ class URLParser {
136140
using IPv4Address = uint32_t;
137141
void serializeIPv4(IPv4Address);
138142
enum class IPv4ParsingError;
139-
enum class IPv4PieceParsingError;
140-
template<typename CharacterTypeForSyntaxViolation, typename CharacterType> Expected<IPv4Address, IPv4ParsingError> parseIPv4Host(const CodePointIterator<CharacterTypeForSyntaxViolation>&, CodePointIterator<CharacterType>);
141-
template<typename CharacterType> Expected<uint32_t, URLParser::IPv4PieceParsingError> parseIPv4Piece(CodePointIterator<CharacterType>&, bool& syntaxViolation);
143+
template<typename CharacterTypeForSyntaxViolation, typename CharacterType> Expected<IPv4Address, IPv4ParsingError> parseIPv4Host(const CodePointIterator<CharacterTypeForSyntaxViolation>&, std::span<const CharacterType>);
142144
using IPv6Address = std::array<uint16_t, 8>;
143-
template<typename CharacterType> std::optional<IPv6Address> parseIPv6Host(CodePointIterator<CharacterType>);
144-
template<typename CharacterType> std::optional<uint32_t> NODELETE parseIPv4PieceInsideIPv6(CodePointIterator<CharacterType>&);
145-
template<typename CharacterType> std::optional<IPv4Address> NODELETE parseIPv4AddressInsideIPv6(CodePointIterator<CharacterType>);
145+
template<typename CharacterType> std::optional<IPv6Address> parseIPv6Host(CodePointIterator<CharacterType> hostBeginForSyntaxViolation, std::span<const CharacterType> address);
146+
template<typename CharacterType> std::optional<uint32_t> NODELETE parseIPv4PieceInsideIPv6(std::span<const CharacterType>&);
147+
template<typename CharacterType> std::optional<IPv4Address> NODELETE parseIPv4AddressInsideIPv6(std::span<const CharacterType>);
146148
void serializeIPv6Piece(uint16_t piece);
147149
void serializeIPv6(IPv6Address);
148150

‎Source/WTF/wtf/cf/URLCF.cpp‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,9 @@ namespace WTF {
3737
URL::URL(CFURLRef url)
3838
{
3939
// FIXME: Why is it OK to ignore the base URL in the CFURL here?
40-
if (!url)
41-
invalidate();
42-
else
43-
*this = URLParser(bytesAsString(url)).result();
40+
invalidate();
41+
if (url)
42+
URLParser(*this, bytesAsString(url));
4443
}
4544

4645
RetainPtr<CFURLRef> URL::createCFURL(const String& string)

‎Source/WTF/wtf/glib/URLGLib.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ URL::URL(GUri* uri)
4343
}
4444

4545
GUniquePtr<char> uriString(g_uri_to_string(uri));
46-
URLParser parser(String::fromUTF8(uriString.get()));
47-
*this = parser.result();
46+
invalidate();
47+
URLParser(*this, String::fromUTF8(uriString.get()));
4848
}
4949

5050
GRefPtr<GUri> URL::createGUri() const

‎Source/WTF/wtf/text/CodePointIterator.h‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
6262
{
6363
return m_data.empty();
6464
}
65+
66+
ALWAYS_INLINE const CharacterType* position() const { return m_data.data(); }
67+
ALWAYS_INLINE std::span<const CharacterType> remainingCodeUnits() const { return m_data; }
6568

6669
ALWAYS_INLINE size_t codeUnitsSince(const CharacterType* reference) const
6770
{
@@ -78,39 +81,48 @@ WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
7881
std::span<const CharacterType> m_data;
7982
};
8083

84+
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
85+
8186
template<>
8287
ALWAYS_INLINE char32_t CodePointIterator<Latin1Character>::operator*() const
8388
{
8489
ASSERT(!atEnd());
85-
return m_data.front();
90+
return *m_data.data();
8691
}
8792

8893
template<>
8994
ALWAYS_INLINE auto CodePointIterator<Latin1Character>::operator++() -> CodePointIterator&
9095
{
91-
skip(m_data, 1);
96+
ASSERT(!atEnd());
97+
m_data = { m_data.data() + 1, m_data.size() - 1 };
9298
return *this;
9399
}
94100

95101
template<>
96102
ALWAYS_INLINE char32_t CodePointIterator<char16_t>::operator*() const
97103
{
98104
ASSERT(!atEnd());
99-
char32_t c;
100-
U16_GET(m_data, 0, 0, m_data.size(), c);
105+
auto* data = m_data.data();
106+
char32_t c = data[0];
107+
if (U16_IS_LEAD(c) && m_data.size() > 1 && U16_IS_TRAIL(data[1])) [[unlikely]]
108+
return U16_GET_SUPPLEMENTARY(c, data[1]);
101109
return c;
102110
}
103111

104112
template<>
105113
ALWAYS_INLINE auto CodePointIterator<char16_t>::operator++() -> CodePointIterator&
106114
{
107-
unsigned i = 0;
108-
size_t length = m_data.size();
109-
U16_FWD_1(m_data, i, length);
110-
skip(m_data, i);
115+
ASSERT(!atEnd());
116+
auto* data = m_data.data();
117+
size_t length = 1;
118+
if (U16_IS_LEAD(data[0]) && m_data.size() > 1 && U16_IS_TRAIL(data[1])) [[unlikely]]
119+
length = 2;
120+
m_data = { data + length, m_data.size() - length };
111121
return *this;
112122
}
113123

124+
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
125+
114126
template<typename CharacterType> CodePointIterator(std::span<const CharacterType>) -> CodePointIterator<CharacterType>;
115127

116128
} // namespace WTF

‎Source/WTF/wtf/text/StringImpl.h‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1201,9 +1201,12 @@ inline void StringImpl::deref()
12011201
return;
12021202
#endif
12031203

1204-
auto oldRefCount = m_refCount.fetch_sub(s_refCountIncrement, std::memory_order_relaxed);
1205-
if (oldRefCount != s_refCountIncrement)
1206-
return;
1204+
// When this is the only reference nobody else can be racing to add one, so skip the atomic read-modify-write.
1205+
auto refCount = m_refCount.load(std::memory_order_relaxed);
1206+
if (refCount != s_refCountIncrement) {
1207+
if (m_refCount.fetch_sub(s_refCountIncrement, std::memory_order_relaxed) != s_refCountIncrement) [[likely]]
1208+
return;
1209+
}
12071210

12081211
StringImpl::destroy(this);
12091212
}

‎Source/WTF/wtf/text/StringView.h‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,11 +1282,7 @@ inline bool hasUnpairedSurrogate(StringView string)
12821282
// Fast path for 8-bit strings; they can't have any surrogates.
12831283
if (string.is8Bit())
12841284
return false;
1285-
for (auto codePoint : string.codePoints()) {
1286-
if (U_IS_SURROGATE(codePoint))
1287-
return true;
1288-
}
1289-
return false;
1285+
return !isWellFormedUTF16(string.span16());
12901286
}
12911287

12921288
inline size_t findCommon(StringView haystack, StringView needle, unsigned start)

‎Tools/TestWebKitAPI/Tests/WTF/URLParser.cpp‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1120,6 +1120,11 @@ TEST_F(WTF_URLParser, AdditionalTests)
11201120
{ "http"_s, ""_s, ""_s, "w"_s, 0, "/%F0%90%85%95"_s, ""_s, ""_s, "http://w/%F0%90%85%95"_s }, testTabsValueForSurrogatePairs);
11211121
shouldFail(utf16String<10>({'h', 't', 't', 'p', ':', '/', surrogateBegin, invalidSurrogateEnd, '/', '\0'}));
11221122
shouldFail(utf16String<9>({'h', 't', 't', 'p', ':', '/', replacementCharacter, '/', '\0'}));
1123+
// A surrogate pair in a host split by a tab is two unpaired surrogates, like elsewhere in the URL.
1124+
checkURL(utf16String<10>({'h', 't', 't', 'p', ':', '/', '/', 0xD83D, 0xDCA9, '\0'}),
1125+
{ "http"_s, ""_s, ""_s, "xn--ls8h"_s, 0, "/"_s, ""_s, ""_s, "http://xn--ls8h/"_s }, testTabsValueForSurrogatePairs);
1126+
shouldFail(utf16String<11>({'h', 't', 't', 'p', ':', '/', '/', 0xD83D, '\t', 0xDCA9, '\0'}));
1127+
shouldFail(utf16String<12>({'f', 'i', 'l', 'e', ':', '/', '/', 0xD83D, '\n', 0xDCA9, '/', '\0'}));
11231128

11241129
// URLParser matches Chrome and Firefox but not URL::parse.
11251130
checkURLDifferences(utf16String<12>({'h', 't', 't', 'p', ':', '/', '/', 'w', '/', surrogateBegin, invalidSurrogateEnd}),

0 commit comments

Comments
 (0)