Title: [285536] trunk
Revision
285536
Author
da...@apple.com
Date
2021-11-09 14:58:40 -0800 (Tue, 09 Nov 2021)

Log Message

[CF] Reduce duplication and unneeded buffer allocations and copying in URL code, also remove unused methods and functions
https://bugs.webkit.org/show_bug.cgi?id=232220

Reviewed by Alex Christensen.

Source/WebKit:

* Shared/API/c/cf/WKURLCF.mm:
(WKURLCreateWithCFURL): Use bytesAsString, saving creation and destruction
of a CString each time this is called.

* Shared/Cocoa/ArgumentCodersCocoa.mm:
(-[WKSecureCodingURLWrapper encodeWithCoder:]): Use bytesAsVector.

* Shared/Cocoa/WKNSURLExtras.h: Removed unused methods
+[NSURL _web_URLWithWTFString:relativeToURL:] and
-[NSURL _web_originalDataAsWTFString].

* Shared/Cocoa/WKNSURLExtras.mm:
(+[NSURL _web_URLWithWTFString:relativeToURL:]): Deleted.
(-[NSURL _web_originalDataAsWTFString]): Deleted.

* Shared/Cocoa/WKNSURLRequest.mm:
(-[WKNSURLRequest URL]): Removed unneeded call to +[NSURL _web_URLWithWTFString:]
because this code is converting a WTF::URL to an NSURL, which can use the conversion
operator in the WTF::URL class.

* Shared/cf/ArgumentCodersCF.cpp:
(IPC::ArgumentCoder<CFURLRef>::encode): Use bytesAsVector.

* UIProcess/API/Cocoa/WKBrowsingContextController.mm:
(-[WKBrowsingContextController loadFileURL:restrictToFilesWithin:userData:]):
Use bytesAsString and bridge_cast.
(-[WKBrowsingContextController loadHTMLString:baseURL:userData:]): Ditto.
(-[WKBrowsingContextController loadData:MIMEType:textEncodingName:baseURL:userData:]): Ditto.
(setUpPagePolicyClient): Removed unneeded call to +[NSURL _web_URLWithWTFString:]
because this code is converting a WTF::URL to an NSURL, which can use the conversion
operator in the WTF::URL class.

* UIProcess/Cocoa/LegacyDownloadClient.mm:
(WebKit::LegacyDownloadClient::willSendRequest): Removed unneeded call to
+[NSURL _web_URLWithWTFString:] because this code is converting a WTF::URL to an NSURL,
which can use the conversion operator in the WTF::URL class.
* WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm:
(-[WKWebProcessPlugInFrame URL]): Ditto.

Source/WebKitLegacy/mac:

* Misc/WebNSURLExtras.h: Tweaked comments a bit. No need to say methods are "new", since
that won't be true in the future. Removed unused methods
+[NSURL _web_URLWithUserTypedString:relativeToURL:],
+[NSURL _webkit_URLWithUserTypedString:relativeToURL:],
+[NSURL _web_URLWithData:], +[NSURL _web_URLWithData:relatveToURL:].
Wanted to remove even more nearly unused methods: many were used only
inside the WebKit project, in legacy plug-in code, and some seemed unused,
but it wasn't easy for me to quickly verify that.

* Misc/WebNSURLExtras.mm: Removed "using namespace WebCore" and
"using namespace WTF".
(+[NSURL _web_URLWithUserTypedString:relativeToURL:]): Deleted.
(+[NSURL _web_URLWithUserTypedString:]): Use WTF prefix explicitly.
(+[NSURL _webkit_URLWithUserTypedString:relativeToURL:]): Deleted.
(+[NSURL _webkit_URLWithUserTypedString:]): Use WTF prefix explicitly.
(+[NSURL _web_URLWithDataAsString:]): Removed special case for nil since the code
will do the right thing with nil without an explicit check.
(+[NSURL _web_URLWithDataAsString:relativeToURL]): Ditto. Also formatted the code
as a one-liner.
(+[NSURL _web_URLWithData:]): Deleted.
(+[NSURL _web_URLWithData:relativeToURL:]): Deleted.
(-[NSURL _web_originalData]): Use WTF prefix explicitly.
(-[NSURL _web_originalDataAsString]): Ditto.
(-[NSURL _web_isEmpty]): Use bridge_cast and make code style checker happy by using
"!" instead of "== 0".
(-[NSURL _web_URLCString]): Use WTF prefix explicitly.
(-[NSURL _webkit_canonicalize]): Use WebCore prefix explicitly.
(-[NSURL _webkit_URLByRemovingFragment]): Use WTF prefix explicitly.
(-[NSURL _web_schemeSeparatorWithoutColon]): Deleted.
(-[NSURL _web_dataForURLComponentType:]): Deleted.
(-[NSURL _web_hostData]): Use WTF prefix explicitly. Rearranged for clarity and
slightly improved efficiency as well.
(-[NSString _web_isUserVisibleURL]): Use WTF prefix explicitly.
(-[NSString _webkit_stringByReplacingValidPercentEscapes]): Use WebCore prefix
explicitly.
(-[NSString _web_decodeHostName]): Use WTF prefix explicitly.
(-[NSString _web_encodeHostName]): Ditto.
(-[NSString _webkit_decodeHostName]): Ditto.
(-[NSString _webkit_encodeHostName]): Ditto.

Source/WTF:

* wtf/URL.h: Removed unneeded includes. Use default instead of { }
for empty destructor. Added emptyCFURL function.

* wtf/cf/CFURLExtras.cpp:
(WTF::bytesAsCFData): Added. Replaces originalURLData from NSURLExtras.mm,
but with a simpler implementation and more error checking. Here it's also
alongside the other nearly identical functions.
(WTF::bytesAsString): Added. Replaces getURLBytes for callers that are
going to turn the bytes into a WTF::String. Before this patch, the callers
were converting from CFURLRef to WTF::CString and then to WTF::String, so
this eliminates the malloc/free pair for CString.
(WTF::bytesAsVector): Added. Replaces getURLBytes using a return value
instead of an out argument. Adds the optimization of filling the buffer if
the inline capacity is sufficient, which was in originalURLData, but not
here in getURLBytes before.
(WTF::isSameOrigin): Renamed from isCFURLSameOrigin and rewrote this to
have fewer type casts and more parallel structure so it's easier to read,
while adapting it to use bytesAsVector.

* wtf/cf/CFURLExtras.h: Replaced URLCharBuffer, getURLBytes, and
isCFURLSameOrigin with URLBytesVectorInlineCapacity, bytesAsCFData,
bytesAsString, bytesAsVector, and isSameOrigin. Got rid of unneeded
includes.

* wtf/cf/URLCF.cpp:
(WTF::URL::URL): Use bytesAsString to streamline implementation and
remove allocation/deallcation of a CString.
(WTF::URL::emptyCFURL): Added. Used to refactor createCFURL so we can
share it across Foundation and non-Foundation versions.
(WTF::URL::createCFURL const): Added the logic that was in the version
in URLCocoa.mm so we can share this single version, and removed the #if
surrounding this.
(WTF::URL::fileSystemPath const): Use auto.

* wtf/cocoa/NSURLExtras.h: Changed URLWithUserTypedString to ignore
the baseURL argument. It's not used, but the function is exported and
currently used in Safari source code, which, like all callers passes
a nil for baseURL. so, for now left the argument. Removed the baseURL
argument from URLWithUserTypedStringDeprecated. Removed unused functions
rangeOfURLScheme and looksLikeAbsoluteURL.

* wtf/cocoa/NSURLExtras.mm: Removed "using namespace URLHelpers".
(WTF::readIDNAllowedScriptListFile): Use URLHelpers explicitly.
(WTF::decodeHostName): Ditto.
(WTF::encodeHostName): Ditto.
(WTF::URLByTruncatingOneCharacterBeforeComponent): Simplified by using
the bytesAsVector function.
(WTF::URLByRemovingResourceSpecifier): Deleted.
(WTF::URLWithData): Call URLByTruncatingOneCharacterBeforeComponent
directly.
(WTF::URLWithUserTypedString): Removed the unneeded support for a
base URL. Use URLHelpers explicitly.
(WTF::URLWithUserTypedStringDeprecated): Ditto.
(WTF::hasQuestionMarkOnlyQueryString): Use bridge_cast.
(WTF::dataForURLComponentType): Rearranged to simplify a bit, remove support
for special value for CFURLComponentType that means the complete URL, since
no callers were using that, and use bytesAsVector.
(WTF::URLByRemovingComponentAndSubsequentCharacter): Use bridge_cast and
bytesAsVector.
(WTF::originalURLData): Use bridge_cast and bytesAsCFData.
(WTF::userVisibleString): Use URLHelpers explicitly.
(WTF::isUserVisibleURL): Rewrote for simplicity and coding style; since
the local characters are a null-terminated C string, we don't need
length checks as long as we validate characters first, since a '\0'
character can be read and will not be valid.
(WTF::rangeOfURLScheme): Deleted.
(WTF::looksLikeAbsoluteURL): Deleted.

* wtf/cocoa/URLCocoa.mm:
(WTF::URL::URL): Changed to just call the CFURLRef constructor so we
don't need to repeat things twice.
(WTF::URL::emptyCFURL): Added. This is the one part of the createCFURL
function that depends on Objective-C.
(WTF::URL::createCFURL const): Merged into the function in URLCF.cpp.
(WTF::makeNSArrayElement): Use bridge_cast instead of the trickier
idiom with explicit calls to leakRef and __bridge_transfer.

* wtf/mac/FileSystemMac.mm:
(WTF::FileSystem::setMetadataURL): Updated since URLWithUserTypedString
no longer requires a baseURL of nil to be passed. Also removed explicit
WTF namespace since this code itself is in the WTF namespace.

