Something went wrong. Try again.
A URI parser and formatter for Zig, modelled on Python's hyperlink package, with LDAP URLs, file: URIs and sdns:// DNS stamps beside it.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `Uri`: an immutable, parsed URI reference.
const std = @import("std");
const build_options = @import("build_options");const components = @import("components.zig");const file_mod = @import("file.zig");const format_mod = @import("format.zig");const normalize_mod = @import("normalize.zig");const relativize_mod = @import("relativize.zig");const parse_mod = @import("parse.zig");const query_mod = @import("query.zig");const schemes = @import("schemes.zig");
const Allocator = std.mem.Allocator;const Components = components.Components;const Host = components.Host;const QueryParam = components.QueryParam;const Writer = std.Io.Writer;
pub const Error = parse_mod.Error;
/// A parsed URI reference.////// Every component is stored *decoded*: the path of `http://x/a%2Fb` is the/// single segment `"a/b"`, and `toText` re-escapes it back to `a%2Fb`. That/// makes the fields directly usable without a decoding step, at the cost of/// output being canonically rather than identically escaped — `%2f` comes back/// as `%2F`, and `%41` comes back as `A`.////// A `Uri` owns an arena holding all of its strings, so every accessor is/// allocation-free. It is immutable: `replace`, `child`, `click`, `set` and/// friends each return a brand-new `Uri` with its own arena, which the caller/// must `deinit`.pub const Uri = struct { arena: *std.heap.ArenaAllocator,
scheme: ?[]const u8 = null, username: ?[]const u8 = null, password: ?[]const u8 = null, host: ?Host = null, port: ?u16 = null, rooted: bool = false, path: []const []const u8 = &.{}, query: []const QueryParam = &.{}, fragment: ?[]const u8 = null,
pub const ParseOptions = parse_mod.Options; pub const TextOptions = format_mod.Options; pub const NormalizeOptions = normalize_mod.Options; pub const RelativizeOptions = relativize_mod.Options; pub const FileOptions = file_mod.Options; pub const FileError = file_mod.Error || Allocator.Error;
// -- construction ------------------------------------------------------
/// Parse a URI reference. Equivalent to Python `hyperlink.URL.from_text`. pub fn parse(alloc: Allocator, text: []const u8) Error!Uri { return parseOpts(alloc, text, .{}); }
pub fn parseOpts(alloc: Allocator, text: []const u8, opts: ParseOptions) Error!Uri { const arena = try newArena(alloc); errdefer destroyArena(arena); return withParts(arena, try parse_mod.parse(arena.allocator(), text, opts)); }
/// Build a `Uri` from loose components, deep-copying every string. pub fn init(alloc: Allocator, c: Components) Allocator.Error!Uri { const arena = try newArena(alloc); errdefer destroyArena(arena); return withParts(arena, try c.dupe(arena.allocator())); }
/// An independent copy, backed by its own arena. pub fn clone(self: Uri, alloc: Allocator) Allocator.Error!Uri { return init(alloc, self.parts()); }
pub fn deinit(self: Uri) void { destroyArena(self.arena); }
/// The components as plain borrowed data, valid until `deinit`. pub fn parts(self: Uri) Components { return .{ .scheme = self.scheme, .username = self.username, .password = self.password, .host = self.host, .port = self.port, .rooted = self.rooted, .path = self.path, .query = self.query, .fragment = self.fragment, }; }
// -- inspection --------------------------------------------------------
/// Whether this reference stands on its own: it has both a scheme and a /// host, so it needs no base URI to be meaningful. pub fn isAbsolute(self: Uri) bool { return self.scheme != null and self.host != null; }
/// Whether this scheme is written `scheme://host/...` rather than as an /// opaque `scheme:body`. pub fn usesNetloc(self: Uri) bool { return schemes.usesNetloc(self.scheme orelse return false); }
/// The scheme's registered default port, ignoring any explicit port. pub fn defaultPort(self: Uri) ?u16 { return schemes.defaultPort(self.scheme orelse return null); }
/// The port a client would actually connect to: the explicit port if there /// is one, otherwise the scheme's default. /// /// (Python's `hyperlink` folds this into `.port` itself; here the `port` /// field stays exactly what was written, so that `http://x` and /// `http://x:80` remain distinguishable and round-trip unchanged.) pub fn effectivePort(self: Uri) ?u16 { return self.port orelse self.defaultPort(); }
pub fn eql(self: Uri, other: Uri) bool { return self.parts().eql(other.parts()); }
pub fn hash(self: Uri) u64 { return self.parts().hash(); }
// -- text --------------------------------------------------------------
/// Write the URI reference to `w`. pub fn write(self: Uri, w: *Writer, opts: TextOptions) Writer.Error!void { return format_mod.write(w, self.parts(), opts); }
/// Render to a fresh slice owned by the caller. pub fn toText(self: Uri, alloc: Allocator, opts: TextOptions) Allocator.Error![]u8 { return format_mod.toText(alloc, self.parts(), opts); }
/// The authority (`[user[:password]@]host[:port]`), or an empty slice if /// there is none. pub fn authority(self: Uri, alloc: Allocator, opts: TextOptions) Allocator.Error![]u8 { var aw: Writer.Allocating = .init(alloc); errdefer aw.deinit(); format_mod.writeAuthority(&aw.writer, self.parts(), opts) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, }; return aw.toOwnedSlice(); }
/// `std.fmt` support: `{f}` renders the URI, with the password withheld. pub fn format(self: Uri, w: *Writer) Writer.Error!void { return self.write(w, .{}); }
// -- derivation --------------------------------------------------------
/// Which fields `replace` should change. /// /// The nullable fields are doubly optional: leaving one as `null` keeps the /// current value, while `@as(?T, null)` clears it. So `.port = 8080` sets /// the port, `.port = @as(?u16, null)` removes it, and omitting `port` /// leaves it alone. pub const Replace = struct { scheme: ??[]const u8 = null, username: ??[]const u8 = null, password: ??[]const u8 = null, host: ??Host = null, port: ??u16 = null, rooted: ?bool = null, path: ?[]const []const u8 = null, query: ?[]const QueryParam = null, fragment: ??[]const u8 = null, };
/// A copy with the given fields changed. pub fn replace(self: Uri, alloc: Allocator, r: Replace) Allocator.Error!Uri { return init(alloc, self.replacedParts(r)); }
/// `replace` without allocating: the result borrows from `self` and `r`. fn replacedParts(self: Uri, r: Replace) Components { var c = self.parts(); if (r.scheme) |v| c.scheme = v; if (r.username) |v| c.username = v; if (r.password) |v| c.password = v; if (r.host) |v| c.host = v; if (r.port) |v| c.port = v; if (r.rooted) |v| c.rooted = v; if (r.path) |v| c.path = v; if (r.query) |v| c.query = v; if (r.fragment) |v| c.fragment = v; return c; }
/// Append path segments, as if descending into a directory. /// /// A trailing empty segment — the one that makes a path end in `/` — is /// replaced rather than appended to, so `http://x/a/` and `http://x/a` /// both give `http://x/a/b`. pub fn child(self: Uri, alloc: Allocator, segments: []const []const u8) Allocator.Error!Uri { if (segments.len == 0) return self.clone(alloc);
var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const sa = scratch.allocator();
const base = if (self.path.len > 0 and self.path[self.path.len - 1].len == 0) self.path[0 .. self.path.len - 1] else self.path;
const path = try sa.alloc([]const u8, base.len + segments.len); @memcpy(path[0..base.len], base); @memcpy(path[base.len..], segments);
return init(alloc, self.replacedParts(.{ .path = path })); }
/// Replace the last path segment, as if naming a file beside this one. pub fn sibling(self: Uri, alloc: Allocator, segment: []const u8) Allocator.Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const sa = scratch.allocator();
const base = if (self.path.len > 0) self.path[0 .. self.path.len - 1] else self.path; const path = try sa.alloc([]const u8, base.len + 1); @memcpy(path[0..base.len], base); path[base.len] = segment;
return init(alloc, self.replacedParts(.{ .path = path })); }
/// Resolve `href` against this URI, the way a browser resolves a link. /// /// Follows RFC 3986 §5.2: an absolute reference replaces this URI outright, /// a rooted path replaces the path, and a relative path is merged against /// this one and then has its `.`/`..` segments resolved. pub fn click(self: Uri, alloc: Allocator, href: []const u8) Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const sa = scratch.allocator();
const ref = if (href.len == 0) self.parts() else try parse_mod.parse(sa, href, .{}); return init(alloc, try mergeRef(sa, self.parts(), ref)); }
/// `click`, with an already-parsed reference. pub fn clickUri(self: Uri, alloc: Allocator, href: Uri) Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); return init(alloc, try mergeRef(scratch.allocator(), self.parts(), href.parts())); }
/// The inverse of `click`: a relative reference that resolves against this /// URI to `target`. /// /// `self.clickUri(self.relativize(target))` is `target` again, with the /// caveat that resolution removes `.` and `..` segments, so a target /// carrying them comes back without them. /// /// When no relative reference would do — a differing scheme, or a /// differing authority without `.network_path` — the result is a copy of /// `target`, unchanged and still absolute. Check with `isAbsolute()` if /// the difference matters. /// /// ```zig /// const base = try Uri.parse(alloc, "https://example.com/docs/intro.html"); /// const target = try Uri.parse(alloc, "https://example.com/api/v1/index.html"); /// const rel = try base.relativize(alloc, target, .{}); /// // ../api/v1/index.html /// ``` pub fn relativize( self: Uri, alloc: Allocator, target: Uri, opts: RelativizeOptions, ) Allocator.Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const sa = scratch.allocator(); const base = self.parts();
// What the target resolves to against this base, which is the most any // reference can be asked to reproduce: resolution removes dot segments // and canonicalises the path, so the target's own spelling is not // always reachable. const want = mergeRef(sa, base, target.parts()) catch |err| switch (err) { error.OutOfMemory => |e| return e, else => return target.clone(alloc), };
const candidate = try relativize_mod.relativize(sa, base, target.parts(), opts);
// Verify rather than trust. The round trip is the whole contract, and // checking it here makes it a property of the function instead of a // property of the test suite -- some targets have no reference that // reaches them at all. `http://x`, with an authority and no path, is // one: every reference resolved against a base with a path yields at // least `/`, so the answer there is the target itself. const got = mergeRef(sa, base, candidate) catch |err| switch (err) { error.OutOfMemory => |e| return e, else => return target.clone(alloc), }; if (!want.eql(got)) return target.clone(alloc);
return init(alloc, candidate); }
// -- file paths --------------------------------------------------------
/// A `file:` URI naming an absolute filesystem path (RFC 8089). /// /// ```zig /// const u = try Uri.fromPath(alloc, "/home/jeff/a b.txt", .{}); /// // file:///home/jeff/a%20b.txt /// ``` /// /// `.platform` says whose path syntax `path` is written in, and defaults /// to the platform this was built for. A relative path has no `file:` URI /// — resolving one needs the working directory, which is I/O — and is /// `error.PathNotAbsolute`; build from the directory with `child` /// instead. See the `file` module for what each platform's paths turn into. pub fn fromPath(alloc: Allocator, path: []const u8, opts: FileOptions) FileError!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); return init(alloc, try file_mod.fromPath(scratch.allocator(), path, opts)); }
/// The filesystem path this `file:` URI names, as a fresh slice owned by /// the caller. /// /// The inverse of `fromPath`, and exact in that direction for a POSIX /// path; a Windows path comes back canonically separated, `C:/a` as /// `C:\a`. Query and fragment are ignored, since neither names anything /// on a filesystem. /// /// Fails with `error.NotFileScheme` for any other scheme, and with /// `error.NonLocalHost` when the URI names a machine this platform cannot /// reach by path — which on POSIX is any host at all besides `localhost`. pub fn toPath(self: Uri, alloc: Allocator, opts: FileOptions) FileError![]u8 { return file_mod.toPath(alloc, self.parts(), opts); }
/// Convert to URI form: the host is IDNA-encoded to its ASCII `xn--` /// form, so that writing the result with the default `TextOptions` /// produces pure ASCII. /// /// Only the host changes. Everything else is stored decoded and is /// escaped on output, so `toText` already emits a conforming URI. /// /// Requires `-Dunicode=true`. pub fn toUri(self: Uri, alloc: Allocator) !Uri { return self.convertHost(alloc, .to_ascii); }
/// Convert to IRI form: an `xn--` host is decoded back to Unicode for /// display. Pair it with `.form = .iri` in `TextOptions` to keep the /// rest of the reference unescaped too. /// /// Requires `-Dunicode=true`. pub fn toIri(self: Uri, alloc: Allocator) !Uri { return self.convertHost(alloc, .to_unicode); }
const HostConversion = enum { to_ascii, to_unicode };
fn convertHost(self: Uri, alloc: Allocator, dir: HostConversion) !Uri { if (!build_options.unicode) { @compileError("toUri/toIri need Unicode support; build with -Dunicode=true"); } const idna = @import("idna.zig");
// Only a registered name is convertible; address literals are already // ASCII and have no Unicode form. const name = switch (self.host orelse return self.clone(alloc)) { .hostname => |h| h, else => return self.clone(alloc), }; if (name.len == 0) return self.clone(alloc);
const converted = switch (dir) { .to_ascii => try idna.toAscii(alloc, name, .{}), .to_unicode => try idna.toUnicode(alloc, name, .{}), }; defer alloc.free(converted);
return init(alloc, self.replacedParts(.{ .host = Host{ .hostname = converted } })); }
/// Syntax-based normalization: lowercase the scheme and host, and resolve /// `.`/`..` path segments. See `NormalizeOptions`. pub fn normalize(self: Uri, alloc: Allocator, opts: NormalizeOptions) Allocator.Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); return init(alloc, try normalize_mod.normalize(scratch.allocator(), self.parts(), opts)); }
// -- query -------------------------------------------------------------
/// Every value recorded for `name`, in order. The outer slice is allocated /// from `alloc` and owned by the caller; the values inside point into this /// `Uri`. pub fn get(self: Uri, alloc: Allocator, name: []const u8) Allocator.Error![]const ?[]const u8 { return query_mod.get(alloc, self.query, name); }
/// The first parameter named `name`, or null. A parameter with a null /// `value` is the bare `?name` form. pub fn first(self: Uri, name: []const u8) ?QueryParam { return query_mod.first(self.query, name); }
/// The last parameter named `name`, or null — the counterpart to `first`. /// /// A repeated query parameter has no defined meaning in RFC 3986, and /// receivers disagree about which occurrence wins, so both ends are /// available. Use `get` to see every value instead. pub fn last(self: Uri, name: []const u8) ?QueryParam { return query_mod.last(self.query, name); }
/// Whether any query parameter uses `name`. pub fn has(self: Uri, name: []const u8) bool { return query_mod.find(self.query, name) != null; }
/// A copy with `name=value` appended to the query. pub fn add(self: Uri, alloc: Allocator, name: []const u8, value: ?[]const u8) Allocator.Error!Uri { return self.withQuery(alloc, query_mod.add, name, value); }
/// A copy in which `name` appears exactly once, with `value`. pub fn set(self: Uri, alloc: Allocator, name: []const u8, value: ?[]const u8) Allocator.Error!Uri { return self.withQuery(alloc, query_mod.set, name, value); }
/// A copy with every parameter named `name` removed. pub fn remove(self: Uri, alloc: Allocator, name: []const u8) Allocator.Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const q = try query_mod.remove(scratch.allocator(), self.query, name); return init(alloc, self.replacedParts(.{ .query = q })); }
/// A copy with matching parameters removed. See `query.removeWhere`. pub fn removeWhere( self: Uri, alloc: Allocator, name: []const u8, value: ??[]const u8, limit: ?usize, ) Allocator.Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const q = try query_mod.removeWhere(scratch.allocator(), self.query, name, value, limit); return init(alloc, self.replacedParts(.{ .query = q })); }
fn withQuery( self: Uri, alloc: Allocator, comptime op: fn (Allocator, []const QueryParam, []const u8, ?[]const u8) Allocator.Error![]const QueryParam, name: []const u8, value: ?[]const u8, ) Allocator.Error!Uri { var scratch = std.heap.ArenaAllocator.init(alloc); defer scratch.deinit(); const q = try op(scratch.allocator(), self.query, name, value); return init(alloc, self.replacedParts(.{ .query = q })); }};
// -- internals -------------------------------------------------------------
fn newArena(alloc: Allocator) Allocator.Error!*std.heap.ArenaAllocator { const arena = try alloc.create(std.heap.ArenaAllocator); arena.* = .init(alloc); return arena;}
fn destroyArena(arena: *std.heap.ArenaAllocator) void { const alloc = arena.child_allocator; arena.deinit(); alloc.destroy(arena);}
fn withParts(arena: *std.heap.ArenaAllocator, c: Components) Uri { return .{ .arena = arena, .scheme = c.scheme, .username = c.username, .password = c.password, .host = c.host, .port = c.port, .rooted = c.rooted, .path = c.path, .query = c.query, .fragment = c.fragment, };}
/// Reference resolution, RFC 3986 §5.2.2, in strict mode.////// Strict means a reference that carries a scheme is taken as-is even when that/// scheme matches the base's — `click("http:g")` against `http://a/b/c/d`/// gives `http:g`, not `http://a/b/c/g`. That is what §5.2.2 specifies; the/// looser reading in §5.2.1 exists only to accommodate old browsers.fn mergeRef(alloc: Allocator, base: Components, ref: Components) Error!Components { var out: Components = .{};
// A reference with a scheme is already absolute, whatever else it has. if (ref.scheme != null) { out = ref; const p = normalize_mod.canonicalPath( format_mod.hasAuthority(out), out.rooted, try normalize_mod.resolveDotSegments(alloc, ref.path), ); out.rooted = p.rooted; out.path = p.segments; return out; } out.scheme = base.scheme;
if (ref.host != null) { // A network-path reference (`//host/x`) replaces the whole authority, // credentials included. out.username = ref.username; out.password = ref.password; out.host = ref.host; out.port = ref.port; out.rooted = ref.rooted; out.path = try normalize_mod.resolveDotSegments(alloc, ref.path); out.query = ref.query; } else { out.username = base.username; out.password = base.password; out.host = base.host; out.port = base.port;
if (!ref.rooted and ref.path.len == 0) { // Same-document reference: keep the base path, and the base query // too unless the reference brought its own. out.rooted = base.rooted; out.path = base.path; out.query = if (ref.query.len > 0) ref.query else base.query; } else if (ref.rooted) { out.rooted = true; out.path = try normalize_mod.resolveDotSegments(alloc, ref.path); out.query = ref.query; } else { // §5.2.3 merge: the reference is relative to the base's "directory", // so the base's last segment is dropped. var merged: []const []const u8 = undefined; if (base.host != null and base.path.len == 0) { merged = ref.path; out.rooted = true; } else { const keep = base.path[0..(base.path.len -| 1)]; const buf = try alloc.alloc([]const u8, keep.len + ref.path.len); @memcpy(buf[0..keep.len], keep); @memcpy(buf[keep.len..], ref.path); merged = buf; out.rooted = base.rooted; } out.path = try normalize_mod.resolveDotSegments(alloc, merged); out.query = ref.query; } }
// Dot-segment removal can leave a path that no reference can be written // with: a lone trailing empty segment, or a leading one where there is no // authority for it to follow. const p = normalize_mod.canonicalPath(format_mod.hasAuthority(out), out.rooted, out.path); out.rooted = p.rooted; out.path = p.segments; out.fragment = ref.fragment; return out;}