Skip to content

Commit

Permalink
Bug 1823354 - Implement URL.canParse() r=emilio
Browse files Browse the repository at this point in the history
Implemented URL.canParse() static function for checking if a URL can be
parsed (instead of having to try wrap the constructor).

Avoids using an ErrorResult/Throws as it is not specified, and for
performance (see spec issue from linked PR).

All WPT tests for it now pass.

Spec PR: whatwg/url#763
WPT tests: https://wpt.fyi/results/url/url-statics-canparse.any.html

Differential Revision: https://phabricator.services.mozilla.com/D179617
  • Loading branch information
CanadaHonk committed May 31, 2023
1 parent b6018cc commit b4bb5c7
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 44 deletions.
28 changes: 28 additions & 0 deletions dom/url/URL.cpp
Expand Up @@ -131,6 +131,34 @@ bool URL::IsValidURL(const GlobalObject& aGlobal, const nsAString& aURL,
return URLWorker::IsValidURL(aGlobal, aURL, aRv);
}

bool URL::CanParse(const GlobalObject& aGlobal, const nsAString& aURL,
const Optional<nsAString>& aBase) {
nsCOMPtr<nsIURI> baseUri;
if (aBase.WasPassed()) {
// Don't use NS_ConvertUTF16toUTF8 because that doesn't let us handle OOM.
nsAutoCString base;
if (!AppendUTF16toUTF8(aBase.Value(), base, fallible)) {
// Just return false with OOM errors as no ErrorResult.
return false;
}

nsresult rv = NS_NewURI(getter_AddRefs(baseUri), base);
if (NS_FAILED(rv)) {
// Invalid base URL, return false.
return false;
}
}

nsAutoCString urlStr;
if (!AppendUTF16toUTF8(aURL, urlStr, fallible)) {
// Just return false with OOM errors as no ErrorResult.
return false;
}

nsCOMPtr<nsIURI> uri;
return NS_SUCCEEDED(NS_NewURI(getter_AddRefs(uri), urlStr, nullptr, baseUri));
}

URLSearchParams* URL::SearchParams() {
CreateSearchParamsIfNeeded();
return mSearchParams;
Expand Down
3 changes: 3 additions & 0 deletions dom/url/URL.h
Expand Up @@ -69,6 +69,9 @@ class URL final : public URLSearchParamsObserver, public nsWrapperCache {
static bool IsValidURL(const GlobalObject& aGlobal, const nsAString& aURL,
ErrorResult& aRv);

static bool CanParse(const GlobalObject& aGlobal, const nsAString& aURL,
const Optional<nsAString>& aBase);

void GetHref(nsAString& aHref) const;

void SetHref(const nsAString& aHref, ErrorResult& aRv);
Expand Down
2 changes: 2 additions & 0 deletions dom/webidl/URL.webidl
Expand Up @@ -19,6 +19,8 @@ interface URL {
[Throws]
constructor(USVString url, optional USVString base);

static boolean canParse(USVString url, optional USVString base);

[SetterThrows]
stringifier attribute USVString href;
readonly attribute USVString origin;
Expand Down
44 changes: 0 additions & 44 deletions testing/web-platform/meta/url/url-statics-canparse.any.js.ini

This file was deleted.

0 comments on commit b4bb5c7

Please sign in to comment.