* wtf/text/cocoa/StringCocoa.mm:
(WTF::String::String): Use bridge_cast.
(WTF::makeNSArrayElement): Use bridge_cast.

Tools:

* TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm:
(TestWebKitAPI::TEST): Removed extra argument to URLWithUserTypedString/Deprecated.

Modified Paths

Diff

Modified: trunk/Source/WTF/ChangeLog (285535 => 285536)


--- trunk/Source/WTF/ChangeLog	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/ChangeLog	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,3 +1,96 @@
+2021-10-28  Darin Adler  <da...@apple.com>
+
+        [CF] Reduce duplication and unneeded buffer allocations and copying in URL code, also remove unused methods and functions
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+
+        Reviewed by Alex Christensen.
+
+        * wtf/URL.h: Removed unneeded includes. Use default instead of { }
+        for empty destructor. Added emptyCFURL function.
+
+        * wtf/cf/CFURLExtras.cpp:
+        (WTF::bytesAsCFData): Added. Replaces originalURLData from NSURLExtras.mm,
+        but with a simpler implementation and more error checking. Here it's also
+        alongside the other nearly identical functions.
+        (WTF::bytesAsString): Added. Replaces getURLBytes for callers that are
+        going to turn the bytes into a WTF::String. Before this patch, the callers
+        were converting from CFURLRef to WTF::CString and then to WTF::String, so
+        this eliminates the malloc/free pair for CString.
+        (WTF::bytesAsVector): Added. Replaces getURLBytes using a return value
+        instead of an out argument. Adds the optimization of filling the buffer if
+        the inline capacity is sufficient, which was in originalURLData, but not
+        here in getURLBytes before.
+        (WTF::isSameOrigin): Renamed from isCFURLSameOrigin and rewrote this to
+        have fewer type casts and more parallel structure so it's easier to read,
+        while adapting it to use bytesAsVector.
+
+        * wtf/cf/CFURLExtras.h: Replaced URLCharBuffer, getURLBytes, and
+        isCFURLSameOrigin with URLBytesVectorInlineCapacity, bytesAsCFData,
+        bytesAsString, bytesAsVector, and isSameOrigin. Got rid of unneeded
+        includes.
+
+        * wtf/cf/URLCF.cpp:
+        (WTF::URL::URL): Use bytesAsString to streamline implementation and
+        remove allocation/deallcation of a CString.
+        (WTF::URL::emptyCFURL): Added. Used to refactor createCFURL so we can
+        share it across Foundation and non-Foundation versions.
+        (WTF::URL::createCFURL const): Added the logic that was in the version
+        in URLCocoa.mm so we can share this single version, and removed the #if
+        surrounding this.
+        (WTF::URL::fileSystemPath const): Use auto.
+
+        * wtf/cocoa/NSURLExtras.h: Changed URLWithUserTypedString to ignore
+        the baseURL argument. It's not used, but the function is exported and
+        currently used in Safari source code, which, like all callers passes
+        a nil for baseURL. so, for now left the argument. Removed the baseURL
+        argument from URLWithUserTypedStringDeprecated. Removed unused functions
+        rangeOfURLScheme and looksLikeAbsoluteURL.
+
+        * wtf/cocoa/NSURLExtras.mm: Removed "using namespace URLHelpers".
+        (WTF::readIDNAllowedScriptListFile): Use URLHelpers explicitly.
+        (WTF::decodeHostName): Ditto.
+        (WTF::encodeHostName): Ditto.
+        (WTF::URLByTruncatingOneCharacterBeforeComponent): Simplified by using
+        the bytesAsVector function.
+        (WTF::URLByRemovingResourceSpecifier): Deleted.
+        (WTF::URLWithData): Call URLByTruncatingOneCharacterBeforeComponent
+        directly.
+        (WTF::URLWithUserTypedString): Removed the unneeded support for a
+        base URL. Use URLHelpers explicitly.
+        (WTF::URLWithUserTypedStringDeprecated): Ditto.
+        (WTF::hasQuestionMarkOnlyQueryString): Use bridge_cast.
+        (WTF::dataForURLComponentType): Rearranged to simplify a bit, remove support
+        for special value for CFURLComponentType that means the complete URL, since
+        no callers were using that, and use bytesAsVector.
+        (WTF::URLByRemovingComponentAndSubsequentCharacter): Use bridge_cast and
+        bytesAsVector.
+        (WTF::originalURLData): Use bridge_cast and bytesAsCFData.
+        (WTF::userVisibleString): Use URLHelpers explicitly.
+        (WTF::isUserVisibleURL): Rewrote for simplicity and coding style; since
+        the local characters are a null-terminated C string, we don't need
+        length checks as long as we validate characters first, since a '\0'
+        character can be read and will not be valid.
+        (WTF::rangeOfURLScheme): Deleted.
+        (WTF::looksLikeAbsoluteURL): Deleted.
+
+        * wtf/cocoa/URLCocoa.mm:
+        (WTF::URL::URL): Changed to just call the CFURLRef constructor so we
+        don't need to repeat things twice.
+        (WTF::URL::emptyCFURL): Added. This is the one part of the createCFURL
+        function that depends on Objective-C.
+        (WTF::URL::createCFURL const): Merged into the function in URLCF.cpp.
+        (WTF::makeNSArrayElement): Use bridge_cast instead of the trickier
+        idiom with explicit calls to leakRef and __bridge_transfer.
+
+        * wtf/mac/FileSystemMac.mm:
+        (WTF::FileSystem::setMetadataURL): Updated since URLWithUserTypedString
+        no longer requires a baseURL of nil to be passed. Also removed explicit
+        WTF namespace since this code itself is in the WTF namespace.
+
+        * wtf/text/cocoa/StringCocoa.mm:
+        (WTF::String::String): Use bridge_cast.
+        (WTF::makeNSArrayElement): Use bridge_cast.
+
 2021-11-09  Chris Dumez  <cdu...@apple.com>
 
         BroadcastChannel is still disabled in service workers

Modified: trunk/Source/WTF/wtf/URL.h (285535 => 285536)


--- trunk/Source/WTF/wtf/URL.h	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/URL.h	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2019 Apple Inc. All rights reserved.
+ * Copyright (C) 2003-2021 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -25,8 +25,6 @@
 
 #pragma once
 
-#include <wtf/Forward.h>
-#include <wtf/RetainPtr.h>
 #include <wtf/text/WTFString.h>
 
 #if USE(GLIB) && HAVE(GURI)
@@ -50,7 +48,7 @@
 public:
     virtual Vector<uint8_t> encodeForURLParsing(StringView) const = 0;
 protected:
