大致遵循 https://tools.ietf.org/html/rfc3986 的统一资源标识符(URI)解析。 不会进行完全严格的语法及字符类别检查, 但应能稳健处理实际出现的 URI。
字段
scheme: []const u8
user: ?Component = null
password: ?Component = null
host: ?Component = null
port: ?u16 = null
path: Component = Component.empty
query: ?Component = null
fragment: ?Component = null
stdtestingUriAllocatorWritergetHostgetHostAllocComponentpercentDecodeBackwardspercentDecodeInPlaceParseErrorparseAfterSchemeformatwriteToStreamFormatfmtparseResolveInPlaceErrorresolveInPlaceremove_dot_segmentsmerge_pathsisValidSchemeisSubLimitisUnreservedisUserCharisPasswordCharisHostCharisPathCharisQueryCharisFragmentCharauthority_seppath_septestAuthorityHost
std.Uri.Allocator
别名
别名目标 std.mem.Allocator
std.Uri.authority_sep
常量
[3]u8
std.Uri.Component
容器
字段
raw: []const u8此分量中的无效字符,必须在作为 URI 的一部分 打印之前进行百分号编码。
percent_encoded: []const u8此分量已经过百分号编码,可直接 作为 URI 的一部分打印。
std.Uri.Component.empty
常量
Component
std.Uri.Component.formatEscaped
函数
pub fn formatEscaped(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatFragment
函数
pub fn formatFragment(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatHost
函数
pub fn formatHost(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatPassword
函数
pub fn formatPassword(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatPath
函数
pub fn formatPath(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatQuery
函数
pub fn formatQuery(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatRaw
函数
pub fn formatRaw(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.formatUser
函数
pub fn formatUser(component: Component, w: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.isEmpty
函数
pub fn isEmpty(component: Component) bool
参数
component: Component
std.Uri.Component.percentEncode
函数
pub fn percentEncode(w: *Writer, raw: []const u8, comptime isValidChar: fn (u8) bool) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Component.toRaw
函数
返回值可能指向 buffer,也可能是原始字符串。
pub fn toRaw(component: Component, buffer: []u8) error{NoSpaceLeft}![]const u8
参数
component: Component
buffer: []u8
错误
- NoSpaceLeft
std.Uri.Component.toRawMaybeAlloc
函数
仅在必要时使用 arena 分配结果,因此不应释放结果。
pub fn toRawMaybeAlloc(component: Component, arena: Allocator) Allocator.Error![]const u8
参数
错误
- OutOfMemory
std.Uri.fmt
函数
pub fn fmt(uri: *const Uri, flags: Format.Flags) std.fmt.Alt(Format, Format.default)
参数
std.Uri.format
函数
pub fn format(uri: *const Uri, writer: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Format
容器
字段
std.Uri.Format.default
函数
pub fn default(f: Format, writer: *Writer) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Uri.Format.Flags
容器
字段
scheme: bool = false为 true 时,包含 URI 的方案部分。
authentication: bool = false为 true 时包含 URI 的用户和密码部分。若 authority 为 false,则忽略。
authority: bool = false为 true 时,包含 URI 的授权信息部分。
path: bool = false为 true 时,包含 URI 的路径部分。
query: bool = false为 true 时包含 URI 的查询部分。path 为 false 时忽略。
fragment: bool = false为 true 时包含 URI 的片段部分。path 为 false 时忽略。
port: bool = true为 true 时包含 URI 的端口部分。port 为 null 时忽略。
std.Uri.Format.Flags.all
常量
Flags
std.Uri.getHost
常量
std.Uri.getHostAlloc
常量
std.Uri.isFragmentChar
别名
别名目标 std.Uri.isQueryChar
std.Uri.isHostChar
函数
fn isHostChar(c: u8) bool
参数
c: u8
std.Uri.isPasswordChar
函数
fn isPasswordChar(c: u8) bool
参数
c: u8
std.Uri.isPathChar
函数
fn isPathChar(c: u8) bool
参数
c: u8
std.Uri.isQueryChar
函数
fn isQueryChar(c: u8) bool
参数
c: u8
std.Uri.isSubLimit
函数
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
fn isSubLimit(c: u8) bool
参数
c: u8
std.Uri.isUnreserved
函数
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
fn isUnreserved(c: u8) bool
参数
c: u8
std.Uri.isUserChar
函数
fn isUserChar(c: u8) bool
参数
c: u8
std.Uri.isValidScheme
函数
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
fn isValidScheme(scheme: []const u8) bool
参数
scheme: []const u8
std.Uri.merge_paths
函数
5.2.3. 合并路径
fn merge_paths(base: Component, new: []u8, aux_buf: *[]u8) error{NoSpaceLeft}!Component
参数
错误
- NoSpaceLeft
std.Uri.parse
函数
返回值包含的字符串指向原始 text。
提供的各个部分均为非 null。
pub fn parse(text: []const u8) ParseError!Uri
参数
text: []const u8
错误
- InvalidFormat
- InvalidHostName
- InvalidPort
- UnexpectedCharacter
std.Uri.parseAfterScheme
函数
解析 URI,或返回错误。此函数不完全遵循规范,但为解析实际中出现的某些 URI 形式所必需,例如 HTTP Location 报头。
返回值中的字符串指向原始 text。
每个已提供的分量都为非 null。
pub fn parseAfterScheme(scheme: []const u8, text: []const u8) ParseError!Uri
参数
scheme: []const u8
text: []const u8
错误
- InvalidFormat
- InvalidHostName
- InvalidPort
- UnexpectedCharacter
std.Uri.ParseError
错误集合
错误
- InvalidFormat
- InvalidHostName
- InvalidPort
- UnexpectedCharacter
std.Uri.path_sep
常量
[2]u8
std.Uri.percentDecodeBackwards
函数
对所有 %XX 执行百分号解码,其中 XX 为有效十六进制数。
若 output.ptr <= input.ptr,output 可与 input 重叠。
修改并返回 output 的子切片。
pub fn percentDecodeBackwards(output: []u8, input: []const u8) []u8
参数
output: []u8
input: []const u8
std.Uri.percentDecodeInPlace
函数
对所有 XX 为有效十六进制数的 %XX 执行百分号解码。
修改 buffer 并返回其中的子切片。
pub fn percentDecodeInPlace(buffer: []u8) []u8
参数
buffer: []u8
std.Uri.remove_dot_segments
函数
RFC 3986 第 5.2.4 节的原地实现。
fn remove_dot_segments(path: []u8) Component
参数
path: []u8
用法示例
test remove_dot_segments {
{
var buffer = "/a/b/c/./../../g".*;
try std.testing.expectEqualStrings("/a/g", remove_dot_segments(&buffer).percent_encoded);
}
}
std.Uri.resolveInPlace
函数
相对于基础 URI 解析 URI,遵循 RFC 3986 第 5 节。
假定新位置已复制到 aux_buf.* 的开头。
将新位置解析为 URI,再原地解析路径。
若需要合并,新构造的路径会保存在
aux_buf.* 中已复制位置的紧后方,并修改 aux_buf.*,
使其仅包含剩余未使用空间。
pub fn resolveInPlace(base: Uri, new_len: usize, aux_buf: *[]u8) ResolveInPlaceError!Uri
参数
错误
- InvalidFormat ParseError
- InvalidHostName ParseError
- InvalidPort ParseError
- NoSpaceLeft
- UnexpectedCharacter ParseError
std.Uri.ResolveInPlaceError
错误集合
错误
- InvalidFormat ParseError
- InvalidHostName ParseError
- InvalidPort ParseError
- NoSpaceLeft
- UnexpectedCharacter ParseError
std.Uri.std
别名
别名目标 std
std.Uri.testAuthorityHost
函数
fn testAuthorityHost(comptime hostlist: anytype) !void
std.Uri.testing
别名
别名目标 std.testing
std.Uri.Uri
别名
别名目标 std.Uri
std.Uri.Writer
别名
别名目标 std.Io.Writer
std.Uri.writeToStream
函数
pub fn writeToStream(uri: *const Uri, writer: *Writer, flags: Format.Flags) Writer.Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
源码
std/Uri.zig
//! 大致遵循 <https://tools.ietf.org/html/rfc3986> 的统一资源标识符(URI)解析。
//! 不会进行完全严格的语法及字符类别检查,
//! 但应能稳健处理实际出现的 URI。
const std = @import("std.zig");
const testing = std.testing;
const Uri = @This();
const Allocator = std.mem.Allocator;
const Writer = std.Io.Writer;
scheme: []const u8,
user: ?Component = null,
password: ?Component = null,
host: ?Component = null,
port: ?u16 = null,
path: Component = Component.empty,
query: ?Component = null,
fragment: ?Component = null,
pub const getHost = @compileError("This function has been moved to std.Io.net.HostName.fromUri");
pub const getHostAlloc = @compileError("This function has been deleted. See std.Io.net.HostName.fromUri instead");
pub const Component = union(enum) {
/// 此分量中的无效字符,必须在作为 URI 的一部分
/// 打印之前进行百分号编码。
raw: []const u8,
/// 此分量已经过百分号编码,可直接
/// 作为 URI 的一部分打印。
percent_encoded: []const u8,
pub const empty: Component = .{ .percent_encoded = "" };
pub fn isEmpty(component: Component) bool {
return switch (component) {
.raw, .percent_encoded => |string| string.len == 0,
};
}
/// 返回值可能指向 `buffer`,也可能是原始字符串。
pub fn toRaw(component: Component, buffer: []u8) error{NoSpaceLeft}![]const u8 {
return switch (component) {
.raw => |raw| raw,
.percent_encoded => |percent_encoded| if (std.mem.findScalar(u8, percent_encoded, '%')) |_|
try std.mem.print(buffer, "{f}", .{std.fmt.alt(component, .formatRaw)})
else
percent_encoded,
};
}
/// 仅在必要时使用 `arena` 分配结果,因此不应释放结果。
pub fn toRawMaybeAlloc(component: Component, arena: Allocator) Allocator.Error![]const u8 {
return switch (component) {
.raw => |raw| raw,
.percent_encoded => |percent_encoded| if (std.mem.findScalar(u8, percent_encoded, '%')) |_|
try arena.print("{f}", .{std.fmt.alt(component, .formatRaw)})
else
percent_encoded,
};
}
pub fn formatRaw(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try w.writeAll(raw),
.percent_encoded => |percent_encoded| {
var start: usize = 0;
var index: usize = 0;
while (std.mem.findScalarPos(u8, percent_encoded, index, '%')) |percent| {
index = percent + 1;
if (percent_encoded.len - index < 2) continue;
const percent_encoded_char =
std.fmt.parseInt(u8, percent_encoded[index..][0..2], 16) catch continue;
try w.print("{s}{c}", .{
percent_encoded[start..percent],
percent_encoded_char,
});
start = percent + 3;
index = percent + 3;
}
try w.writeAll(percent_encoded[start..]);
},
}
}
pub fn formatEscaped(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isUnreserved),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn formatUser(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isUserChar),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn formatPassword(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isPasswordChar),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn formatHost(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isHostChar),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn formatPath(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isPathChar),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn formatQuery(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isQueryChar),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn formatFragment(component: Component, w: *Writer) Writer.Error!void {
switch (component) {
.raw => |raw| try percentEncode(w, raw, isFragmentChar),
.percent_encoded => |percent_encoded| try w.writeAll(percent_encoded),
}
}
pub fn percentEncode(w: *Writer, raw: []const u8, comptime isValidChar: fn (u8) bool) Writer.Error!void {
var start: usize = 0;
for (raw, 0..) |char, index| {
if (isValidChar(char)) continue;
try w.print("{s}%{X:0>2}", .{ raw[start..index], char });
start = index + 1;
}
try w.writeAll(raw[start..]);
}
};
/// 对所有 %XX 执行百分号解码,其中 XX 为有效十六进制数。
/// 若 `output.ptr <= input.ptr`,`output` 可与 `input` 重叠。
/// 修改并返回 `output` 的子切片。
pub fn percentDecodeBackwards(output: []u8, input: []const u8) []u8 {
var input_index = input.len;
var output_index = output.len;
while (input_index > 0) {
if (input_index >= 3) {
const maybe_percent_encoded = input[input_index - 3 ..][0..3];
if (maybe_percent_encoded[0] == '%') {
if (std.fmt.parseInt(u8, maybe_percent_encoded[1..], 16)) |percent_encoded_char| {
input_index -= maybe_percent_encoded.len;
output_index -= 1;
output[output_index] = percent_encoded_char;
continue;
} else |_| {}
}
}
input_index -= 1;
output_index -= 1;
output[output_index] = input[input_index];
}
return output[output_index..];
}
/// 对所有 XX 为有效十六进制数的 %XX 执行百分号解码。
/// 修改 `buffer` 并返回其中的子切片。
pub fn percentDecodeInPlace(buffer: []u8) []u8 {
return percentDecodeBackwards(buffer, buffer);
}
pub const ParseError = error{ UnexpectedCharacter, InvalidFormat, InvalidPort, InvalidHostName };
/// 解析 URI,或返回错误。此函数不完全遵循规范,但为解析实际中出现的某些 URI 形式所必需,例如 HTTP Location 报头。
/// 返回值中的字符串指向原始 `text`。
/// 每个已提供的分量都为非 `null`。
///
pub fn parseAfterScheme(scheme: []const u8, text: []const u8) ParseError!Uri {
var uri: Uri = .{ .scheme = scheme, .path = undefined };
var i: usize = 0;
if (std.mem.startsWith(u8, text, "//")) a: {
i = std.mem.findAnyPos(u8, text, 2, &authority_sep) orelse text.len;
const authority = text[2..i];
if (authority.len == 0) {
if (!std.mem.startsWith(u8, text[2..], "/")) return error.InvalidFormat;
break :a;
}
var start_of_host: usize = 0;
// 使用 findLast,以便妥善处理 userinfo 中未编码的 @,
// 例如 scheme://user:p@ssword@hostname。此行为偏离 RFC3986
// (该规范要求 userinfo 中的 @ 百分号编码为 %40),但
// 对于实际出现的 URI 更稳健。
if (std.mem.findLast(u8, authority, "@")) |index| {
start_of_host = index + 1;
const user_info = authority[0..index];
if (std.mem.find(u8, user_info, ":")) |idx| {
uri.user = .{ .percent_encoded = user_info[0..idx] };
if (idx < user_info.len - 1) { // 空密码也表示 "no password"
uri.password = .{ .percent_encoded = user_info[idx + 1 ..] };
}
} else {
uri.user = .{ .percent_encoded = user_info };
uri.password = null;
}
}
// 仅当 URI 只包含 `userinfo@` 时才可能发生。
if (start_of_host >= authority.len) break :a;
var end_of_host: usize = authority.len;
// 若先看到 `]` 而没有 `@`
if (authority[start_of_host] == ']') {
return error.InvalidFormat;
}
if (authority.len > start_of_host and authority[start_of_host] == '[') { // IPv6
end_of_host = std.mem.findLast(u8, authority, "]") orelse return error.InvalidFormat;
end_of_host += 1;
if (std.mem.findLast(u8, authority, ":")) |index| {
if (index >= end_of_host) { // 若不属于 V6 地址字段
end_of_host = @min(end_of_host, index);
uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort;
}
}
} else if (std.mem.findLast(u8, authority, ":")) |index| {
if (index >= start_of_host) { // 若不属于 userinfo 字段
end_of_host = @min(end_of_host, index);
uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort;
}
}
if (start_of_host >= end_of_host) return error.InvalidFormat;
const host = authority[start_of_host..end_of_host];
if (host.len > std.Io.net.HostName.max_len) return error.InvalidHostName;
uri.host = .{ .percent_encoded = host };
}
const path_start = i;
i = std.mem.findAnyPos(u8, text, path_start, &path_sep) orelse text.len;
uri.path = .{ .percent_encoded = text[path_start..i] };
if (std.mem.startsWith(u8, text[i..], "?")) {
const query_start = i + 1;
i = std.mem.findScalarPos(u8, text, query_start, '#') orelse text.len;
uri.query = .{ .percent_encoded = text[query_start..i] };
}
if (std.mem.startsWith(u8, text[i..], "#")) {
uri.fragment = .{ .percent_encoded = text[i + 1 ..] };
}
return uri;
}
pub fn format(uri: *const Uri, writer: *Writer) Writer.Error!void {
return writeToStream(uri, writer, .all);
}
pub fn writeToStream(uri: *const Uri, writer: *Writer, flags: Format.Flags) Writer.Error!void {
if (flags.scheme) {
try writer.print("{s}:", .{uri.scheme});
if (flags.authority and uri.host != null) {
try writer.writeAll("//");
}
}
if (flags.authority) {
if (flags.authentication and uri.host != null) {
if (uri.user) |user| {
try user.formatUser(writer);
if (uri.password) |password| {
try writer.writeByte(':');
try password.formatPassword(writer);
}
try writer.writeByte('@');
}
}
if (uri.host) |host| {
try host.formatHost(writer);
if (flags.port) {
if (uri.port) |port| try writer.print(":{d}", .{port});
}
}
}
if (flags.path) {
const uri_path: Component = if (uri.path.isEmpty()) .{ .percent_encoded = "/" } else uri.path;
try uri_path.formatPath(writer);
if (flags.query) {
if (uri.query) |query| {
try writer.writeByte('?');
try query.formatQuery(writer);
}
}
if (flags.fragment) {
if (uri.fragment) |fragment| {
try writer.writeByte('#');
try fragment.formatFragment(writer);
}
}
}
}
pub const Format = struct {
uri: *const Uri,
flags: Flags = .{},
pub const Flags = struct {
/// 为 true 时,包含 URI 的方案部分。
scheme: bool = false,
/// 为 true 时包含 URI 的用户和密码部分。若 `authority` 为 false,则忽略。
authentication: bool = false,
/// 为 true 时,包含 URI 的授权信息部分。
authority: bool = false,
/// 为 true 时,包含 URI 的路径部分。
path: bool = false,
/// 为 true 时包含 URI 的查询部分。`path` 为 false 时忽略。
query: bool = false,
/// 为 true 时包含 URI 的片段部分。`path` 为 false 时忽略。
fragment: bool = false,
/// 为 true 时包含 URI 的端口部分。`port` 为 null 时忽略。
port: bool = true,
pub const all: Flags = .{
.scheme = true,
.authentication = true,
.authority = true,
.path = true,
.query = true,
.fragment = true,
.port = true,
};
};
pub fn default(f: Format, writer: *Writer) Writer.Error!void {
return writeToStream(f.uri, writer, f.flags);
}
};
pub fn fmt(uri: *const Uri, flags: Format.Flags) std.fmt.Alt(Format, Format.default) {
return .{ .data = .{ .uri = uri, .flags = flags } };
}
/// 返回值包含的字符串指向原始 `text`。
/// 提供的各个部分均为非 `null`。
pub fn parse(text: []const u8) ParseError!Uri {
const scheme, const rest = std.mem.cutScalar(u8, text, ':') orelse
return error.InvalidFormat;
if (!isValidScheme(scheme))
return error.UnexpectedCharacter;
return parseAfterScheme(scheme, rest);
}
pub const ResolveInPlaceError = ParseError || error{NoSpaceLeft};
/// 相对于基础 URI 解析 URI,遵循
/// [RFC 3986 第 5 节](https://www.rfc-editor.org/rfc/rfc3986#section-5)。
///
/// 假定新位置已复制到 `aux_buf.*` 的开头。
/// 将新位置解析为 URI,再原地解析路径。
///
/// 若需要合并,新构造的路径会保存在
/// `aux_buf.*` 中已复制位置的紧后方,并修改 `aux_buf.*`,
/// 使其仅包含剩余未使用空间。
pub fn resolveInPlace(base: Uri, new_len: usize, aux_buf: *[]u8) ResolveInPlaceError!Uri {
const new = aux_buf.*[0..new_len];
const new_parsed = parse(new) catch |err| (parseAfterScheme("", new) catch return err);
aux_buf.* = aux_buf.*[new_len..];
// 如上所示,`new` 不是 const 指针。
const new_path: []u8 = @constCast(new_parsed.path.percent_encoded);
if (new_parsed.scheme.len > 0) return .{
.scheme = new_parsed.scheme,
.user = new_parsed.user,
.password = new_parsed.password,
.host = new_parsed.host,
.port = new_parsed.port,
.path = remove_dot_segments(new_path),
.query = new_parsed.query,
.fragment = new_parsed.fragment,
};
if (new_parsed.host) |host| return .{
.scheme = base.scheme,
.user = new_parsed.user,
.password = new_parsed.password,
.host = host,
.port = new_parsed.port,
.path = remove_dot_segments(new_path),
.query = new_parsed.query,
.fragment = new_parsed.fragment,
};
const path, const query = if (new_path.len == 0) .{
base.path,
new_parsed.query orelse base.query,
} else if (new_path[0] == '/') .{
remove_dot_segments(new_path),
new_parsed.query,
} else .{
try merge_paths(base.path, new_path, aux_buf),
new_parsed.query,
};
return .{
.scheme = base.scheme,
.user = base.user,
.password = base.password,
.host = base.host,
.port = base.port,
.path = path,
.query = query,
.fragment = new_parsed.fragment,
};
}
/// RFC 3986 第 5.2.4 节的原地实现。
fn remove_dot_segments(path: []u8) Component {
var in_i: usize = 0;
var out_i: usize = 0;
while (in_i < path.len) {
if (std.mem.startsWith(u8, path[in_i..], "./")) {
in_i += 2;
} else if (std.mem.startsWith(u8, path[in_i..], "../")) {
in_i += 3;
} else if (std.mem.startsWith(u8, path[in_i..], "/./")) {
in_i += 2;
} else if (std.mem.eql(u8, path[in_i..], "/.")) {
in_i += 1;
path[in_i] = '/';
} else if (std.mem.startsWith(u8, path[in_i..], "/../")) {
in_i += 3;
while (out_i > 0) {
out_i -= 1;
if (path[out_i] == '/') break;
}
} else if (std.mem.eql(u8, path[in_i..], "/..")) {
in_i += 2;
path[in_i] = '/';
while (out_i > 0) {
out_i -= 1;
if (path[out_i] == '/') break;
}
} else if (std.mem.eql(u8, path[in_i..], ".")) {
in_i += 1;
} else if (std.mem.eql(u8, path[in_i..], "..")) {
in_i += 2;
} else {
while (true) {
path[out_i] = path[in_i];
out_i += 1;
in_i += 1;
if (in_i >= path.len or path[in_i] == '/') break;
}
}
}
return .{ .percent_encoded = path[0..out_i] };
}
test remove_dot_segments {
{
var buffer = "/a/b/c/./../../g".*;
try std.testing.expectEqualStrings("/a/g", remove_dot_segments(&buffer).percent_encoded);
}
}
/// 5.2.3. 合并路径
fn merge_paths(base: Component, new: []u8, aux_buf: *[]u8) error{NoSpaceLeft}!Component {
var aux: Writer = .fixed(aux_buf.*);
if (!base.isEmpty()) {
base.formatPath(&aux) catch return error.NoSpaceLeft;
aux.end = std.mem.findScalarLast(u8, aux.buffered(), '/') orelse return remove_dot_segments(new);
}
aux.print("/{s}", .{new}) catch return error.NoSpaceLeft;
const merged_path = remove_dot_segments(aux.buffered());
aux_buf.* = aux_buf.*[merged_path.percent_encoded.len..];
return merged_path;
}
/// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
fn isValidScheme(scheme: []const u8) bool {
if (scheme.len == 0) return false;
if (!std.ascii.isAlphabetic(scheme[0])) return false;
for (scheme[1..]) |byte| {
switch (byte) {
'A'...'Z', 'a'...'z', '0'...'9', '+', '-', '.' => continue,
else => return false,
}
}
return true;
}
/// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/// / "*" / "+" / "," / ";" / "="
fn isSubLimit(c: u8) bool {
return switch (c) {
'!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' => true,
else => false,
};
}
/// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
fn isUnreserved(c: u8) bool {
return switch (c) {
'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => true,
else => false,
};
}
fn isUserChar(c: u8) bool {
return isUnreserved(c) or isSubLimit(c);
}
fn isPasswordChar(c: u8) bool {
return isUserChar(c) or c == ':';
}
fn isHostChar(c: u8) bool {
return isPasswordChar(c) or c == '[' or c == ']';
}
fn isPathChar(c: u8) bool {
return isUserChar(c) or c == '/' or c == ':' or c == '@';
}
fn isQueryChar(c: u8) bool {
return isPathChar(c) or c == '?';
}
const isFragmentChar = isQueryChar;
const authority_sep: [3]u8 = .{ '/', '?', '#' };
const path_sep: [2]u8 = .{ '?', '#' };
test "basic" {
const parsed = try parse("https://ziglang.org/download");
try testing.expectEqualStrings("https", parsed.scheme);
try testing.expectEqualStrings("ziglang.org", parsed.host.?.percent_encoded);
try testing.expectEqualStrings("/download", parsed.path.percent_encoded);
try testing.expectEqual(@as(?u16, null), parsed.port);
}
test "with port" {
const parsed = try parse("http://example:1337/");
try testing.expectEqualStrings("http", parsed.scheme);
try testing.expectEqualStrings("example", parsed.host.?.percent_encoded);
try testing.expectEqualStrings("/", parsed.path.percent_encoded);
try testing.expectEqual(@as(?u16, 1337), parsed.port);
}
test "should fail gracefully" {
try std.testing.expectError(error.InvalidFormat, parse("foobar://"));
}
test "parse name too long" {
const uri = "http://" ++ @as([std.Io.net.HostName.max_len + 1]u8, @splat('Z'));
try std.testing.expectError(error.InvalidHostName, parse(uri));
}
test "file" {
const parsed = try parse("file:///");
try std.testing.expectEqualStrings("file", parsed.scheme);
try std.testing.expectEqual(@as(?Component, null), parsed.host);
try std.testing.expectEqualStrings("/", parsed.path.percent_encoded);
const parsed2 = try parse("file:///an/absolute/path/to/something");
try std.testing.expectEqualStrings("file", parsed2.scheme);
try std.testing.expectEqual(@as(?Component, null), parsed2.host);
try std.testing.expectEqualStrings("/an/absolute/path/to/something", parsed2.path.percent_encoded);
const parsed3 = try parse("file://localhost/an/absolute/path/to/another/thing/");
try std.testing.expectEqualStrings("file", parsed3.scheme);
try std.testing.expectEqualStrings("localhost", parsed3.host.?.percent_encoded);
try std.testing.expectEqualStrings("/an/absolute/path/to/another/thing/", parsed3.path.percent_encoded);
const parsed4 = try parse("file:/an/absolute/path");
try std.testing.expectEqualStrings("file", parsed4.scheme);
try std.testing.expectEqual(@as(?Component, null), parsed4.host);
try std.testing.expectEqualStrings("/an/absolute/path", parsed4.path.percent_encoded);
}
test "scheme" {
try std.testing.expectEqualStrings("http", (try parse("http:_")).scheme);
try std.testing.expectEqualStrings("scheme-mee", (try parse("scheme-mee:_")).scheme);
try std.testing.expectEqualStrings("a.b.c", (try parse("a.b.c:_")).scheme);
try std.testing.expectEqualStrings("ab+", (try parse("ab+:_")).scheme);
try std.testing.expectEqualStrings("X+++", (try parse("X+++:_")).scheme);
try std.testing.expectEqualStrings("Y+-.", (try parse("Y+-.:_")).scheme);
try std.testing.expectError(error.InvalidFormat, parse(""));
try std.testing.expectError(error.UnexpectedCharacter, parse(":"));
try std.testing.expectError(error.UnexpectedCharacter, parse("-:"));
try std.testing.expectError(error.UnexpectedCharacter, parse("+hTTp:"));
try std.testing.expectError(error.UnexpectedCharacter, parse("$:"));
try std.testing.expectError(error.UnexpectedCharacter, parse("h$:"));
}
test "authority" {
try std.testing.expectEqualStrings("hostname", (try parse("scheme://hostname")).host.?.percent_encoded);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://userinfo@hostname")).host.?.percent_encoded);
try std.testing.expectEqualStrings("userinfo", (try parse("scheme://userinfo@hostname")).user.?.percent_encoded);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://userinfo@hostname")).password);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://userinfo@")).host);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://user:password@hostname")).host.?.percent_encoded);
try std.testing.expectEqualStrings("user", (try parse("scheme://user:password@hostname")).user.?.percent_encoded);
try std.testing.expectEqualStrings("password", (try parse("scheme://user:password@hostname")).password.?.percent_encoded);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://hostname:0")).host.?.percent_encoded);
try std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://hostname:1234")).port.?);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://userinfo@hostname:1234")).host.?.percent_encoded);
try std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://userinfo@hostname:1234")).port.?);
try std.testing.expectEqualStrings("userinfo", (try parse("scheme://userinfo@hostname:1234")).user.?.percent_encoded);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://userinfo@hostname:1234")).password);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://user:password@hostname:1234")).host.?.percent_encoded);
try std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://user:password@hostname:1234")).port.?);
try std.testing.expectEqualStrings("user", (try parse("scheme://user:password@hostname:1234")).user.?.percent_encoded);
try std.testing.expectEqualStrings("password", (try parse("scheme://user:password@hostname:1234")).password.?.percent_encoded);
try std.testing.expectEqualStrings("user", (try parse("scheme://user:p@ssword@hostname:1234")).user.?.percent_encoded);
try std.testing.expectEqualStrings("p@ssword", (try parse("scheme://user:p@ssword@hostname:1234")).password.?.percent_encoded);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://user:p@ssword@hostname:1234")).host.?.percent_encoded);
try std.testing.expectEqualStrings("user", (try parse("scheme://user:p@@@word@hostname:1234")).user.?.percent_encoded);
try std.testing.expectEqualStrings("p@@@word", (try parse("scheme://user:p@@@word@hostname:1234")).password.?.percent_encoded);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://user:p@@@word@hostname:1234")).host.?.percent_encoded);
try std.testing.expectEqualStrings("user@name", (try parse("scheme://user@name@hostname")).user.?.percent_encoded);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://user@name@hostname")).password);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://user@name@hostname")).host.?.percent_encoded);
try std.testing.expectEqualStrings("user@name", (try parse("scheme://user@name@hostname:1234")).user.?.percent_encoded);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://user@name@hostname:1234")).password);
try std.testing.expectEqualStrings("hostname", (try parse("scheme://user@name@hostname:1234")).host.?.percent_encoded);
try std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://user@name@hostname:1234")).port.?);
}
test "authority.password" {
try std.testing.expectEqualStrings("username", (try parse("scheme://username@a")).user.?.percent_encoded);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://username@a")).password);
try std.testing.expectEqualStrings("username", (try parse("scheme://username:@a")).user.?.percent_encoded);
try std.testing.expectEqual(@as(?Component, null), (try parse("scheme://username:@a")).password);
try std.testing.expectEqualStrings("username", (try parse("scheme://username:password@a")).user.?.percent_encoded);
try std.testing.expectEqualStrings("password", (try parse("scheme://username:password@a")).password.?.percent_encoded);
try std.testing.expectEqualStrings("username", (try parse("scheme://username::@a")).user.?.percent_encoded);
try std.testing.expectEqualStrings(":", (try parse("scheme://username::@a")).password.?.percent_encoded);
}
fn testAuthorityHost(comptime hostlist: anytype) !void {
inline for (hostlist) |hostname| {
try std.testing.expectEqualStrings(hostname, (try parse("scheme://" ++ hostname)).host.?.percent_encoded);
}
}
test "authority.dns-names" {
try testAuthorityHost(.{
"a",
"a.b",
"example.com",
"www.example.com",
"example.org.",
"www.example.org.",
"xn--nw2a.xn--j6w193g", // 国际化 URI:見.香港
"fe80--1ff-fe23-4567-890as3.ipv6-literal.net",
});
}
test "authority.IPv4" {
try testAuthorityHost(.{
"127.0.0.1",
"255.255.255.255",
"0.0.0.0",
"8.8.8.8",
"1.2.3.4",
"192.168.0.1",
"10.42.0.0",
});
}
test "authority.IPv6" {
try testAuthorityHost(.{
"[2001:db8:0:0:0:0:2:1]",
"[2001:db8::2:1]",
"[2001:db8:0000:1:1:1:1:1]",
"[2001:db8:0:1:1:1:1:1]",
"[0:0:0:0:0:0:0:0]",
"[0:0:0:0:0:0:0:1]",
"[::1]",
"[::]",
"[2001:db8:85a3:8d3:1319:8a2e:370:7348]",
"[fe80::1ff:fe23:4567:890a%25eth2]",
"[fe80::1ff:fe23:4567:890a]",
"[fe80::1ff:fe23:4567:890a%253]",
"[fe80:3::1ff:fe23:4567:890a]",
});
}
test "RFC example 1" {
const uri = "foo://example.com:8042/over/there?name=ferret#nose";
try std.testing.expectEqual(Uri{
.scheme = uri[0..3],
.user = null,
.password = null,
.host = .{ .percent_encoded = uri[6..17] },
.port = 8042,
.path = .{ .percent_encoded = uri[22..33] },
.query = .{ .percent_encoded = uri[34..45] },
.fragment = .{ .percent_encoded = uri[46..50] },
}, try parse(uri));
}
test "RFC example 2" {
const uri = "urn:example:animal:ferret:nose";
try std.testing.expectEqual(Uri{
.scheme = uri[0..3],
.user = null,
.password = null,
.host = null,
.port = null,
.path = .{ .percent_encoded = uri[4..] },
.query = null,
.fragment = null,
}, try parse(uri));
}
// 来源:
// https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Examples
test "Examples from wikipedia" {
const list = [_][]const u8{
"https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top",
"ldap://[2001:db8::7]/c=GB?objectClass?one",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"http://a/b/c/d;p?q",
};
for (list) |uri| {
_ = try parse(uri);
}
}
// 来源:
// https://tools.ietf.org/html/rfc3986#section-5.4.1
test "Examples from RFC3986" {
const list = [_][]const u8{
"http://a/b/c/g",
"http://a/b/c/g",
"http://a/b/c/g/",
"http://a/g",
"http://g",
"http://a/b/c/d;p?y",
"http://a/b/c/g?y",
"http://a/b/c/d;p?q#s",
"http://a/b/c/g#s",
"http://a/b/c/g?y#s",
"http://a/b/c/;x",
"http://a/b/c/g;x",
"http://a/b/c/g;x?y#s",
"http://a/b/c/d;p?q",
"http://a/b/c/",
"http://a/b/c/",
"http://a/b/",
"http://a/b/",
"http://a/b/g",
"http://a/",
"http://a/",
"http://a/g",
};
for (list) |uri| {
_ = try parse(uri);
}
}
test "Special test" {
// 献给所有阅读代码的人 ♥
_ = try parse("https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be&t=0");
}
test "URI percent encoding" {
try std.testing.expectFmt(
"%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad",
"{f}",
.{std.fmt.alt(
@as(Component, .{ .raw = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad" }),
.formatEscaped,
)},
);
}
test "URI percent decoding" {
{
const expected = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad";
var input = "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad".*;
try std.testing.expectFmt(expected, "{f}", .{std.fmt.alt(
@as(Component, .{ .percent_encoded = &input }),
.formatRaw,
)});
var output: [expected.len]u8 = undefined;
try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);
try std.testing.expectEqualStrings(expected, percentDecodeInPlace(&input));
}
{
const expected = "/abc%";
var input = expected.*;
try std.testing.expectFmt(expected, "{f}", .{std.fmt.alt(
@as(Component, .{ .percent_encoded = &input }),
.formatRaw,
)});
var output: [expected.len]u8 = undefined;
try std.testing.expectEqualStrings(percentDecodeBackwards(&output, &input), expected);
try std.testing.expectEqualStrings(expected, percentDecodeInPlace(&input));
}
}
test "URI query encoding" {
const address = "https://objects.githubusercontent.com/?response-content-type=application%2Foctet-stream";
const parsed = try Uri.parse(address);
// 格式化 URI 并对其执行百分号编码
try std.testing.expectFmt("/?response-content-type=application%2Foctet-stream", "{f}", .{
parsed.fmt(.{ .path = true, .query = true }),
});
}
test "format" {
const uri: Uri = .{
.scheme = "file",
.user = null,
.password = null,
.host = null,
.port = null,
.path = .{ .raw = "/foo/bar/baz" },
.query = null,
.fragment = null,
};
try std.testing.expectFmt("file:/foo/bar/baz", "{f}", .{
uri.fmt(.{ .scheme = true, .path = true, .query = true, .fragment = true }),
});
}
test "URI malformed input" {
try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://]["));
try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://]@["));
try std.testing.expectError(error.InvalidFormat, std.Uri.parse("http://lo]s\x85hc@[/8\x10?0Q"));
}