Skip to content

Commit b2e4183

Browse files
Merge pull request #1174 from lightpanda-io/nikneym/url-can-parse
Add `URL.canParse`
2 parents 1015fc0 + 2e6ec1e commit b2e4183

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/browser/url/url.zig

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,18 @@ pub const URL = struct {
132132
return ada.clearHash(self.internal);
133133
}
134134

135+
/// Returns a boolean indicating whether or not an absolute URL,
136+
/// or a relative URL combined with a base URL, are parsable and valid.
137+
pub fn static_canParse(url: ConstructorArg, maybe_base: ?ConstructorArg, page: *Page) !bool {
138+
const url_str = try url.toString(page);
139+
140+
if (maybe_base) |base| {
141+
return ada.canParseWithBase(url_str, try base.toString(page));
142+
}
143+
144+
return ada.canParse(url_str);
145+
}
146+
135147
/// Alias to get_href.
136148
pub fn _toString(self: *const URL, page: *Page) ![]const u8 {
137149
return self.get_href(page);

src/tests/url/url.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,11 @@
9999
_ = new URL("://foo.bar/path?query#fragment");
100100
});
101101
</script>
102+
103+
<script id=URL.canParse>
104+
testing.expectEqual(true, URL.canParse("https://lightpanda.io"));
105+
testing.expectEqual(false, URL.canParse("://lightpanda.io"));
106+
107+
testing.expectEqual(true, URL.canParse("/home", "https://lightpanda.io"));
108+
testing.expectEqual(false, URL.canParse("lightpanda.io", "https"));
109+
</script>

vendor/ada/root.zig

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ pub fn parseWithBase(input: []const u8, base: []const u8) ParseError!URL {
3333
return url;
3434
}
3535

36+
pub inline fn canParse(input: []const u8) bool {
37+
return c.ada_can_parse(input.ptr, input.len);
38+
}
39+
40+
pub inline fn canParseWithBase(input: []const u8, base: []const u8) bool {
41+
return c.ada_can_parse_with_base(input.ptr, input.len, base.ptr, base.len);
42+
}
43+
3644
pub inline fn getComponents(url: URL) *const URLComponents {
3745
return c.ada_get_components(url);
3846
}

0 commit comments

Comments
 (0)