-    virtual ~URLTextEncoding() { }
+    virtual ~URLTextEncoding() = default;
 };
 
 class URL {
@@ -82,7 +80,7 @@
     bool isEmpty() const;
     bool isValid() const;
 
-    // Since we overload operator NSURL* we have this to prevent accidentally using that operator
+    // Since we overload operator NSURL * we have this to prevent accidentally using that operator
     // when placing a URL in an if statment.
     operator bool() const = delete;
 
@@ -195,8 +193,9 @@
 #ifndef NDEBUG
     void print() const;
 #endif
-    WTF_EXPORT_PRIVATE void dump(PrintStream& out) const;
 
+    WTF_EXPORT_PRIVATE void dump(PrintStream&) const;
+
     template<typename Encoder> void encode(Encoder&) const;
     template<typename Decoder> static WARN_UNUSED_RETURN bool decode(Decoder&, URL&);
     template<typename Decoder> static std::optional<URL> decode(Decoder&);
@@ -214,6 +213,10 @@
 
     friend WTF_EXPORT_PRIVATE bool protocolHostAndPortAreEqual(const URL&, const URL&);
 
+#if USE(CF)
+    static RetainPtr<CFURLRef> emptyCFURL();
+#endif
+
     String m_string;
 
     unsigned m_isValid : 1;

Modified: trunk/Source/WTF/wtf/cf/CFURLExtras.cpp (285535 => 285536)


--- trunk/Source/WTF/wtf/cf/CFURLExtras.cpp	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/cf/CFURLExtras.cpp	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2013-2021 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,43 +27,63 @@
 #include <wtf/cf/CFURLExtras.h>
 
 #include <wtf/URL.h>
-#include <wtf/text/CString.h>
 
 namespace WTF {
 
-void getURLBytes(CFURLRef url, URLCharBuffer& result)
+RetainPtr<CFDataRef> bytesAsCFData(CFURLRef url)
 {
-    CFIndex bytesLength = CFURLGetBytes(url, nullptr, 0);
-    result.resize(bytesLength);
-    CFIndex finalLength = CFURLGetBytes(url, reinterpret_cast<UInt8*>(result.data()), bytesLength);
-    ASSERT_UNUSED(finalLength, finalLength == bytesLength);
+    auto bytesLength = CFURLGetBytes(url, nullptr, 0);
+    RELEASE_ASSERT(bytesLength != -1);
+    auto buffer = static_cast<uint8_t*>(malloc(bytesLength));
+    RELEASE_ASSERT(buffer);
+    CFURLGetBytes(url, buffer, bytesLength);
+    return adoptCF(CFDataCreateWithBytesNoCopy(nullptr, buffer, bytesLength, kCFAllocatorMalloc));
 }
 
-void getURLBytes(CFURLRef url, CString& result)
+String bytesAsString(CFURLRef url)
 {
-    CFIndex bytesLength = CFURLGetBytes(url, nullptr, 0);
-    char* bytes;
-    result = CString::newUninitialized(bytesLength, bytes);
-    CFIndex finalLength = CFURLGetBytes(url, reinterpret_cast<UInt8*>(bytes), bytesLength);
-    ASSERT_UNUSED(finalLength, finalLength == bytesLength);
+    auto bytesLength = CFURLGetBytes(url, nullptr, 0);
+    RELEASE_ASSERT(bytesLength != -1);
+    RELEASE_ASSERT(bytesLength <= static_cast<CFIndex>(String::MaxLength));
+    LChar* buffer;
+    auto result = String::createUninitialized(bytesLength, buffer);
+    CFURLGetBytes(url, buffer, bytesLength);
+    return result;
 }
 
-bool isCFURLSameOrigin(CFURLRef cfURL, const URL& url)
+Vector<uint8_t, URLBytesVectorInlineCapacity> bytesAsVector(CFURLRef url)
 {
-    ASSERT(url.protocolIsInHTTPFamily());
+    Vector<uint8_t, URLBytesVectorInlineCapacity> result(URLBytesVectorInlineCapacity);
+    auto bytesLength = CFURLGetBytes(url, result.data(), URLBytesVectorInlineCapacity);
+    if (bytesLength != -1)
+        result.shrink(bytesLength);
+    else {
+        bytesLength = CFURLGetBytes(url, nullptr, 0);
+        RELEASE_ASSERT(bytesLength != -1);
+        result.grow(bytesLength);
+        CFURLGetBytes(url, result.data(), bytesLength);
+    }
 
-    if (url.hasCredentials())
-        return protocolHostAndPortAreEqual(url, URL { cfURL });
+    // This may look like it copies the bytes in the vector, but due to the return value optimization it does not.
+    return result;
+}
 
-    URLCharBuffer bytes;
-    getURLBytes(cfURL, bytes);
-    StringView cfURLString { reinterpret_cast<const LChar*>(bytes.data()), static_cast<unsigned>(bytes.size()) };
+bool isSameOrigin(CFURLRef a, const URL& b)
+{
+    ASSERT(b.protocolIsInHTTPFamily());
 
-    if (!url.hasPath())
-        return StringView { url.string() } == cfURLString;
+    if (b.hasCredentials())
+        return protocolHostAndPortAreEqual(a, b);
 
-    auto urlWithoutPath = StringView { url.string() }.substring(0, url.pathStart() + 1);
-    return cfURLString.startsWith(urlWithoutPath);
+    auto aBytes = bytesAsVector(a);
+    StringView aString { aBytes.data(), static_cast<unsigned>(aBytes.size()) };
+    StringView bString { b.string() };
+
+    if (!b.hasPath())
+        return aString == bString;
+
+    unsigned afterPathSeparator = b.pathStart() + 1;
+    return aString.left(afterPathSeparator) == bString.left(afterPathSeparator);
 }
 
 }

Modified: trunk/Source/WTF/wtf/cf/CFURLExtras.h (285535 => 285536)


--- trunk/Source/WTF/wtf/cf/CFURLExtras.h	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/cf/CFURLExtras.h	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2013-2021 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,17 +26,22 @@
 #pragma once
 
 #include <wtf/Forward.h>
-#include <wtf/RetainPtr.h>
-#include <wtf/Vector.h>
 
+typedef const struct __CFData* CFDataRef;
+typedef const struct __CFURL* CFURLRef;
+
 namespace WTF {
 
-class URL;
-typedef Vector<char, 512> URLCharBuffer;
+constexpr size_t URLBytesVectorInlineCapacity = 2048;
 
-WTF_EXPORT_PRIVATE void getURLBytes(CFURLRef, URLCharBuffer&);
-WTF_EXPORT_PRIVATE void getURLBytes(CFURLRef, CString&);
+RetainPtr<CFDataRef> bytesAsCFData(CFURLRef);
+WTF_EXPORT_PRIVATE String bytesAsString(CFURLRef);
+WTF_EXPORT_PRIVATE Vector<uint8_t, URLBytesVectorInlineCapacity> bytesAsVector(CFURLRef);
 
-bool isCFURLSameOrigin(CFURLRef, const URL&);
+bool isSameOrigin(CFURLRef, const URL&);
 
 }
+
+using WTF::bytesAsCFData;
+using WTF::bytesAsString;
+using WTF::bytesAsVector;

Modified: trunk/Source/WTF/wtf/cf/URLCF.cpp (285535 => 285536)


--- trunk/Source/WTF/wtf/cf/URLCF.cpp	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/cf/URLCF.cpp	2021-11-09 22:58:40 UTC (rev 285536)
@@ -35,39 +35,47 @@
 
 URL::URL(CFURLRef url)
 {
-    if (!url) {
+    // FIXME: Why is it OK to ignore the base URL in the CFURL here?
+    if (!url)
         invalidate();
-        return;
-    }
+    else
+        *this = URLParser(bytesAsString(url)).result();
+}
 
-    // FIXME: Why is it OK to ignore base URL here?
-    CString urlBytes;
-    getURLBytes(url, urlBytes);
-    URLParser parser(urlBytes.data());
-    *this = parser.result();
+#if !USE(FOUNDATION)
+
+RetainPtr<CFURLRef> URL::emptyCFURL()
+{
+    return nullptr;
 }
 
-#if !USE(FOUNDATION)
+#endif
+
 RetainPtr<CFURLRef> URL::createCFURL() const
 {
-    RetainPtr<CFURLRef> cfURL;
+    if (isNull())
+        return nullptr;
+
+    if (isEmpty())
+        return emptyCFURL();
+
+    RetainPtr<CFURLRef> result;
     if (LIKELY(m_string.is8Bit() && m_string.isAllASCII()))
-        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, m_string.characters8(), m_string.length(), kCFStringEncodingUTF8, nullptr, true));
+        result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, m_string.characters8(), m_string.length(), kCFStringEncodingUTF8, nullptr, true));
     else {
         CString utf8 = m_string.utf8();
-        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, utf8.dataAsUInt8Ptr(), utf8.length(), kCFStringEncodingUTF8, nullptr, true));
+        result = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, utf8.dataAsUInt8Ptr(), utf8.length(), kCFStringEncodingUTF8, nullptr, true));
     }
 
-    if (protocolIsInHTTPFamily() && !isCFURLSameOrigin(cfURL.get(), *this))
+    if (protocolIsInHTTPFamily() && !isSameOrigin(result.get(), *this))
         return nullptr;
 
-    return cfURL;
+    return result;
 }
-#endif
 
 String URL::fileSystemPath() const
 {
-    RetainPtr<CFURLRef> cfURL = createCFURL();
+    auto cfURL = createCFURL();
     if (!cfURL)
         return String();
 

Modified: trunk/Source/WTF/wtf/cocoa/NSURLExtras.h (285535 => 285536)


--- trunk/Source/WTF/wtf/cocoa/NSURLExtras.h	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/cocoa/NSURLExtras.h	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005, 2007, 2012, 2014 Apple, Inc. All rights reserved.
+ * Copyright (C) 2005-2021 Apple, Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -33,7 +33,7 @@
 namespace WTF {
 
 WTF_EXPORT_PRIVATE NSString *userVisibleString(NSURL *);
-WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedString(NSString *, NSURL *baseURL); // Return value of nil means error.
+WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedString(NSString *, NSURL *ignored = nil); // Return value of nil means error.
 WTF_EXPORT_PRIVATE NSURL *URLByRemovingUserInfo(NSURL *);
 WTF_EXPORT_PRIVATE NSString *decodeHostName(NSString *); // Return value of nil means error.
 WTF_EXPORT_PRIVATE NSString *encodeHostName(NSString *); // Return value of nil means error.
@@ -41,10 +41,8 @@
 WTF_EXPORT_PRIVATE NSURL *URLWithData(NSData *, NSURL *baseURL);
 WTF_EXPORT_PRIVATE NSData *originalURLData(NSURL *);
 WTF_EXPORT_PRIVATE NSData *dataForURLComponentType(NSURL *, CFURLComponentType);
-WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedStringDeprecated(NSString *, NSURL *baseURL);
+WTF_EXPORT_PRIVATE NSURL *URLWithUserTypedStringDeprecated(NSString *);
 
-NSRange rangeOfURLScheme(NSString *);
 WTF_EXPORT_PRIVATE BOOL isUserVisibleURL(NSString *);
-WTF_EXPORT_PRIVATE BOOL looksLikeAbsoluteURL(NSString *);
 
 } // namespace WTF

Modified: trunk/Source/WTF/wtf/cocoa/NSURLExtras.mm (285535 => 285536)


--- trunk/Source/WTF/wtf/cocoa/NSURLExtras.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/cocoa/NSURLExtras.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005, 2007, 2014 Apple Inc. All rights reserved.
+ * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -32,17 +32,14 @@
 #import <mutex>
 #import <wtf/Function.h>
 #import <wtf/RetainPtr.h>
+#import <wtf/URL.h>
 #import <wtf/URLHelpers.h>
-#import <wtf/URLParser.h>
 #import <wtf/Vector.h>
 #import <wtf/cf/CFURLExtras.h>
+#import <wtf/cocoa/TypeCastsCocoa.h>
 
 namespace WTF {
 
-using namespace URLHelpers;
-
-constexpr unsigned urlBytesBufferLength = 2048;
-
 static BOOL readIDNAllowedScriptListFile(NSString *filename)
 {
     if (!filename)
@@ -67,7 +64,7 @@
         
         if (result == 1) {
             // Got a word, map to script code and put it into the array.
-            addScriptToIDNAllowedScriptList(word);
+            URLHelpers::addScriptToIDNAllowedScriptList(word);
         }
     }
     fclose(file);
@@ -100,7 +97,7 @@
 
 NSString *decodeHostName(NSString *string)
 {
-    std::optional<String> host = mapHostName(string, nullptr);
+    std::optional<String> host = URLHelpers::mapHostName(string, nullptr);
     if (!host)
         return nil;
     return !*host ? string : (NSString *)*host;
@@ -108,7 +105,7 @@
 
 NSString *encodeHostName(NSString *string)
 {
-    std::optional<String> host = mapHostName(string, decodePercentEscapes);
+    std::optional<String> host = URLHelpers::mapHostName(string, decodePercentEscapes);
     if (!host)
         return nil;
     return !*host ? string : (NSString *)*host;
@@ -126,30 +123,19 @@
     if (!URL)
         return nil;
     
-    CFRange fragRg = CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, component, nullptr);
-    if (fragRg.location == kCFNotFound)
+    CFRange range = CFURLGetByteRangeForComponent(bridge_cast(URL), component, nullptr);
+    if (range.location == kCFNotFound)
         return URL;
 
-    Vector<UInt8, urlBytesBufferLength> urlBytes(urlBytesBufferLength);
-    CFIndex numBytes = CFURLGetBytes((__bridge CFURLRef)URL, urlBytes.data(), urlBytes.size());
-    if (numBytes == -1) {
-        numBytes = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
-        urlBytes.grow(numBytes);
-        CFURLGetBytes((__bridge CFURLRef)URL, urlBytes.data(), numBytes);
-    }
+    auto bytes = bytesAsVector(bridge_cast(URL));
 
-    auto result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes.data(), fragRg.location - 1, kCFStringEncodingUTF8, nullptr));
+    auto result = adoptCF(CFURLCreateWithBytes(nullptr, bytes.data(), range.location - 1, kCFStringEncodingUTF8, nullptr));
     if (!result)
-        result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes.data(), fragRg.location - 1, kCFStringEncodingISOLatin1, nullptr));
-        
+        result = adoptCF(CFURLCreateWithBytes(nullptr, bytes.data(), range.location - 1, kCFStringEncodingISOLatin1, nullptr));
+
     return result ? result.bridgingAutorelease() : URL;
 }
 
