// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Serializing `Components` back to URI text. //! //! Because components are stored decoded, writing re-applies percent-encoding. //! Each component is escaped with the largest character set that cannot change //! how the result re-parses, so output is minimally escaped and stable: writing //! and re-parsing always yields the same components. const std = @import("std"); const percent = @import("percent.zig"); const schemes = @import("schemes.zig"); const components = @import("components.zig"); const Components = components.Components; const Writer = std.Io.Writer; pub const Options = struct { /// Whether to write a URI (ASCII only, RFC 3986) or an IRI (RFC 3987), /// which carries the permitted non-ASCII characters literally. /// /// This governs only the escaping of text. Converting the *host* between /// its Unicode and `xn--` forms is `toUri` and `toIri` in the separate /// `uri_unicode` module, because that needs an allocator and Unicode /// tables. form: percent.Form = .uri, /// Include the password in the userinfo. Off by default so that logging a /// `Uri` does not leak a credential; `user:@host` is written instead of /// `user:secret@host`, which is what Python's `hyperlink` does too. with_password: bool = false, }; /// Whether an authority (`//...`) has to be written at all. pub fn hasAuthority(c: Components) bool { return c.host != null or c.port != null or c.username != null or c.password != null; } /// Length of the joined path string. Only its zero-ness is meaningful for /// callers, since percent-encoding changes the true length. fn pathLen(c: Components) usize { const n = c.path.len + @intFromBool(c.rooted); if (n == 0) return 0; var total: usize = n - 1; for (c.path) |s| total += s.len; return total; } /// Whether the joined path string begins with `/`. fn pathStartsWithSlash(c: Components) bool { if (c.rooted) return c.path.len > 0; return c.path.len > 1 and c.path[0].len == 0; } /// Whether the joined path string begins with `//`, which would be re-read as /// the start of an authority. fn pathStartsWithDoubleSlash(c: Components) bool { if (c.rooted) return c.path.len > 1 and c.path[0].len == 0; return c.path.len > 2 and c.path[0].len == 0 and c.path[1].len == 0; } /// Write the authority: `[user[:password]@]host[:port]`. pub fn writeAuthority(w: *Writer, c: Components, opts: Options) Writer.Error!void { if (c.username != null or c.password != null) { try percent.encodeForm(w, c.username orelse "", &percent.username, opts.form); if (c.password) |pw| { // The `:` is kept even when the password is withheld, so that the // presence of a password is still visible. try w.writeByte(':'); if (opts.with_password) try percent.encodeForm(w, pw, &percent.password, opts.form); } try w.writeByte('@'); } if (c.host) |host| switch (host) { .ipv4 => |s| try w.writeAll(s), .ipv6 => |s| { try w.writeByte('['); try w.writeAll(s); try w.writeByte(']'); }, .hostname => |s| try percent.encodeForm(w, s, &percent.host, opts.form), }; if (c.port) |port| try w.print(":{d}", .{port}); } /// Write the path, escaping each segment. fn writePath(w: *Writer, c: Components, force_nc_first: bool, form: percent.Form) Writer.Error!void { var need_sep = c.rooted; for (c.path, 0..) |seg, i| { if (need_sep) try w.writeByte('/'); need_sep = true; const set = if (i == 0 and force_nc_first) &percent.segment_nc else &percent.segment; try percent.encodeForm(w, seg, set, form); } } /// Write the query string, without the leading `?`. pub fn writeQuery(w: *Writer, c: Components, form: percent.Form) Writer.Error!void { // A query is the one place RFC 3987 also allows private-use characters. const q: percent.Form = if (form == .iri) .iri_query else form; for (c.query, 0..) |param, i| { if (i > 0) try w.writeByte('&'); try percent.encodeForm(w, param.key, &percent.query_key, q); if (param.value) |v| { try w.writeByte('='); try percent.encodeForm(w, v, &percent.query_value, q); } } } /// Write the full URI reference. pub fn write(w: *Writer, c: Components, opts: Options) Writer.Error!void { if (c.scheme) |s| { try percent.encode(w, s, &percent.scheme); try w.writeByte(':'); } // `//` is written only when there really is an authority. Python's // `hyperlink` also emits it for any scheme that *could* have one, turning // `http:/foo` into `http:///foo`; that is a normalization rather than a // serialization, and it silently converts "no authority" into "empty // authority" when the result is re-parsed. An empty authority is still // reachable by asking for one: `.host = .{ .hostname = "" }`. const authority = hasAuthority(c); if (authority) { try w.writeAll("//"); try writeAuthority(w, c, opts); } if (pathLen(c) > 0) { // RFC 3986 §3.3: with no authority the path may not begin with `//`, // or it would be re-read as one. Parsing can never produce such a // path, so this only catches hand-built `Components`. std.debug.assert(authority or !pathStartsWithDoubleSlash(c)); // With an authority present the path must be rooted, or the authority // would run straight into the first segment. if (authority and !pathStartsWithSlash(c)) try w.writeByte('/'); // In a bare relative reference a `:` in the first segment would be // read as a scheme, so it has to be escaped there (RFC 3986 // `segment-nz-nc`). const nc = c.scheme == null and !authority and !c.rooted; try writePath(w, c, nc, opts.form); } if (c.query.len > 0) { try w.writeByte('?'); try writeQuery(w, c, opts.form); } if (c.fragment) |f| { try w.writeByte('#'); try percent.encodeForm(w, f, &percent.fragment, opts.form); } } /// `write`, into a freshly allocated slice owned by the caller. pub fn toText(alloc: std.mem.Allocator, c: Components, opts: Options) ![]u8 { var aw: Writer.Allocating = .init(alloc); errdefer aw.deinit(); write(&aw.writer, c, opts) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, }; return aw.toOwnedSlice(); }