-static NSURL *URLByRemovingResourceSpecifier(NSURL *URL)
-{
-    return URLByTruncatingOneCharacterBeforeComponent(URL, kCFURLComponentResourceSpecifier);
-}
-
 NSURL *URLWithData(NSData *data, NSURL *baseURL)
 {
     if (!data)
@@ -157,15 +143,15 @@
     
     size_t length = [data length];
     if (length > 0) {
-        // work around <rdar://4470771>: CFURLCreateAbsoluteURLWithBytes(.., TRUE) doesn't remove non-path components.
-        baseURL = URLByRemovingResourceSpecifier(baseURL);
-        
+        // Work around <rdar://4470771>: CFURLCreateAbsoluteURLWithBytes(.., TRUE) doesn't remove non-path components.
+        baseURL = URLByTruncatingOneCharacterBeforeComponent(baseURL, kCFURLComponentResourceSpecifier);
+
         const UInt8 *bytes = static_cast<const UInt8*>([data bytes]);
-        
+
         // CFURLCreateAbsoluteURLWithBytes would complain to console if we passed a path to it.
         if (bytes[0] == '/' && !baseURL)
             return nil;
-        
+
         // NOTE: We use UTF-8 here since this encoding is used when computing strings when returning URL components
         // (e.g calls to NSURL -path). However, this function is not tolerant of illegal UTF-8 sequences, which
         // could either be a malformed string or bytes in a different encoding, like shift-jis, so we fall back
@@ -177,6 +163,7 @@
     }
     return [NSURL URLWithString:@""];
 }
+
 static NSData *dataWithUserTypedString(NSString *string)
 {
     NSData *userTypedData = [string dataUsingEncoding:NSUTF8StringEncoding];
@@ -211,17 +198,17 @@
     return [NSData dataWithBytesNoCopy:outBytes length:outLength]; // adopts outBytes
 }
 
-NSURL *URLWithUserTypedString(NSString *string, NSURL *nsURL)
+NSURL *URLWithUserTypedString(NSString *string, NSURL *)
 {
     if (!string)
         return nil;
 
-    auto mappedString = mapHostNames(stringByTrimmingWhitespace(string).get(), decodePercentEscapes);
+    auto mappedString = URLHelpers::mapHostNames(stringByTrimmingWhitespace(string).get(), decodePercentEscapes);
     if (!mappedString)
         return nil;
 
     // Let's check whether the URL is bogus.
-    URL url { URL { nsURL }, mappedString };
+    URL url { URL { }, mappedString };
     if (!url.createCFURL())
         return nil;
 
@@ -231,113 +218,86 @@
     if (!data)
         return [NSURL URLWithString:@""];
 
-    return URLWithData(data, nsURL);
+    return URLWithData(data, nil);
 }
 
-NSURL *URLWithUserTypedStringDeprecated(NSString *string, NSURL *URL)
+NSURL *URLWithUserTypedStringDeprecated(NSString *string)
 {
     if (!string)
         return nil;
 
-    NSURL *result = URLWithUserTypedString(string, URL);
+    NSURL *result = URLWithUserTypedString(string);
     if (!result) {
         NSData *resultData = dataWithUserTypedString(string);
         if (!resultData)
             return [NSURL URLWithString:@""];
-        result = URLWithData(resultData, URL);
+        result = URLWithData(resultData, nil);
     }
 
     return result;
 }
 
-static BOOL hasQuestionMarkOnlyQueryString(NSURL *URL)
+static bool hasQuestionMarkOnlyQueryString(NSURL *URL)
 {
     CFRange rangeWithSeparators;
-    CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, kCFURLComponentQuery, &rangeWithSeparators);
-    if (rangeWithSeparators.location != kCFNotFound && rangeWithSeparators.length == 1)
-        return YES;
-
-    return NO;
+    CFURLGetByteRangeForComponent(bridge_cast(URL), kCFURLComponentQuery, &rangeWithSeparators);
+    return rangeWithSeparators.location != kCFNotFound && rangeWithSeparators.length == 1;
 }
 
 NSData *dataForURLComponentType(NSURL *URL, CFURLComponentType componentType)
 {
-    Vector<UInt8, urlBytesBufferLength> allBytesBuffer(urlBytesBufferLength);
-    CFIndex bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, allBytesBuffer.data(), allBytesBuffer.size());
-    if (bytesFilled == -1) {
-        CFIndex bytesToAllocate = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
-        allBytesBuffer.grow(bytesToAllocate);
-        bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, allBytesBuffer.data(), bytesToAllocate);
-    }
-    
-    const CFURLComponentType completeURL = (CFURLComponentType)-1;
-    CFRange range;
-    if (componentType != completeURL) {
-        range = CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, componentType, nullptr);
-        if (range.location == kCFNotFound)
-            return nil;
-    } else {
-        range.location = 0;
-        range.length = bytesFilled;
-    }
-    
-    NSData *componentData = [NSData dataWithBytes:allBytesBuffer.data() + range.location length:range.length]; 
-    
-    const unsigned char *bytes = static_cast<const unsigned char *>([componentData bytes]);
-    NSMutableData *resultData = [NSMutableData data];
-    // NOTE: add leading '?' to query strings non-zero length query strings.
-    // NOTE: retain question-mark only query strings.
+    CFRange range = CFURLGetByteRangeForComponent(bridge_cast(URL), componentType, nullptr);
+    if (range.location == kCFNotFound)
+        return nil;
+
+    auto bytesBuffer = bytesAsVector(bridge_cast(URL));
+    auto bytes = bytesBuffer.data() + range.location;
+
+    NSMutableData *result = [NSMutableData data];
+
+    // We add leading '?' to non-zero length query strings including question-mark only query strings.
     if (componentType == kCFURLComponentQuery) {
-        if (range.length > 0 || hasQuestionMarkOnlyQueryString(URL))
-            [resultData appendBytes:"?" length:1];    
+        if (range.length || hasQuestionMarkOnlyQueryString(URL))
+            [result appendBytes:"?" length:1];
     }
-    for (int i = 0; i < range.length; i++) {
+
+    for (CFIndex i = 0; i < range.length; i++) {
         unsigned char c = bytes[i];
-        if (c <= 0x20 || c >= 0x7f) {
-            char escaped[3];
-            escaped[0] = '%';
-            escaped[1] = upperNibbleToASCIIHexDigit(c);
-            escaped[2] = lowerNibbleToASCIIHexDigit(c);
-            [resultData appendBytes:escaped length:3];    
-        } else {
-            char b[1];
-            b[0] = c;
-            [resultData appendBytes:b length:1];    
-        }               
+        if (c > 0x20 && c < 0x7F)
+            [result appendBytes:&bytes[i] length:1];
+        else {
+            char escaped[3] = { '%', upperNibbleToASCIIHexDigit(c), lowerNibbleToASCIIHexDigit(c) };
+            [result appendBytes:escaped length:3];
+        }
     }
-    
-    return resultData;
+
+    return result;
 }
 
 static NSURL *URLByRemovingComponentAndSubsequentCharacter(NSURL *URL, CFURLComponentType component)
 {
-    CFRange range = CFURLGetByteRangeForComponent((__bridge CFURLRef)URL, component, 0);
+    CFRange range = CFURLGetByteRangeForComponent(bridge_cast(URL), component, 0);
     if (range.location == kCFNotFound)
         return URL;
-    
+
     // Remove one subsequent character.
     range.length++;
 
-    Vector<UInt8, urlBytesBufferLength> buffer(urlBytesBufferLength);
-    CFIndex numBytes = CFURLGetBytes((__bridge CFURLRef)URL, buffer.data(), buffer.size());
-    if (numBytes == -1) {
-        numBytes = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
-        buffer.grow(numBytes);
-        CFURLGetBytes((__bridge CFURLRef)URL, buffer.data(), numBytes);
-    }
-    UInt8* urlBytes = buffer.data();
-        
+    auto bytes = bytesAsVector(bridge_cast(URL));
+    auto urlBytes = bytes.data();
+    CFIndex numBytes = bytes.size();
+
     if (numBytes < range.location)
         return URL;
     if (numBytes < range.location + range.length)
         range.length = numBytes - range.location;
-        
+
     memmove(urlBytes + range.location, urlBytes + range.location + range.length, numBytes - range.location + range.length);
-    
+
     auto result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes, numBytes - range.length, kCFStringEncodingUTF8, nullptr));
     if (!result)
         result = adoptCF(CFURLCreateWithBytes(nullptr, urlBytes, numBytes - range.length, kCFStringEncodingISOLatin1, nullptr));
-                
+
     return result ? result.bridgingAutorelease() : URL;
 }
 
@@ -348,97 +308,42 @@
 
 NSData *originalURLData(NSURL *URL)
 {
-    UInt8 *buffer = (UInt8 *)malloc(urlBytesBufferLength);
-    CFIndex bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, buffer, urlBytesBufferLength);
-    if (bytesFilled == -1) {
-        CFIndex bytesToAllocate = CFURLGetBytes((__bridge CFURLRef)URL, nullptr, 0);
-        buffer = (UInt8 *)realloc(buffer, bytesToAllocate);
-        bytesFilled = CFURLGetBytes((__bridge CFURLRef)URL, buffer, bytesToAllocate);
-        ASSERT(bytesFilled == bytesToAllocate);
-    }
-    
-    // buffer is adopted by the NSData
-    NSData *data = "" dataWithBytesNoCopy:buffer length:bytesFilled freeWhenDone:YES];
-    
-    NSURL *baseURL = (__bridge NSURL *)CFURLGetBaseURL((__bridge CFURLRef)URL);
-    if (baseURL)
-        return originalURLData(URLWithData(data, baseURL));
-    return data;
+    auto data = ""
+    if (auto baseURL = bridge_cast(CFURLGetBaseURL(bridge_cast(URL))))
+        return originalURLData(URLWithData(data.get(), baseURL));
+    return data.autorelease();
 }
 
 NSString *userVisibleString(NSURL *URL)
 {
     NSData *data = ""
-    CString string(static_cast<const char*>([data bytes]), [data length]);
-    return userVisibleURL(string);
+    return URLHelpers::userVisibleURL(CString(static_cast<const char*>([data bytes]), [data length]));
 }
 
 BOOL isUserVisibleURL(NSString *string)
 {
-    BOOL valid = YES;
-    // get buffer
-    
-    char static_buffer[1024];
-    const char *p;
-    BOOL success = CFStringGetCString((__bridge CFStringRef)string, static_buffer, 1023, kCFStringEncodingUTF8);
-    p = success ? static_buffer : [string UTF8String];
-    
-    int length = strlen(p);
-    
-    // check for characters <= 0x20 or >=0x7f, %-escape sequences of %7f, and xn--, these
-    // are the things that will lead _web_userVisibleString to actually change things.
-    for (int i = 0; i < length; i++) {
-        unsigned char c = p[i];
-        // escape control characters, space, and delete
-        if (c <= 0x20 || c == 0x7f) {
-            valid = NO;
-            break;
-        } else if (c == '%' && (i + 1 < length && isASCIIHexDigit(p[i + 1])) && i + 2 < length && isASCIIHexDigit(p[i + 2])) {
-            auto u = toASCIIHexValue(p[i + 1], p[i + 2]);
-            if (u > 0x7f) {
-                valid = NO;
-                break;
-            }
-            i += 2;
-        } else {
-            // Check for "xn--" in an efficient, non-case-sensitive, way.
-            if (c == '-' && i >= 3 && (p[i - 3] | 0x20) == 'x' && (p[i - 2] | 0x20) == 'n' && p[i - 1] == '-') {
-                valid = NO;
-                break;
-            }
-        }
+    // Return true if the userVisibleString function is guaranteed to not change the passed-in URL.
+    // This function is used to optimize all the most common cases where we don't need the userVisibleString algorithm.
+
+    char buffer[1024];
+    auto success = CFStringGetCString(bridge_cast(string), reinterpret_cast<char*>(buffer), sizeof(buffer) - 1, kCFStringEncodingUTF8);
+    auto characters = success ? buffer : [string UTF8String];
+
+    // Check for control characters, %-escape sequences that are non-ASCII, and xn--: these
+    // are the things that might lead the userVisibleString function to actually change the string.
+    while (auto character = *characters++) {
+        // Control characters, including space, will be escaped by userVisibleString.
+        if (character <= 0x20 || character == 0x7F)
+            return NO;
+        // Escape sequences that expand to non-ASCII characters may be converted to non-escaped UTF-8 sequences.
+        if (character == '%' && isASCIIHexDigit(characters[0]) && isASCIIHexDigit(characters[1]) && !isASCII(toASCIIHexValue(characters[0], characters[1])))
+            return NO;
+        // If "xn--" appears, then we might need to run the IDN algorithm if it's a host name.
+        if (isASCIIAlphaCaselessEqual(character, 'x') && isASCIIAlphaCaselessEqual(characters[0], 'n') && characters[1] == '-' && characters[2] == '-')
+            return NO;
     }
-    
-    return valid;
-}
 
-NSRange rangeOfURLScheme(NSString *string)
-{
-    NSRange colon = [string rangeOfString:@":"];
-    if (colon.location != NSNotFound && colon.location > 0) {
-        NSRange scheme = {0, colon.location};
-        /*
-         This stuff is very expensive.  10-15 msec on a 2x1.2GHz.  If not cached it swamps
-         everything else when adding items to the autocomplete DB.  Makes me wonder if we
-         even need to enforce the character set here.
-         */
-        NSString *acceptableCharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-";
-        static LazyNeverDestroyed<RetainPtr<NSCharacterSet>> inverseSchemeCharacterSet;
-        static std::once_flag onceKey;
-        std::call_once(onceKey, [&] {
-            inverseSchemeCharacterSet.construct([[NSCharacterSet characterSetWithCharactersInString:acceptableCharacters] invertedSet]);
-        });
-        NSRange illegals = [string rangeOfCharacterFromSet:inverseSchemeCharacterSet.get().get() options:0 range:scheme];
-        if (illegals.location == NSNotFound)
-            return scheme;
-    }
-    return NSMakeRange(NSNotFound, 0);
+    return YES;
 }
 
-BOOL looksLikeAbsoluteURL(NSString *string)
-{
-    // Trim whitespace because _web_URLWithString allows whitespace.
-    return rangeOfURLScheme(stringByTrimmingWhitespace(string).get()).location != NSNotFound;
 }
-
-} // namespace WebCore

Modified: trunk/Source/WTF/wtf/cocoa/URLCocoa.mm (285535 => 285536)


--- trunk/Source/WTF/wtf/cocoa/URLCocoa.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/cocoa/URLCocoa.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -39,17 +39,8 @@
 namespace WTF {
 
 URL::URL(NSURL *cocoaURL)
+    : URL(bridge_cast(cocoaURL))
 {
-    if (!cocoaURL) {
-        invalidate();
-        return;
-    }
-
-    // FIXME: Why is it OK to ignore base URL here?
-    CString bytes;
-    WTF::getURLBytes(bridge_cast(cocoaURL), bytes);
-    URLParser parser(bytes.data());
-    *this = parser.result();
 }
 
 URL::operator NSURL *() const
@@ -59,28 +50,11 @@
     return createCFURL().bridgingAutorelease();
 }
 
-RetainPtr<CFURLRef> URL::createCFURL() const
+RetainPtr<CFURLRef> URL::emptyCFURL()
 {
-    if (isNull())
-        return nullptr;
-
-    if (isEmpty()) {
-        // We use the toll-free bridge between NSURL and CFURL to create a CFURLRef supporting both empty and null values.
-        return bridge_cast(adoptNS([[NSURL alloc] initWithString:@""]));
-    }
-
-    RetainPtr<CFURLRef> cfURL;
-    if (LIKELY(m_string.is8Bit() && m_string.isAllASCII()))
-        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, m_string.characters8(), m_string.length(), kCFStringEncodingUTF8, nullptr, true));
-    else {
-        CString utf8 = m_string.utf8();
-        cfURL = adoptCF(CFURLCreateAbsoluteURLWithBytes(nullptr, utf8.dataAsUInt8Ptr(), utf8.length(), kCFStringEncodingUTF8, nullptr, true));
-    }
-
-    if (protocolIsInHTTPFamily() && !WTF::isCFURLSameOrigin(cfURL.get(), *this))
-        return nullptr;
-
-    return cfURL;
+    // We use the toll-free bridge to create an empty value that is distinct from null that no CFURL function can create.
+    // FIXME: When we originally wrote this, we thought that creating empty CF URLs was valuable; can we do without it now?
+    return bridge_cast(adoptNS([[NSURL alloc] initWithString:@""]));
 }
 
 bool URL::hostIsIPAddress(StringView host)
@@ -90,7 +64,7 @@
 
 RetainPtr<id> makeNSArrayElement(const URL& vectorElement)
 {
-    return adoptNS((__bridge_transfer id)vectorElement.createCFURL().leakRef());
+    return bridge_cast(vectorElement.createCFURL());
 }
 
 std::optional<URL> makeVectorElement(const URL*, id arrayElement)

Modified: trunk/Source/WTF/wtf/mac/FileSystemMac.mm (285535 => 285536)


--- trunk/Source/WTF/wtf/mac/FileSystemMac.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/mac/FileSystemMac.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -37,8 +37,8 @@
 void FileSystem::setMetadataURL(const String& path, const String& metadataURLString, const String& referrer)
 {
     String urlString;
-    if (NSURL *url = "" nil))
-        urlString = WTF::userVisibleString(WTF::URLByRemovingUserInfo(url));
+    if (NSURL *url = ""
+        urlString = userVisibleString(URLByRemovingUserInfo(url));
     else
         urlString = metadataURLString;
 

Modified: trunk/Source/WTF/wtf/text/cocoa/StringCocoa.mm (285535 => 285536)


--- trunk/Source/WTF/wtf/text/cocoa/StringCocoa.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WTF/wtf/text/cocoa/StringCocoa.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2018 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2021 Apple Inc. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -22,17 +22,20 @@
 #import <wtf/text/WTFString.h>
 
 #import <CoreFoundation/CFString.h>
+#import <wtf/cocoa/TypeCastsCocoa.h>
 
 namespace WTF {
 
 #if HAVE(SAFARI_FOR_WEBKIT_DEVELOPMENT_REQUIRING_EXTRA_SYMBOLS)
 String::String(NSString *string)
-    : String((__bridge CFStringRef)string) { }
+    : String(bridge_cast(string))
+{
+}
 #endif
 
 RetainPtr<id> makeNSArrayElement(const String& vectorElement)
 {
-    return adoptNS((__bridge_transfer id)vectorElement.createCFString().leakRef());
+    return bridge_cast(vectorElement.createCFString());
 }
 
 std::optional<String> makeVectorElement(const String*, id arrayElement)

Modified: trunk/Source/WebKit/ChangeLog (285535 => 285536)


--- trunk/Source/WebKit/ChangeLog	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/ChangeLog	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,3 +1,49 @@
+2021-10-28  Darin Adler  <da...@apple.com>
+
+        [CF] Reduce duplication and unneeded buffer allocations and copying in URL code, also remove unused methods and functions
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+
+        Reviewed by Alex Christensen.
+
+        * Shared/API/c/cf/WKURLCF.mm:
+        (WKURLCreateWithCFURL): Use bytesAsString, saving creation and destruction
+        of a CString each time this is called.
+
+        * Shared/Cocoa/ArgumentCodersCocoa.mm:
+        (-[WKSecureCodingURLWrapper encodeWithCoder:]): Use bytesAsVector.
+
+        * Shared/Cocoa/WKNSURLExtras.h: Removed unused methods
+        +[NSURL _web_URLWithWTFString:relativeToURL:] and
+        -[NSURL _web_originalDataAsWTFString].
+
+        * Shared/Cocoa/WKNSURLExtras.mm:
+        (+[NSURL _web_URLWithWTFString:relativeToURL:]): Deleted.
+        (-[NSURL _web_originalDataAsWTFString]): Deleted.
+
+        * Shared/Cocoa/WKNSURLRequest.mm:
+        (-[WKNSURLRequest URL]): Removed unneeded call to +[NSURL _web_URLWithWTFString:]
+        because this code is converting a WTF::URL to an NSURL, which can use the conversion
+        operator in the WTF::URL class.
+
+        * Shared/cf/ArgumentCodersCF.cpp:
+        (IPC::ArgumentCoder<CFURLRef>::encode): Use bytesAsVector.
+
+        * UIProcess/API/Cocoa/WKBrowsingContextController.mm:
+        (-[WKBrowsingContextController loadFileURL:restrictToFilesWithin:userData:]):
+        Use bytesAsString and bridge_cast.
+        (-[WKBrowsingContextController loadHTMLString:baseURL:userData:]): Ditto.
+        (-[WKBrowsingContextController loadData:MIMEType:textEncodingName:baseURL:userData:]): Ditto.
+        (setUpPagePolicyClient): Removed unneeded call to +[NSURL _web_URLWithWTFString:]
+        because this code is converting a WTF::URL to an NSURL, which can use the conversion
+        operator in the WTF::URL class.
+
+        * UIProcess/Cocoa/LegacyDownloadClient.mm:
+        (WebKit::LegacyDownloadClient::willSendRequest): Removed unneeded call to
+        +[NSURL _web_URLWithWTFString:] because this code is converting a WTF::URL to an NSURL,
+        which can use the conversion operator in the WTF::URL class.
+        * WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm:
+        (-[WKWebProcessPlugInFrame URL]): Ditto.
+
 2021-11-09  Chris Dumez  <cdu...@apple.com>
 
         BroadcastChannel is still disabled in service workers

Modified: trunk/Source/WebKit/Shared/API/c/cf/WKURLCF.mm (285535 => 285536)


--- trunk/Source/WebKit/Shared/API/c/cf/WKURLCF.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/Shared/API/c/cf/WKURLCF.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -30,7 +30,6 @@
 #import "WKNSURL.h"
 #import <objc/runtime.h>
 #import <wtf/cf/CFURLExtras.h>
-#import <wtf/text/CString.h>
 
 static inline Class wkNSURLClass()
 {
@@ -45,16 +44,14 @@
 WKURLRef WKURLCreateWithCFURL(CFURLRef cfURL)
 {
     if (!cfURL)
-        return 0;
+        return nullptr;
 
     // Since WKNSURL is an internal class with no subclasses, we can do a simple equality check.
     if (object_getClass((__bridge NSURL *)cfURL) == wkNSURLClass())
         return WebKit::toAPI(static_cast<API::URL*>(&[(WKNSURL *)(__bridge NSURL *)CFRetain(cfURL) _apiObject]));
 
-    CString urlBytes;
-    WTF::getURLBytes(cfURL, urlBytes);
-
-    return WebKit::toCopiedURLAPI(urlBytes.data());
+    // FIXME: Why is it OK to ignore the base URL in the CFURL here?
+    return WebKit::toCopiedURLAPI(bytesAsString(cfURL));
 }
 
 CFURLRef WKURLCopyCFURL(CFAllocatorRef allocatorRef, WKURLRef URLRef)

Modified: trunk/Source/WebKit/Shared/Cocoa/ArgumentCodersCocoa.mm (285535 => 285536)


--- trunk/Source/WebKit/Shared/Cocoa/ArgumentCodersCocoa.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/Shared/Cocoa/ArgumentCodersCocoa.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -104,9 +104,8 @@
     if (hasBaseURL)
         [coder encodeObject:baseURL forKey:baseURLKey];
 
-    WTF::URLCharBuffer urlBytes;
-    WTF::getURLBytes(bridge_cast(m_wrappedURL.get()), urlBytes);
-    [coder encodeBytes:urlBytes.data() length:urlBytes.size()];
+    auto bytes = bytesAsVector(bridge_cast(m_wrappedURL.get()));
+    [coder encodeBytes:bytes.data() length:bytes.size()];
 }
 
 - (_Nullable instancetype)initWithCoder:(NSCoder *)coder

Modified: trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.h (285535 => 285536)


--- trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.h	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.h	2021-11-09 22:58:40 UTC (rev 285536)
@@ -28,8 +28,5 @@
 @interface NSURL (WKExtras)
 
 + (instancetype)_web_URLWithWTFString:(const String&)string;
-+ (instancetype)_web_URLWithWTFString:(const String&)string relativeToURL:(NSURL *)baseURL;
 
-- (String)_web_originalDataAsWTFString;
-
 @end

Modified: trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.mm (285535 => 285536)


--- trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/Shared/Cocoa/WKNSURLExtras.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -27,9 +27,6 @@
 #import "WKNSURLExtras.h"
 
 #import <wtf/URL.h>
-#import <wtf/cf/CFURLExtras.h>
-#import <wtf/text/CString.h>
-#import <wtf/text/WTFString.h>
 
 @implementation NSURL (WKExtras)
 
@@ -39,18 +36,4 @@
     return (NSURL *)url;
 }
 
-+ (instancetype)_web_URLWithWTFString:(const String&)string relativeToURL:(NSURL *)baseURL
-{
-    URL url { URL { baseURL }, string };
-    return (NSURL *)url;
-}
-
-- (String)_web_originalDataAsWTFString
-{
-    // FIXME: Why is it OK to ignore base URL here?
-    CString originalData;
-    WTF::getURLBytes((__bridge CFURLRef)self, originalData);
-    return String::fromUTF8(originalData);
-}
-
 @end

Modified: trunk/Source/WebKit/Shared/Cocoa/WKNSURLRequest.mm (285535 => 285536)


--- trunk/Source/WebKit/Shared/Cocoa/WKNSURLRequest.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/Shared/Cocoa/WKNSURLRequest.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -37,7 +37,7 @@
 
 - (NSURL *)URL
 {
-    return [NSURL _web_URLWithWTFString:static_cast<API::URLRequest*>(&self._apiObject)->resourceRequest().url().string()];
+    return static_cast<API::URLRequest*>(&self._apiObject)->resourceRequest().url();
 }
 
 #pragma mark NSCopying protocol implementation

Modified: trunk/Source/WebKit/Shared/cf/ArgumentCodersCF.cpp (285535 => 285536)


--- trunk/Source/WebKit/Shared/cf/ArgumentCodersCF.cpp	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/Shared/cf/ArgumentCodersCF.cpp	2021-11-09 22:58:40 UTC (rev 285536)
@@ -643,9 +643,7 @@
     if (baseURL)
         encoder << baseURL;
 
-    WTF::URLCharBuffer urlBytes;
-    WTF::getURLBytes(url, urlBytes);
-    encoder << IPC::DataReference(reinterpret_cast<const uint8_t*>(urlBytes.data()), urlBytes.size());
+    encoder << IPC::DataReference(bytesAsVector(url));
 }
 
 template void ArgumentCoder<CFURLRef>::encode<Encoder>(Encoder&, CFURLRef);

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm (285535 => 285536)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -60,6 +60,7 @@
 #import <wtf/BlockPtr.h>
 #import <wtf/NeverDestroyed.h>
 #import <wtf/WeakObjCPtr.h>
+#import <wtf/cf/CFURLExtras.h>
 
 NSString * const WKActionIsMainFrameKey = @"WKActionIsMainFrameKey";
 NSString * const WKActionNavigationTypeKey = @"WKActionNavigationTypeKey";
@@ -157,7 +158,7 @@
     if (userData)
         wkUserData = WebKit::ObjCObjectGraph::create(userData);
 
-    _page->loadFile([URL _web_originalDataAsWTFString], [allowedDirectory _web_originalDataAsWTFString], wkUserData.get());
+    _page->loadFile(bytesAsString(bridge_cast(URL)), bytesAsString(bridge_cast(allowedDirectory)), wkUserData.get());
 }
 
 - (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL
@@ -172,7 +173,7 @@
         wkUserData = WebKit::ObjCObjectGraph::create(userData);
 
     NSData *data = "" dataUsingEncoding:NSUTF8StringEncoding];
-    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, "text/html"_s, "UTF-8"_s, [baseURL _web_originalDataAsWTFString], wkUserData.get());
+    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, "text/html"_s, "UTF-8"_s, bytesAsString(bridge_cast(baseURL)), wkUserData.get());
 }
 
 - (void)loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL
@@ -192,7 +193,7 @@
     if (userData)
         wkUserData = WebKit::ObjCObjectGraph::create(userData);
 
-    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, encodingName, [baseURL _web_originalDataAsWTFString], wkUserData.get());
+    _page->loadData({ static_cast<const uint8_t*>(data.bytes), data.length }, MIMEType, encodingName, bytesAsString(bridge_cast(baseURL)), wkUserData.get());
 }
 
 - (void)stopLoading
@@ -508,7 +509,7 @@
 
             if (originatingFrame) {
                 actionDictionary = adoptNS([actionDictionary mutableCopy]);
-                [(NSMutableDictionary *)actionDictionary.get() setObject:[NSURL _web_URLWithWTFString:WebKit::toImpl(originatingFrame)->url().string()] forKey:WKActionOriginatingFrameURLKey];
+                [(NSMutableDictionary *)actionDictionary.get() setObject:(NSURL *)WebKit::toImpl(originatingFrame)->url() forKey:WKActionOriginatingFrameURLKey];
             }
             
             [policyDelegate browsingContextController:browsingContext decidePolicyForNavigationAction:actionDictionary.get() decisionHandler:makePolicyDecisionBlock(listener).get()];

Modified: trunk/Source/WebKit/UIProcess/Cocoa/LegacyDownloadClient.mm (285535 => 285536)


--- trunk/Source/WebKit/UIProcess/Cocoa/LegacyDownloadClient.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/UIProcess/Cocoa/LegacyDownloadClient.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -272,7 +272,7 @@
 void LegacyDownloadClient::willSendRequest(DownloadProxy& downloadProxy, WebCore::ResourceRequest&& request, const WebCore::ResourceResponse&, CompletionHandler<void(WebCore::ResourceRequest&&)>&& completionHandler)
 {
     if (m_delegateMethods.downloadDidReceiveServerRedirectToURL)
-        [m_delegate _download:[_WKDownload downloadWithDownload:wrapper(downloadProxy)] didReceiveServerRedirectToURL:[NSURL _web_URLWithWTFString:request.url().string()]];
+        [m_delegate _download:[_WKDownload downloadWithDownload:wrapper(downloadProxy)] didReceiveServerRedirectToURL:request.url()];
 
     completionHandler(WTFMove(request));
 }

Modified: trunk/Source/WebKit/WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm (285535 => 285536)


--- trunk/Source/WebKit/WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKit/WebProcess/InjectedBundle/API/Cocoa/WKWebProcessPlugInFrame.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -110,7 +110,7 @@
 
 - (NSURL *)URL
 {
-    return [NSURL _web_URLWithWTFString:_frame->url().string()];
+    return _frame->url();
 }
 
 - (NSArray *)childFrames

Modified: trunk/Source/WebKitLegacy/mac/ChangeLog (285535 => 285536)


--- trunk/Source/WebKitLegacy/mac/ChangeLog	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKitLegacy/mac/ChangeLog	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,3 +1,50 @@
+2021-10-28  Darin Adler  <da...@apple.com>
+
+        [CF] Reduce duplication and unneeded buffer allocations and copying in URL code, also remove unused methods and functions
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+
+        Reviewed by Alex Christensen.
+
+        * Misc/WebNSURLExtras.h: Tweaked comments a bit. No need to say methods are "new", since
+        that won't be true in the future. Removed unused methods
+        +[NSURL _web_URLWithUserTypedString:relativeToURL:],
+        +[NSURL _webkit_URLWithUserTypedString:relativeToURL:],
+        +[NSURL _web_URLWithData:], +[NSURL _web_URLWithData:relatveToURL:].
+        Wanted to remove even more nearly unused methods: many were used only
+        inside the WebKit project, in legacy plug-in code, and some seemed unused,
+        but it wasn't easy for me to quickly verify that.
+
+        * Misc/WebNSURLExtras.mm: Removed "using namespace WebCore" and
+        "using namespace WTF".
+        (+[NSURL _web_URLWithUserTypedString:relativeToURL:]): Deleted.
+        (+[NSURL _web_URLWithUserTypedString:]): Use WTF prefix explicitly.
+        (+[NSURL _webkit_URLWithUserTypedString:relativeToURL:]): Deleted.
+        (+[NSURL _webkit_URLWithUserTypedString:]): Use WTF prefix explicitly.
+        (+[NSURL _web_URLWithDataAsString:]): Removed special case for nil since the code
+        will do the right thing with nil without an explicit check.
+        (+[NSURL _web_URLWithDataAsString:relativeToURL]): Ditto. Also formatted the code
+        as a one-liner.
+        (+[NSURL _web_URLWithData:]): Deleted.
+        (+[NSURL _web_URLWithData:relativeToURL:]): Deleted.
+        (-[NSURL _web_originalData]): Use WTF prefix explicitly.
+        (-[NSURL _web_originalDataAsString]): Ditto.
+        (-[NSURL _web_isEmpty]): Use bridge_cast and make code style checker happy by using
+        "!" instead of "== 0".
+        (-[NSURL _web_URLCString]): Use WTF prefix explicitly.
+        (-[NSURL _webkit_canonicalize]): Use WebCore prefix explicitly.
+        (-[NSURL _webkit_URLByRemovingFragment]): Use WTF prefix explicitly.
+        (-[NSURL _web_schemeSeparatorWithoutColon]): Deleted.
+        (-[NSURL _web_dataForURLComponentType:]): Deleted.
+        (-[NSURL _web_hostData]): Use WTF prefix explicitly. Rearranged for clarity and
+        slightly improved efficiency as well.
+        (-[NSString _web_isUserVisibleURL]): Use WTF prefix explicitly.
+        (-[NSString _webkit_stringByReplacingValidPercentEscapes]): Use WebCore prefix
+        explicitly.
+        (-[NSString _web_decodeHostName]): Use WTF prefix explicitly.
+        (-[NSString _web_encodeHostName]): Ditto.
+        (-[NSString _webkit_decodeHostName]): Ditto.
+        (-[NSString _webkit_encodeHostName]): Ditto.
+
 2021-11-06  David Kilzer  <ddkil...@apple.com>
 
         Remove empty directories from from svn.webkit.org repository as of r285357

Modified: trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.h (285535 => 285536)


--- trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.h	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.h	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2009, 2014 Apple Inc. All rights reserved.
+ * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -28,30 +28,23 @@
 
 #import <Foundation/Foundation.h>
 
-// FIXME: Change method names back to _web_ from _webkit_ when identically-named
-// methods are no longer present in Foundation.
+// FIXME: Consider renaming to _web_ from _webkit_ once identically-named methods are no longer present in Foundation.
 
 @interface NSURL (WebNSURLExtras)
 
-// Deprecated as it ignores URL parsing error.
-// Please use the _webkit_ counterparts.
+// Deprecated, as it ignores URL parsing errors.
+// Please use the _webkit_URLWithUserTypedString instead.
 + (NSURL *)_web_URLWithUserTypedString:(NSString *)string;
-+ (NSURL *)_web_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL;
 
-// New SPI.
 // Return value of nil means error in URL parsing.
 + (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string;
-+ (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL;
 
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string;
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string relativeToURL:(NSURL *)baseURL;
 
-+ (NSURL *)_web_URLWithData:(NSData *)data;
-+ (NSURL *)_web_URLWithData:(NSData *)data relativeToURL:(NSURL *)baseURL;
-
 - (NSData *)_web_originalData;
 - (NSString *)_web_originalDataAsString;
-- (const char *)_web_URLCString;
+- (const char*)_web_URLCString;
 
 - (NSString *)_web_hostString;
 
@@ -78,14 +71,16 @@
 
 - (BOOL)_web_isUserVisibleURL;
 
-// Deprecated as it ignores URL parsing error.
-// Please use the _webkit_ counterparts.
-// turns funny-looking ASCII form into Unicode, returns self if no decoding needed, convenient cover
+// Deprecated as it ignores URL parsing errors.
+// Please use _webkit_decodeHostName instead.
+// Turns funny-looking ASCII form into Unicode, returns self if no decoding needed.
 - (NSString *)_web_decodeHostName;
-// turns Unicode into funny-looking ASCII form, returns self if no decoding needed, convenient cover
+
+// Deprecated as it ignores URL parsing errors.
+// Please use the _webkit_encodeHostName instead.
+// Turns Unicode into funny-looking ASCII form, returns self if no encoding needed.
 - (NSString *)_web_encodeHostName;
 
-// New SPI.
 // Return value of nil means error in URL parsing.
 - (NSString *)_webkit_decodeHostName;
 - (NSString *)_webkit_encodeHostName;

Modified: trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.mm (285535 => 285536)


--- trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Source/WebKitLegacy/mac/Misc/WebNSURLExtras.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005, 2007, 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2005-2021 Apple Inc. All rights reserved.
  * Copyright (C) 2006 Alexey Proskuryakov (a...@nypop.com)
  *
  * Redistribution and use in source and binary forms, with or without
@@ -41,70 +41,38 @@
 #import <wtf/Assertions.h>
 #import <wtf/URL.h>
 #import <wtf/cocoa/NSURLExtras.h>
+#import <wtf/cocoa/TypeCastsCocoa.h>
 
-using namespace WebCore;
-using namespace WTF;
-
-#define URL_BYTES_BUFFER_LENGTH 2048
-
 @implementation NSURL (WebNSURLExtras)
 
-+ (NSURL *)_web_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL
-{
-    return URLWithUserTypedStringDeprecated(string, URL);
-}
-
 + (NSURL *)_web_URLWithUserTypedString:(NSString *)string
 {
-    return URLWithUserTypedStringDeprecated(string, nil);
+    return WTF::URLWithUserTypedStringDeprecated(string);
 }
 
-+ (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL
-{
-    return URLWithUserTypedString(string, URL);
-}
-
 + (NSURL *)_webkit_URLWithUserTypedString:(NSString *)string
 {
-    return URLWithUserTypedString(string, nil);
+    return WTF::URLWithUserTypedString(string);
 }
 
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string
 {
-    if (string == nil) {
-        return nil;
-    }
     return [self _web_URLWithDataAsString:string relativeToURL:nil];
 }
 
 + (NSURL *)_web_URLWithDataAsString:(NSString *)string relativeToURL:(NSURL *)baseURL
 {
-    if (string == nil) {
-        return nil;
-    }
-    string = [string _webkit_stringByTrimmingWhitespace];
-    NSData *data = "" dataUsingEncoding:NSISOLatin1StringEncoding];
-    return URLWithData(data, baseURL);
+    return WTF::URLWithData([[string _webkit_stringByTrimmingWhitespace] dataUsingEncoding:NSISOLatin1StringEncoding], baseURL);
 }
 
-+ (NSURL *)_web_URLWithData:(NSData *)data
-{
-    return URLWithData(data, nil);
-}      
-
-+ (NSURL *)_web_URLWithData:(NSData *)data relativeToURL:(NSURL *)baseURL
-{
-    return URLWithData(data, baseURL);
-}
-
 - (NSData *)_web_originalData
 {
-    return originalURLData(self);
+    return WTF::originalURLData(self);
 }
 
 - (NSString *)_web_originalDataAsString
 {
-    return adoptNS([[NSString alloc] initWithData:originalURLData(self) encoding:NSISOLatin1StringEncoding]).autorelease();
+    return adoptNS([[NSString alloc] initWithData:WTF::originalURLData(self) encoding:NSISOLatin1StringEncoding]).autorelease();
 }
 
 - (NSString *)_web_userVisibleString
@@ -114,22 +82,22 @@
 
 - (BOOL)_web_isEmpty
 {
-    if (!CFURLGetBaseURL((CFURLRef)self))
-        return CFURLGetBytes((CFURLRef)self, NULL, 0) == 0;
-    return [originalURLData(self) length] == 0;
+    if (!CFURLGetBaseURL(bridge_cast(self)))
+        return !CFURLGetBytes(bridge_cast(self), nullptr, 0);
+    return ![WTF::originalURLData(self) length];
 }
 
-- (const char *)_web_URLCString
+- (const char*)_web_URLCString
 {
     NSMutableData *data = "" data];
-    [data appendData:originalURLData(self)];
+    [data appendData:WTF::originalURLData(self)];
     [data appendBytes:"\0" length:1];
-    return (const char *)[data bytes];
+    return (const char*)[data bytes];
  }
 
 - (NSURL *)_webkit_canonicalize
 {
-    return URLByCanonicalizingURL(self);
+    return WebCore::URLByCanonicalizingURL(self);
 }
 
 - (NSURL *)_webkit_canonicalize_with_wtf
@@ -140,7 +108,7 @@
 
 - (NSURL *)_webkit_URLByRemovingFragment 
 {
-    return URLByTruncatingOneCharacterBeforeComponent(self, kCFURLComponentFragment);
+    return WTF::URLByTruncatingOneCharacterBeforeComponent(self, kCFURLComponentFragment);
 }
 
 - (NSURL *)_web_URLByRemovingUserInfo
@@ -163,27 +131,6 @@
     return [[self _web_originalDataAsString] _webkit_isFileURL];
 }
 
--(NSData *)_web_schemeSeparatorWithoutColon
-{
-    NSData *result = nil;
-    CFRange rangeWithSeparators;
-    CFRange range = CFURLGetByteRangeForComponent((CFURLRef)self, kCFURLComponentScheme, &rangeWithSeparators);
-    if (rangeWithSeparators.location != kCFNotFound) {
-        NSString *absoluteString = [self absoluteString];
-        NSRange separatorsRange = NSMakeRange(range.location + range.length + 1, rangeWithSeparators.length - range.length - 1);
-        if (separatorsRange.location + separatorsRange.length <= [absoluteString length]) {
-            NSString *slashes = [absoluteString substringWithRange:separatorsRange];
-            result = [slashes dataUsingEncoding:NSISOLatin1StringEncoding];
-        }
-    }
-    return result;
-}
-
--(NSData *)_web_dataForURLComponentType:(CFURLComponentType)componentType
-{
-    return WTF::dataForURLComponentType(self, componentType);
-}
-
 -(NSData *)_web_schemeData
 {
     return WTF::dataForURLComponentType(self, kCFURLComponentScheme);
@@ -192,11 +139,11 @@
 -(NSData *)_web_hostData
 {
     NSData *result = WTF::dataForURLComponentType(self, kCFURLComponentHost);
-    NSData *scheme = [self _web_schemeData];
-    // Take off localhost for file
-    if ([scheme _web_isCaseInsensitiveEqualToCString:"file"]) {
-        return ([result _web_isCaseInsensitiveEqualToCString:"localhost"]) ? nil : result;
-    }
+
+    // Take off localhost for file.
+    if ([result _web_isCaseInsensitiveEqualToCString:"localhost"] && [[self _web_schemeData] _web_isCaseInsensitiveEqualToCString:"file"])
+        return nil;
+
     return result;
 }
 
@@ -223,7 +170,7 @@
 
 - (BOOL)_web_isUserVisibleURL
 {
-    return isUserVisibleURL(self);
+    return WTF::isUserVisibleURL(self);
 }
 
 - (BOOL)_webkit_isJavaScriptURL
@@ -238,7 +185,7 @@
 
 - (NSString *)_webkit_stringByReplacingValidPercentEscapes
 {
-    return decodeURLEscapeSequences(String(self));
+    return WebCore::decodeURLEscapeSequences(String(self));
 }
 
 - (NSString *)_webkit_scriptIfJavaScriptURL
@@ -251,24 +198,24 @@
 
 - (NSString *)_web_decodeHostName
 {
-    NSString *name = decodeHostName(self);
+    NSString *name = WTF::decodeHostName(self);
     return !name ? self : name;
 }
 
 - (NSString *)_web_encodeHostName
 {
-    NSString *name = encodeHostName(self);
+    NSString *name = WTF::encodeHostName(self);
     return !name ? self : name;
 }
 
 - (NSString *)_webkit_decodeHostName
 {
-    return decodeHostName(self);
+    return WTF::decodeHostName(self);
 }
 
 - (NSString *)_webkit_encodeHostName
 {
-    return encodeHostName(self);
+    return WTF::encodeHostName(self);
 }
 
 -(NSRange)_webkit_rangeOfURLScheme

Modified: trunk/Tools/ChangeLog (285535 => 285536)


--- trunk/Tools/ChangeLog	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Tools/ChangeLog	2021-11-09 22:58:40 UTC (rev 285536)
@@ -1,3 +1,13 @@
+2021-10-28  Darin Adler  <da...@apple.com>
+
+        [CF] Reduce duplication and unneeded buffer allocations and copying in URL code, also remove unused methods and functions
+        https://bugs.webkit.org/show_bug.cgi?id=232220
+
+        Reviewed by Alex Christensen.
+
+        * TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm:
+        (TestWebKitAPI::TEST): Removed extra argument to URLWithUserTypedString/Deprecated.
+
 2021-11-09  Myles C. Maxfield  <mmaxfi...@apple.com>
 
         [WebGPU] Stub out methods in WebGPU.framework

Modified: trunk/Tools/TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm (285535 => 285536)


--- trunk/Tools/TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm	2021-11-09 22:25:51 UTC (rev 285535)
+++ trunk/Tools/TestWebKitAPI/Tests/WTF/cocoa/URLExtras.mm	2021-11-09 22:58:40 UTC (rev 285536)
@@ -249,10 +249,10 @@
 
 TEST(WTF_URLExtras, URLExtras_Nil)
 {
-    NSURL *url1 = WTF::URLWithUserTypedString(nil, nil);
+    NSURL *url1 = WTF::URLWithUserTypedString(nil);
     EXPECT_TRUE(url1 == nil);
 
-    NSURL *url2 = WTF::URLWithUserTypedStringDeprecated(nil, nil);
+    NSURL *url2 = WTF::URLWithUserTypedStringDeprecated(nil);
     EXPECT_TRUE(url2 == nil);
 }
 
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to