跳转到内容
标准库Zig 0.17.1官方原文
源码std/fs/path.zig

第 1 行

POSIX 路径是任意 u8 序列,不规定编码。

Windows 路径是任意 u16 序列(WTF-16)。 对于处理 u8 序列的跨平台 API,Zig 将 Windows 路径编码为 WTF-8。 WTF-8 是 UTF-8 的超集,允许编码代理码点, 从而在与 WTF-16 互转时实现无损往返 (前提是 WTF-8 编码的代理码点不构成一对)。

WASI 路径是有效 Unicode 标量值序列, 因此 WASI 无法处理不能编码为 格式良好的 UTF-8/UTF-16 的路径。 https://github.com/WebAssembly/wasi-filesystem/issues/17#issuecomment-1430639353

std.fs.path.Allocator

别名

第 22 行

别名目标 std.mem.Allocator

std.fs.path.assert

别名

第 19 行

别名目标 std.debug.assert

std.fs.path.basename

函数

第 1525 行

pub fn basename(path: []const u8) []const u8

参数

path: []const u8

用法示例

test basename {
    try testBasename("", "");
    try testBasename("/", "");
    try testBasename("/dir/basename.ext", "basename.ext");
    try testBasename("/basename.ext", "basename.ext");
    try testBasename("basename.ext", "basename.ext");
    try testBasename("basename.ext/", "basename.ext");
    try testBasename("basename.ext//", "basename.ext");
    try testBasename("/aaa/bbb", "bbb");
    try testBasename("/aaa/", "aaa");
    try testBasename("/aaa/b", "b");
    try testBasename("/a/b", "b");

    // 在 Windows 上,这是仅包含服务器名称部分的 UNC 路径。
    try testBasename("//a", if (native_os == .windows) "" else "a");

    try testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext");
    try testBasenamePosix("\\basename.ext", "\\basename.ext");
    try testBasenamePosix("basename.ext", "basename.ext");
    try testBasenamePosix("basename.ext\\", "basename.ext\\");
    try testBasenamePosix("basename.ext\\\\", "basename.ext\\\\");
    try testBasenamePosix("foo", "foo");

    try testBasenameWindows("\\dir\\basename.ext", "basename.ext");
    try testBasenameWindows("\\basename.ext", "basename.ext");
    try testBasenameWindows("basename.ext", "basename.ext");
    try testBasenameWindows("basename.ext\\", "basename.ext");
    try testBasenameWindows("basename.ext\\\\", "basename.ext");
    try testBasenameWindows("foo", "foo");
    try testBasenameWindows("C:", "");
    try testBasenameWindows("C:.", ".");
    try testBasenameWindows("C:\\", "");
    try testBasenameWindows("C:\\dir\\base.ext", "base.ext");
    try testBasenameWindows("C:\\basename.ext", "basename.ext");
    try testBasenameWindows("C:basename.ext", "basename.ext");
    try testBasenameWindows("C:basename.ext\\", "basename.ext");
    try testBasenameWindows("C:basename.ext\\\\", "basename.ext");
    try testBasenameWindows("\\\\.", "");
    try testBasenameWindows("\\\\.\\", "");
    try testBasenameWindows("\\\\.\\basename.ext", "basename.ext");
    try testBasenameWindows("\\\\?", "");
    try testBasenameWindows("\\\\?\\", "");
    try testBasenameWindows("\\\\?\\basename.ext", "basename.ext");
    try testBasenameWindows("C:foo", "foo");
    try testBasenameWindows("file:stream", "file:stream");
}

std.fs.path.basenameInner

函数

第 1541 行

fn basenameInner(comptime path_type: PathType, path: []const u8) []const u8

参数

path_type: PathType
path: []const u8

std.fs.path.basenamePosix

函数

第 1533 行

pub fn basenamePosix(path: []const u8) []const u8

参数

path: []const u8

std.fs.path.basenameWindows

函数

第 1537 行

pub fn basenameWindows(path: []const u8) []const u8

参数

path: []const u8

std.fs.path.builtin

常量

第 15 行

std.fs.path.compareDiskDesignators

函数

第 803 行

假定 p1 和 p2 均属于给定的 kind。

fn compareDiskDesignators(comptime T: type, kind: DiskDesignatorKind, p1: []const T, p2: []const T) bool

参数

T: type
kind: DiskDesignatorKind
p1: []const T
p2: []const T

用法示例

test compareDiskDesignators {
    try testCompareDiskDesignators(true, .drive, "c:", "C:\\");
    try testCompareDiskDesignators(true, .drive, "C:\\", "C:");
    try testCompareDiskDesignators(false, .drive, "C:\\", "D:\\");
    // 严格来说,不区分大小写规则也适用于非 ASCII 驱动器字母
    try testCompareDiskDesignators(true, .drive, "λ:\\", "Λ:");

    try testCompareDiskDesignators(true, .unc, "\\\\server", "//server//");
    try testCompareDiskDesignators(true, .unc, "\\\\server\\\\share", "/\\server/share");
    try testCompareDiskDesignators(true, .unc, "\\\\server\\\\share", "/\\server/share\\\\foo");
    try testCompareDiskDesignators(false, .unc, "\\\\server\\sharefoo", "/\\server/share\\foo");
    try testCompareDiskDesignators(false, .unc, "\\\\serverfoo\\\\share", "//server/share");
    try testCompareDiskDesignators(false, .unc, "\\\\server\\", "//server/share");
}

std.fs.path.componentIterator

函数

第 2340 行

pub fn componentIterator(path: []const u8) NativeComponentIterator

参数

path: []const u8

std.fs.path.ComponentIterator

类型函数

第 2166 行

可向前及向后移动的路径分量迭代器。 路径的“根”,POSIX 为 /,Windows 为 C:\、\\server\share\ 等, 会特殊处理,绝不会由 first、last、next 或 previous 返回。 迭代时会跳过连续多个路径分隔符, 将其视为单个分隔符。 返回的所有分量名/路径都是原始路径的切片。 迭代时不对路径进行规范化。

pub fn ComponentIterator(comptime path_type: PathType, comptime T: type) type

参数

path_type: PathType
T: type

字段

path: []const T
root_len: usize

根路径的长度,最多包含一个末尾路径分隔符(例如 C:/)。

root_end_index: usize

根路径的长度,包含所有尾随路径分隔符(例如 C://///)。

start_index: usize = 0
end_index: usize = 0

std.fs.path.ComponentIterator.Component

容器

第 2178 行

字段

name: []const T

当前组件的路径名称,例如“b”。其中永远不会包含路径分隔符。

path: []const T

截至并包含当前组件的完整路径,例如“/a/b”。 末尾永远不会有路径分隔符。

std.fs.path.ComponentIterator.first

函数

第 2232 行

返回从路径开头计算的第一个分量。 例如,路径为 /a/b/c 时,返回 a 分量。 调用 first 后,previous 始终返回 null,next 则返回 first 所返回分量右侧的分量,若存在。

pub fn first(self: *Self) ?Component

参数

self: *Self

std.fs.path.ComponentIterator.init

函数

第 2192 行

调用 init 后,next 将返回根之后的第一个分量 (无需在 init 后调用 first)。 要反向迭代(从路径末尾到开头),请在 init 后调用 last, 再通过调用 previous 迭代。 对于 Windows 路径,假定路径位于 Win32 命名空间。

pub fn init(path: []const T) Self

参数

path: []const T

std.fs.path.ComponentIterator.last

函数

第 2249 行

返回从路径末尾计算的最后一个分量。 例如,路径为 /a/b/c 时,返回 c 分量。 调用 last 后,next 始终返回 null,previous 则返回 last 所返回分量左侧的分量,若存在。

pub fn last(self: *Self) ?Component

参数

self: *Self

std.fs.path.ComponentIterator.next

函数

第 2276 行

返回下一个分量(最近返回分量右侧的 分量);不存在时返回 null。 例如,路径为 /a/b/c,最近返回的分量 为 b 时,这里返回分量 c。

pub fn next(self: *Self) ?Component

参数

self: *Self

std.fs.path.ComponentIterator.peekNext

函数

第 2284 行

类似于 next,但不修改迭代器状态。

pub fn peekNext(self: Self) ?Component

参数

self: Self

std.fs.path.ComponentIterator.peekPrevious

函数

第 2312 行

类似于 previous,但不修改迭代器状态。

pub fn peekPrevious(self: Self) ?Component

参数

self: Self

std.fs.path.ComponentIterator.previous

函数

第 2304 行

返回上一个分量(最近返回分量左侧的 分量);不存在时返回 null。 例如,路径为 /a/b/c,最近返回的分量 为 b 时,这里返回分量 a。

pub fn previous(self: *Self) ?Component

参数

self: *Self

std.fs.path.ComponentIterator.root

函数

第 2223 行

如果路径不是相对路径,则返回其根;否则返回 null。 POSIX 路径的根为 /。 Windows 路径的根形如 C:\、\\server\share\ 等。 UEFI 路径的根为 \。

pub fn root(self: Self) ?[]const T

参数

self: Self

std.fs.path.ComponentIterator.Self

别名

第 2176 行

别名目标 std.fs.path.ComponentIterator

std.fs.path.delimiter

常量

第 42 行

std.fs.path.delimiter_posix

常量

第 41 行

u8

std.fs.path.delimiter_windows

常量

第 40 行

u8

std.fs.path.dirname

函数

第 1424 行

移除文件路径的最后一个分量。

若路径是当前目录中的文件(不包含目录分量), 则返回 null。

若路径是根目录,则返回 null。

pub fn dirname(path: []const u8) ?[]const u8

参数

path: []const u8

std.fs.path.dirnameInner

函数

第 1440 行

fn dirnameInner(comptime path_type: PathType, path: []const u8) ?[]const u8

参数

path_type: PathType
path: []const u8

std.fs.path.dirnamePosix

函数

第 1436 行

pub fn dirnamePosix(path: []const u8) ?[]const u8

参数

path: []const u8

用法示例

test dirnamePosix {
    try testDirnamePosix("/a/b/c", "/a/b");
    try testDirnamePosix("/a/b/c///", "/a/b");
    try testDirnamePosix("/a", "/");
    try testDirnamePosix("/", null);
    try testDirnamePosix("//", null);
    try testDirnamePosix("///", null);
    try testDirnamePosix("////", null);
    try testDirnamePosix("", null);
    try testDirnamePosix("a", null);
    try testDirnamePosix("a/", null);
    try testDirnamePosix("a//", null);
}

std.fs.path.dirnameWindows

函数

第 1432 行

pub fn dirnameWindows(path: []const u8) ?[]const u8

参数

path: []const u8

用法示例

test dirnameWindows {
    try testDirnameWindows("c:\\", null);
    try testDirnameWindows("c:\\\\", null);
    try testDirnameWindows("c:\\foo", "c:\\");
    try testDirnameWindows("c:\\\\foo\\", "c:\\");
    try testDirnameWindows("c:\\foo\\bar", "c:\\foo");
    try testDirnameWindows("c:\\foo\\bar\\", "c:\\foo");
    try testDirnameWindows("c:\\\\foo\\bar\\baz", "c:\\\\foo\\bar");
    try testDirnameWindows("\\", null);
    try testDirnameWindows("\\foo", "\\");
    try testDirnameWindows("\\foo\\", "\\");
    try testDirnameWindows("\\foo\\bar", "\\foo");
    try testDirnameWindows("\\foo\\bar\\", "\\foo");
    try testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar");
    try testDirnameWindows("c:", null);
    try testDirnameWindows("c:foo", "c:");
    try testDirnameWindows("c:foo\\", "c:");
    try testDirnameWindows("c:foo\\bar", "c:foo");
    try testDirnameWindows("c:foo\\bar\\", "c:foo");
    try testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar");
    try testDirnameWindows("file:stream", null);
    try testDirnameWindows("dir\\file:stream", "dir");
    try testDirnameWindows("\\\\unc\\share", null);
    try testDirnameWindows("\\\\unc\\share\\\\", null);
    try testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\");
    try testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\");
    try testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo");
    try testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo");
    try testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar");
    try testDirnameWindows("\\\\.", null);
    try testDirnameWindows("\\\\.\\", null);
    try testDirnameWindows("\\\\.\\device", "\\\\.\\");
    try testDirnameWindows("\\\\.\\device\\", "\\\\.\\");
    try testDirnameWindows("\\\\.\\device\\foo", "\\\\.\\device");
    try testDirnameWindows("\\\\?", null);
    try testDirnameWindows("\\\\?\\", null);
    try testDirnameWindows("\\\\?\\device", "\\\\?\\");
    try testDirnameWindows("\\\\?\\device\\", "\\\\?\\");
    try testDirnameWindows("\\\\?\\device\\foo", "\\\\?\\device");
    try testDirnameWindows("/a/b/", "/a");
    try testDirnameWindows("/a/b", "/a");
    try testDirnameWindows("/a", "/");
    try testDirnameWindows("", null);
    try testDirnameWindows("/", null);
    try testDirnameWindows("////", null);
    try testDirnameWindows("foo", null);
}

std.fs.path.diskDesignator

函数

第 691 行

已弃用;使用 parsePath

pub fn diskDesignator(path: []const u8) []const u8

参数

path: []const u8

std.fs.path.DiskDesignatorKind

容器

第 800 行

字段

drive
unc

std.fs.path.diskDesignatorWindows

函数

第 700 行

已弃用;请使用 parsePathWindows

pub fn diskDesignatorWindows(path: []const u8) []const u8

参数

path: []const u8

std.fs.path.eqlIgnoreCaseWtf16

别名

第 24 行

别名目标 std.os.windows.eqlIgnoreCaseWtf16

std.fs.path.eqlIgnoreCaseWtf8

别名

第 23 行

别名目标 std.os.windows.eqlIgnoreCaseWtf8

std.fs.path.extension

函数

第 2062 行

查找由 . 分隔的文件扩展名,并返回该 . 起的字符串。 文件名以 . 开头且名称中没有其他 . 时, 视为没有扩展名,此时返回 ""。 示例:

  • "main.zig" ⇒ ".zig"
  • "src/main.zig" ⇒ ".zig"
  • ".gitignore" ⇒ ""
  • ".image.png" ⇒ ".png"
  • "keep." ⇒ "."
  • "src.keep.me" ⇒ ".me"
  • "/src/keep.me" ⇒ ".me"
  • "/src/keep.me/" ⇒ ".me" 即使切片长度为零,也保证返回切片的指针位于 path 的起始和末尾指针所界定的地址范围内。
pub fn extension(path: []const u8) []const u8

参数

path: []const u8

用法示例

test extension {
    try testExtension("", "");
    try testExtension(".", "");
    try testExtension("a.", ".");
    try testExtension("abc.", ".");
    try testExtension(".a", "");
    try testExtension(".file", "");
    try testExtension(".gitignore", "");
    try testExtension(".image.png", ".png");
    try testExtension("file.ext", ".ext");
    try testExtension("file.ext.", ".");
    try testExtension("very-long-file.bruh", ".bruh");
    try testExtension("a.b.c", ".c");
    try testExtension("a.b.c/", ".c");

    try testExtension("/", "");
    try testExtension("/.", "");
    try testExtension("/a.", ".");
    try testExtension("/abc.", ".");
    try testExtension("/.a", "");
    try testExtension("/.file", "");
    try testExtension("/.gitignore", "");
    try testExtension("/file.ext", ".ext");
    try testExtension("/file.ext.", ".");
    try testExtension("/very-long-file.bruh", ".bruh");
    try testExtension("/a.b.c", ".c");
    try testExtension("/a.b.c/", ".c");

    try testExtension("/foo/bar/bam/", "");
    try testExtension("/foo/bar/bam/.", "");
    try testExtension("/foo/bar/bam/a.", ".");
    try testExtension("/foo/bar/bam/abc.", ".");
    try testExtension("/foo/bar/bam/.a", "");
    try testExtension("/foo/bar/bam/.file", "");
    try testExtension("/foo/bar/bam/.gitignore", "");
    try testExtension("/foo/bar/bam/file.ext", ".ext");
    try testExtension("/foo/bar/bam/file.ext.", ".");
    try testExtension("/foo/bar/bam/very-long-file.bruh", ".bruh");
    try testExtension("/foo/bar/bam/a.b.c", ".c");
    try testExtension("/foo/bar/bam/a.b.c/", ".c");
}

std.fs.path.fmtAsUtf8Lossy

别名

第 2797 行

将字节编码的路径格式化为 UTF-8,以供显示。 返回给定路径的 Formatter。格式化时将路径转换为有效 UTF-8;若路径包含任何结构不良的 UTF-8,则此转换有损。 根据 Unicode 标准第 3 章“用 U+FFFD 替换最大子部分”及 https://encoding.spec.whatwg.org/#utf-8-decoder 的规定,将结构不良的 UTF-8 字节序列替换为替换字符 U+FFFD。

别名目标 std.unicode.fmtUtf8

std.fs.path.fmtJoin

函数

第 146 行

pub fn fmtJoin(paths: []const []const u8) std.fmt.Alt([]const []const u8, formatJoin)

参数

paths: []const []const u8

std.fs.path.fmtWtf16LeAsUtf8Lossy

别名

第 2804 行

格式化以 WTF-16 LE 编码的路径,供 UTF-8 显示使用。 返回用于 UTF-16 LE 路径(可能格式不正确)的 Formatter。 格式化期间会将路径转换为有效的 UTF-8。如果路径包含 未配对代理码元,则此转换有损。 未配对代理码元会替换为替换字符(U+FFFD)。

别名目标 std.unicode.fmtUtf16Le

std.fs.path.formatJoin

函数

第 150 行

fn formatJoin(paths: []const []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void

参数

paths: []const []const u8
w: *std.Io.Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.fs.path.getDriveLetter

函数

第 827 行

假定 path 为驱动器相对路径或驱动器绝对路径。

fn getDriveLetter(comptime T: type, path: []const T) []const T

参数

T: type
path: []const T

std.fs.path.getWin32PathType

函数

第 2827 行

获取 Win32 命名空间路径的路径类型。 类似 RtlDetermineDosPathNameType_U。 若 T 为 u16,则 path 应采用 WTF-16LE 编码。

pub fn getWin32PathType(comptime T: type, path: []const T) Win32PathType

参数

T: type
path: []const T

用法示例

test getWin32PathType {
    try std.testing.expectEqual(.relative, getWin32PathType(u8, ""));
    try std.testing.expectEqual(.relative, getWin32PathType(u8, "x"));
    try std.testing.expectEqual(.relative, getWin32PathType(u8, "x\\"));

    try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "//."));
    try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "/\\?"));
    try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "\\\\?"));

    try std.testing.expectEqual(.local_device, getWin32PathType(u8, "//./x"));
    try std.testing.expectEqual(.local_device, getWin32PathType(u8, "/\\?\\x"));
    try std.testing.expectEqual(.local_device, getWin32PathType(u8, "\\\\?\\x"));
    // 本地设备路径的根之后必须有路径分隔符,否则会被视为 UNC 路径。
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "\\\\?x"));
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//.x"));

    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//"));
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "\\\\x"));
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//x"));

    try std.testing.expectEqual(.rooted, getWin32PathType(u8, "\\x"));
    try std.testing.expectEqual(.rooted, getWin32PathType(u8, "/"));

    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:"));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:abc"));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:a/b/c"));

    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:\\"));
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:\\abc"));
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:/a/b/c"));

    // 编码为单个 WTF-16 代码单元的非 ASCII 码点被视为有效驱动器盘符。
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "€:\\"));
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("€:\\")));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "€:"));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("€:")));
    // 但编码为两个 WTF-16 代码单元的码点不在此列
    try std.testing.expectEqual(.relative, getWin32PathType(u8, "\u{10000}:\\"));
    try std.testing.expectEqual(.relative, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("\u{10000}:\\")));
}

std.fs.path.isAbsolute

函数

第 274 行

pub fn isAbsolute(path: []const u8) bool

参数

path: []const u8

std.fs.path.isAbsolutePosix

函数

第 311 行

pub fn isAbsolutePosix(path: []const u8) bool

参数

path: []const u8

用法示例

test isAbsolutePosix {
    try testIsAbsolutePosix("", false);
    try testIsAbsolutePosix("/home/foo", true);
    try testIsAbsolutePosix("/home/foo/..", true);
    try testIsAbsolutePosix("bar/", false);
    try testIsAbsolutePosix("./baz", false);
}

std.fs.path.isAbsolutePosixZ

函数

第 315 行

pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool

参数

path_c: [*:0]const u8

std.fs.path.isAbsoluteWindows

函数

第 295 行

pub fn isAbsoluteWindows(path: []const u8) bool

参数

path: []const u8

用法示例

test isAbsoluteWindows {
    try testIsAbsoluteWindows("", false);
    try testIsAbsoluteWindows("/", true);
    try testIsAbsoluteWindows("//", true);
    try testIsAbsoluteWindows("//server", true);
    try testIsAbsoluteWindows("//server/file", true);
    try testIsAbsoluteWindows("\\\\server\\file", true);
    try testIsAbsoluteWindows("\\\\server", true);
    try testIsAbsoluteWindows("\\\\", true);
    try testIsAbsoluteWindows("c", false);
    try testIsAbsoluteWindows("c:", false);
    try testIsAbsoluteWindows("c:\\", true);
    try testIsAbsoluteWindows("c:/", true);
    try testIsAbsoluteWindows("c://", true);
    try testIsAbsoluteWindows("C:/Users/", true);
    try testIsAbsoluteWindows("C:\\Users\\", true);
    try testIsAbsoluteWindows("C:cwd/another", false);
    try testIsAbsoluteWindows("C:cwd\\another", false);
    try testIsAbsoluteWindows("λ:\\", true);
    try testIsAbsoluteWindows("λ:", false);
    try testIsAbsoluteWindows("\u{10000}:\\", false);
    try testIsAbsoluteWindows("directory/directory", false);
    try testIsAbsoluteWindows("directory\\directory", false);
    try testIsAbsoluteWindows("/usr/local", true);
}

std.fs.path.isAbsoluteWindowsImpl

函数

第 282 行

fn isAbsoluteWindowsImpl(comptime T: type, path: []const T) bool

参数

T: type
path: []const T

std.fs.path.isAbsoluteWindowsW

函数

第 299 行

pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool

参数

path_w: [*:0]const u16

std.fs.path.isAbsoluteWindowsWtf16

函数

第 303 行

pub fn isAbsoluteWindowsWtf16(path: []const u16) bool

参数

path: []const u16

std.fs.path.isAbsoluteWindowsZ

函数

第 307 行

pub fn isAbsoluteWindowsZ(path_c: [*:0]const u8) bool

参数

path_c: [*:0]const u8

std.fs.path.isAbsoluteZ

函数

第 266 行

pub fn isAbsoluteZ(path_c: [*:0]const u8) bool

参数

path_c: [*:0]const u8

std.fs.path.isSep

函数

第 45 行

返回给定字节是否为有效路径分隔符

pub fn isSep(byte: u8) bool

参数

byte: u8

std.fs.path.join

函数

第 135 行

使用原生路径分隔符直接组合一系列路径。 为结果分配内存,必须由调用方释放。

pub fn join(allocator: Allocator, paths: []const []const u8) ![]u8

参数

allocator: Allocator
paths: []const []const u8

用法示例

test join {
    {
        const actual: []u8 = try join(testing.allocator, &[_][]const u8{});
        defer testing.allocator.free(actual);
        try testing.expectEqualSlices(u8, "", actual);
    }
    {
        const actual: [:0]u8 = try joinZ(testing.allocator, &[_][]const u8{});
        defer testing.allocator.free(actual);
        try testing.expectEqualSlices(u8, "", actual);
    }
    for (&[_]bool{ false, true }) |zero| {
        try testJoinMaybeZWindows(&[_][]const u8{}, "", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b\\", "\\c" }, "c:\\a\\b\\c", zero);

        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b\\", "c" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\", "b\\", "c" }, "c:\\a\\b\\c", zero);

        try testJoinMaybeZWindows(
            &[_][]const u8{ "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "ab.zig" },
            "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\ab.zig",
            zero,
        );

        try testJoinMaybeZUefi(&[_][]const u8{ "EFI", "Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);
        try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);
        try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\", "\\Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);
        try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\", "\\Boot\\", "\\bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);

        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b/", "c" }, "c:\\a\\b/c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "b\\", "/c" }, "c:\\a/b\\c", zero);

        try testJoinMaybeZWindows(&[_][]const u8{ "", "c:\\", "", "", "a", "b\\", "c", "" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "", "b\\", "", "/c" }, "c:\\a/b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "", "" }, "", zero);

        try testJoinMaybeZPosix(&[_][]const u8{}, "", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/b/", "c" }, "/a/b/c", zero);

        try testJoinMaybeZPosix(&[_][]const u8{ "/", "a", "b/", "c" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "b/", "c" }, "/a/b/c", zero);

        try testJoinMaybeZPosix(
            &[_][]const u8{ "/home/andy/dev/zig/build/lib/zig/std", "ab.zig" },
            "/home/andy/dev/zig/build/lib/zig/std/ab.zig",
            zero,
        );

        try testJoinMaybeZPosix(&[_][]const u8{ "a", "/c" }, "a/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "a/", "/c" }, "a/c", zero);

        try testJoinMaybeZPosix(&[_][]const u8{ "", "/", "a", "", "b/", "c", "" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "", "", "b/", "c" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "", "" }, "", zero);
    }
}

std.fs.path.joinSepMaybeZ

函数

第 71 行

与 mem.join 不同:若连续两条路径的前一条末尾 或后一条开头已有分隔符,则不会重复添加。

fn joinSepMaybeZ(allocator: Allocator, separator: u8, comptime sepPredicate: fn (u8) bool, paths: []const []const u8, zero: bool) ![]u8

参数

allocator: Allocator
separator: u8
sepPredicate: fn (u8) bool
paths: []const []const u8
zero: bool

std.fs.path.joinZ

函数

第 141 行

使用原生路径分隔符和空终止符,直接组合一系列路径。 为结果分配内存,调用方必须释放。

pub fn joinZ(allocator: Allocator, paths: []const []const u8) ![:0]u8

参数

allocator: Allocator
paths: []const []const u8

std.fs.path.mem

别名

第 21 行

别名目标 std.mem

std.fs.path.native_os

常量

第 16 行

std.fs.path.NativeComponentIterator

类型

第 2334 行

std.fs.path.parsePath

函数

第 474 行

Windows 上调用 parsePathWindows,POSIX 上调用 parsePathPosix。

返回平台相关结构体,包含 root 和 kind 两个字段。 root 是 path 的切片;POSIX 绝对路径中为 /,Windows 路径中 则为 C:\、\\server\share\ 等。 若路径种类为 .relative,root 长度为零。

pub fn parsePath(path: []const u8) switch (native_os) { .windows => WindowsPath2(u8), else => PosixPath, }

参数

path: []const u8

std.fs.path.parsePathPosix

函数

第 489 行

pub fn parsePathPosix(path: []const u8) PosixPath

参数

path: []const u8

用法示例

test parsePathPosix {
    {
        const parsed = parsePathPosix("a/b");
        try testing.expectEqual(.relative, parsed.kind);
        try testing.expectEqualStrings("", parsed.root);
    }
    {
        const parsed = parsePathPosix("/a/b");
        try testing.expectEqual(.absolute, parsed.kind);
        try testing.expectEqualStrings("/", parsed.root);
    }
    {
        const parsed = parsePathPosix("///a/b");
        try testing.expectEqual(.absolute, parsed.kind);
        try testing.expectEqualStrings("/", parsed.root);
    }
}

std.fs.path.parsePathWindows

函数

第 522 行

pub fn parsePathWindows(comptime T: type, path: []const T) WindowsPath2(T)

参数

T: type
path: []const T

用法示例

test parsePathWindows {
    {
        const path = "//a/b";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("//a/b", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\b";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\b", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\/a/b/c";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\/a/b/", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\b\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\b\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\/b\\/";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\/b\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\кириллица\\ελληνικά\\português";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\кириллица\\ελληνικά\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "/usr/local";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.rooted, parsed.kind);
        try testing.expectEqualStrings("/", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\.";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.root_local_device, parsed.kind);
        try testing.expectEqualStrings("\\\\.", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\.\\a";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.local_device, parsed.kind);
        try testing.expectEqualStrings("\\\\.\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "c:../";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_relative, parsed.kind);
        try testing.expectEqualStrings("c:", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "C:\\../";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_absolute, parsed.kind);
        try testing.expectEqualStrings("C:\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        // 编码为单个 WTF-16 代码单元的非 ASCII 码点被视为有效驱动器盘符。
        const path = "€:\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_absolute, parsed.kind);
        try testing.expectEqualStrings("€:\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "€:";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_relative, parsed.kind);
        try testing.expectEqualStrings("€:", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        // 但编码为两个 WTF-16 代码单元的码点不在此列
        const path = "\u{10000}:\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.relative, parsed.kind);
        try testing.expectEqualStrings("", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\u{10000}:";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.relative, parsed.kind);
        try testing.expectEqualStrings("", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        // 假定路径位于 Win32 命名空间,因此尽管它
        // 可能是 NT 命名空间路径,仍按根路径处理。
        const path = "\\??\\foo";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.rooted, parsed.kind);
        try testing.expectEqualStrings("\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
}

std.fs.path.parseUNC

函数

第 714 行

断言 path 以两个路径分隔符开头

fn parseUNC(comptime T: type, path: []const T) WindowsUNC(T)

参数

T: type
path: []const T

用法示例

test parseUNC {
    {
        const unc = parseUNC(u8, "//");
        try std.testing.expectEqualStrings("", unc.server);
        try std.testing.expect(!unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\s");
        try std.testing.expectEqualStrings("s", unc.server);
        try std.testing.expect(!unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\s/");
        try std.testing.expectEqualStrings("s", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\/server\\share");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("share", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "/\\server\\share/");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("share", unc.share);
        try std.testing.expect(unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\server/\\share\\/");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("share", unc.share);
        try std.testing.expect(unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\server\\/\\\\");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
}

std.fs.path.PathType

容器

第 53 行

字段

windows
uefi
posix

std.fs.path.PathType.isSep

函数

第 60 行

若 c 是 path_type 的有效路径分隔符,返回 true。 若 T 为 u16,假定 c 为小端序。

pub inline fn isSep(comptime path_type: PathType, comptime T: type, c: T) bool

参数

path_type: PathType
T: type
c: T

std.fs.path.PosixPath

容器

第 484 行

字段

kind: enum { relative, absolute }
root: []const u8

std.fs.path.relative

别名

第 871 行

已弃用,改用 relativeAlloc。

别名目标 std.fs.path.relativeAlloc

std.fs.path.relativeAlloc

函数

第 1617 行

以已分配切片形式,返回从 from 到 to 的非绝对路径。

除内存分配外,此函数为纯函数:结果仅取决于输入参数。

若 from 与 to 分别经 resolve 解析后得到相同路径,则返回零长度字符串。

参见 relativePosix 和 relativeWindows,了解操作系统专用细节及 environ_map 的使用方式。

另见:

pub fn relativeAlloc( gpa: Allocator, cwd: []const u8, environ_map: ?*const std.process.Environ.Map, from: []const u8, to: []const u8, ) Allocator.Error![]u8

参数

gpa: Allocator
cwd: []const u8
environ_map: ?*const std.process.Environ.Map
from: []const u8
to: []const u8

错误

OutOfMemory

std.fs.path.relativeAllocPosix

函数

第 1879 行

按照 POSIX 规则,返回从 from 到 to 的非绝对路径,作为已分配切片。

除内存分配外,这是纯函数;结果仅取决于输入参数。

如果 from 和 to 分别调用 resolve 后解析为同一路径, 则返回零长度字符串。

另请参见:

pub fn relativeAllocPosix(gpa: Allocator, cwd: []const u8, from: []const u8, to: []const u8) Allocator.Error![]u8

参数

gpa: Allocator
cwd: []const u8
from: []const u8
to: []const u8

错误

OutOfMemory

std.fs.path.relativeAllocWindows

函数

第 1677 行

按照 Windows 规则,将从 from 到 to 的非绝对路径作为已分配的切片返回。

除内存分配外,这是纯函数;结果完全由输入参数决定。

如果 from 和 to 分别解析后(调用各自的 resolve)得到同一路径,则返回长度为零的字符串。

结果不保证是相对路径,因为路径可能位于不同卷上。此时结果将是 to 的规范化绝对路径。

每个驱动器的当前工作目录存储在特殊的半隐藏环境变量中,格式为 =<drive-letter>:,例如 =C:。 这类当前工作目录纯粹是 shell 概念,因此不能保证它已设置,也不能保证其准确性。这就是提供 environ_map 参数的唯一原因。若该环境变量不存在,则将 null 视为等同情况。

另见: relativeAlloc relativeAppendWindows

pub fn relativeAllocWindows( gpa: Allocator, cwd: []const u8, environ_map: ?*const std.process.Environ.Map, from: []const u8, to: []const u8, ) Allocator.Error![]u8

参数

gpa: Allocator
cwd: []const u8
environ_map: ?*const std.process.Environ.Map
from: []const u8
to: []const u8

错误

OutOfMemory

std.fs.path.relativeAppend

函数

第 1644 行

将从 from 到 to 的非绝对路径追加到给定数组列表。

除修改给定数组列表外,此函数为纯函数:结果仅取决于输入参数,不执行文件系统操作。

若 from 与 to 分别经 resolveAppend 解析后得到相同路径,则返回零长度字符串。

参见 relativeAppendPosix 和 relativeAppendWindows,了解操作系统专用细节及 environ_map 的使用方式。

另见:

pub fn relativeAppend( gpa: Allocator, al: *std.ArrayList(u8), cwd: []const u8, environ_map: ?*const std.process.Environ.Map, from: []const u8, to: []const u8, ) Allocator.Error!void

参数

gpa: Allocator
al: *std.ArrayList(u8)
cwd: []const u8
environ_map: ?*const std.process.Environ.Map
from: []const u8
to: []const u8

错误

OutOfMemory

std.fs.path.relativeAppendPosix

函数

第 1898 行

按 POSIX 规则,将从 from 到 to 的非绝对路径追加到给定数组列表。

除修改给定数组列表外,此函数为纯函数:结果仅取决于输入参数,不执行文件系统操作。

若 from 与 to 分别经 resolveAppend 解析后得到相同路径,则不向数组列表追加任何内容。

另见:

pub fn relativeAppendPosix( gpa: Allocator, al: *std.ArrayList(u8), cwd: []const u8, from: []const u8, to: []const u8, ) Allocator.Error!void

参数

gpa: Allocator
al: *std.ArrayList(u8)
cwd: []const u8
from: []const u8
to: []const u8

错误

OutOfMemory

std.fs.path.relativeAppendWindows

函数

第 1791 行

按照 Windows 规则,将从 from 到 to 的非绝对路径追加到提供的数组列表。

除内存分配外,这是纯函数;结果完全由输入参数决定。

如果 from 和 to 分别解析后(调用各自的 resolve)得到同一路径,则返回长度为零的字符串。

结果不保证是相对路径,因为路径可能位于不同卷上。此时结果将是 to 的规范化绝对路径。

每个驱动器的当前工作目录存储在特殊的半隐藏环境变量中,格式为 =<drive-letter>:,例如 =C:。 这类当前工作目录纯粹是 shell 概念,因此不能保证它已设置,也不能保证其准确性。这就是提供 environ_map 参数的唯一原因。若该环境变量不存在,则将 null 视为等同情况。

另见: relativeAppend relativeAllocWindows

pub fn relativeAppendWindows( gpa: Allocator, al: *std.ArrayList(u8), cwd: []const u8, environ_map: ?*const std.process.Environ.Map, from: []const u8, to: []const u8, ) Allocator.Error!void

参数

gpa: Allocator
al: *std.ArrayList(u8)
cwd: []const u8
environ_map: ?*const std.process.Environ.Map
from: []const u8
to: []const u8

错误

OutOfMemory

std.fs.path.relativePosix

别名

第 873 行

已弃用,请改用 relativeAllocPosix。

别名目标 std.fs.path.relativeAllocPosix

std.fs.path.relativeWindows

别名

第 875 行

已弃用,请改用 relativeAllocWindows。

别名目标 std.fs.path.relativeAllocWindows

std.fs.path.resolve

别名

第 864 行

已弃用,改用 resolveAlloc。

别名目标 std.fs.path.resolveAlloc

std.fs.path.resolveAlloc

函数

第 881 行

在 Windows 上调用 resolveAllocWindows;否则调用 resolveAllocPosix。

另请参见: resolveAppend

pub fn resolveAlloc(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8

参数

gpa: Allocator
paths: []const []const u8

错误

OutOfMemory

std.fs.path.resolveAllocPosix

函数

第 1172 行

在无符号链接的虚拟文件系统上模拟一系列相对目录切换,将结果 作为已分配切片返回。

会解析 "." 和 "..",但不会将相对路径变为绝对路径。若结果路径为相对路径, 且没有更早的分量可抵消,则保留 ".." 分量。

结果不含末尾路径分隔符。

此函数不执行系统调用。在真实文件系统上执行相同的路径查找序列, 可能因符号链接而产生不同结果。

另请参见:

pub fn resolveAllocPosix(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8

参数

gpa: Allocator
paths: []const []const u8

错误

OutOfMemory

用法示例

test resolveAllocPosix {
    try testResolvePosix(&.{ "/a/b", "c" }, "/a/b/c");
    try testResolvePosix(&.{ "/a/b", "c", "//d", "e///" }, "/d/e");
    try testResolvePosix(&.{ "/a/b/c", "..", "../" }, "/a");
    try testResolvePosix(&.{ "/", "..", ".." }, "/");
    try testResolvePosix(&.{"/a/b/c/"}, "/a/b/c");

    try testResolvePosix(&.{ "/var/lib", "../", "file/" }, "/var/file");
    try testResolvePosix(&.{ "/var/lib", "/../", "file/" }, "/file");
    try testResolvePosix(&.{ "/some/dir", ".", "/absolute/" }, "/absolute");
    try testResolvePosix(&.{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }, "/foo/tmp.3/cycles/root.js");

    // 保持相对路径为相对形式。
    try testResolvePosix(&.{"a/b"}, "a/b");
    try testResolvePosix(&.{"."}, ".");
    try testResolvePosix(&.{ ".", "src/test.zig", "..", "../test/cases.zig" }, "test/cases.zig");
}

std.fs.path.resolveAllocWindows

函数

第 925 行

在没有符号链接的虚拟文件系统中模拟一系列相对目录切换,以分配的切片返回结果。

路径分隔符规范化为 '\',驱动器字母规范化为大写。

解析 "." 和 "..",但不会将相对路径变为绝对路径。如果结果路径是相对路径或驱动器相对路径,".." 分量可能仍然保留。

除以下情况外,结果末尾不包含路径分隔符:

  • 结果是没有路径分量的驱动器绝对路径,例如 C:\。
  • 结果是仅包含服务器名称的 UNC 路径,且输入末尾带分隔符,例如 \\server\。
  • 结果是共享名称后没有其他分量的 UNC 路径,且输入末尾带分隔符,例如 \\server\share\。

每个驱动器有自己的当前工作目录,仅通过给定路径解析。如果包含驱动器相对路径,但无法仅依据输入路径解析,则结果仍为驱动器相对路径。同理,无法仅依据输入解析的根相对路径,结果仍为根相对路径。

此函数不执行系统调用。在真实文件系统中执行同样的路径查找序列,可能因符号链接而得到不同结果。

另见:

pub fn resolveAllocWindows(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8

参数

gpa: Allocator
paths: []const []const u8

错误

OutOfMemory

用法示例

test resolveAllocWindows {
    try testResolveWindows(
        &[_][]const u8{ "Z:\\", "/usr/local", "lib\\zig\\std\\array_list.zig" },
        "Z:\\usr\\local\\lib\\zig\\std\\array_list.zig",
    );
    try testResolveWindows(
        &[_][]const u8{ "z:\\", "usr/local", "lib\\zig" },
        "Z:\\usr\\local\\lib\\zig",
    );

    try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }, "C:\\hi\\ok");
    try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c\\", ".\\..\\foo" }, "C:\\a\\b\\foo");
    try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }, "C:\\blah\\a");
    try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }, "C:\\blah\\a");
    try testResolveWindows(&[_][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }, "D:\\e.exe");
    try testResolveWindows(&[_][]const u8{ "c:/ignore", "c:/some/file" }, "C:\\some\\file");
    // 第一个路径“设置”当前工作目录,因此驱动器相对路径随后相对于它。
    try testResolveWindows(&[_][]const u8{ "d:/foo", "d:some/dir//", "D:another" }, "D:\\foo\\some\\dir\\another");
    try testResolveWindows(&[_][]const u8{ "//server/share", "..", "relative\\" }, "\\\\server\\share\\relative");
    try testResolveWindows(&[_][]const u8{ "\\\\server/share", "..", "relative\\" }, "\\\\server\\share\\relative");
    try testResolveWindows(&[_][]const u8{ "\\\\server/share/ignore", "//server/share/bar" }, "\\\\server\\share\\bar");
    try testResolveWindows(&[_][]const u8{ "\\/server\\share/", "..", "relative" }, "\\\\server\\share\\relative");
    try testResolveWindows(&[_][]const u8{ "\\\\server\\share", "C:drive-relative" }, "C:drive-relative");
    try testResolveWindows(&[_][]const u8{ "c:/", "//" }, "\\\\");
    try testResolveWindows(&[_][]const u8{ "c:/", "//server" }, "\\\\server");
    try testResolveWindows(&[_][]const u8{ "c:/", "//server/share" }, "\\\\server\\share");
    try testResolveWindows(&[_][]const u8{ "c:/", "//server//share////" }, "\\\\server\\share\\");
    try testResolveWindows(&[_][]const u8{ "c:/", "///some//dir" }, "\\\\\\some\\dir");
    try testResolveWindows(&[_][]const u8{ "c:foo", "bar" }, "C:foo\\bar");
    try testResolveWindows(&[_][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }, "C:\\foo\\tmp.3\\cycles\\root.js");
    // 若无法提供驱动器专属的当前工作目录,则驱动器相对路径仍保持驱动器相对形式
    try testResolveWindows(&[_][]const u8{ "relative", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "../..\\..", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "../..\\..", "\\rooted", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "C:\\foo", "../..\\..", "\\rooted", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "D:relevant", "../..\\..", "d:foo" }, "D:..\\..\\foo");
    try testResolveWindows(&[_][]const u8{ "D:relevant", "../..\\..", "\\\\.\\ignored", "C:\\ignored", "C:ignored", "\\\\ignored", "d:foo" }, "D:..\\..\\foo");
    try testResolveWindows(&[_][]const u8{ "ignored", "\\\\.\\ignored", "C:\\ignored", "C:ignored", "\\\\ignored", "d:foo" }, "D:foo");
    // 没有可用于解析"根"的绝对路径时,根路径仍保持根路径形式
    try testResolveWindows(&[_][]const u8{ "/foo", "bar" }, "\\foo\\bar");
    // 以 UNC 路径为根
    try testResolveWindows(&[_][]const u8{ "//server/share/ignore", "/foo", "bar" }, "\\\\server\\share\\foo\\bar");
    try testResolveWindows(&[_][]const u8{ "//server/share/", "/foo" }, "\\\\server\\share\\foo");
    try testResolveWindows(&[_][]const u8{ "//server/share", "/foo" }, "\\\\server\\share\\foo");
    try testResolveWindows(&[_][]const u8{ "//server/", "/foo" }, "\\\\server\\foo");
    try testResolveWindows(&[_][]const u8{ "//server", "/foo" }, "\\\\server\\foo");
    try testResolveWindows(&[_][]const u8{ "//", "/foo" }, "\\\\foo");
    // 相对于驱动器相对路径确定根
    try testResolveWindows(&[_][]const u8{ "C:", "/foo", "bar" }, "C:\\foo\\bar");
    try testResolveWindows(&[_][]const u8{ "C:\\ignore", "C:", "/foo", "bar" }, "C:\\foo\\bar");
    try testResolveWindows(&[_][]const u8{ "C:\\ignore", "\\foo", "C:bar" }, "C:\\foo\\bar");
    // 仅最后一个有根路径有意义
    try testResolveWindows(&[_][]const u8{ "\\ignore", "\\foo" }, "\\foo");
    try testResolveWindows(&[_][]const u8{ "c:ignore", "ignore", "\\ignore", "\\foo" }, "C:\\foo");
    // 仅当之前存在驱动器路径时,根路径才与驱动器相对路径有关
    try testResolveWindows(&[_][]const u8{ "\\ignore", "C:foo" }, "C:foo");
    try testResolveWindows(&[_][]const u8{ "\\ignore", "\\ignore2", "C:foo" }, "C:foo");
    try testResolveWindows(&[_][]const u8{ "c:ignore", "\\ignore", "\\rooted", "C:foo" }, "C:\\rooted\\foo");
    try testResolveWindows(&[_][]const u8{ "c:\\ignore", "\\ignore", "\\rooted", "C:foo" }, "C:\\rooted\\foo");
    try testResolveWindows(&[_][]const u8{ "d:\\ignore", "\\ignore", "\\ignore2", "C:foo" }, "C:foo");
    // 根本地设备路径
    try testResolveWindows(&[_][]const u8{"\\/."}, "\\\\.");
    try testResolveWindows(&[_][]const u8{ "\\/.", "C:drive-relative" }, "C:drive-relative");
    try testResolveWindows(&[_][]const u8{"/\\?"}, "\\\\?");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\.", "foo" }, "\\\\.\\foo");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\?", "foo" }, "\\\\?\\foo");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "//.", "ignore", "\\foo" }, "\\\\.\\foo");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\?", "ignore", "\\foo" }, "\\\\?\\foo");

    // 保持相对路径为相对形式。
    try testResolveWindows(&[_][]const u8{"a/b"}, "a\\b");
    try testResolveWindows(&[_][]const u8{".."}, "..");
    try testResolveWindows(&[_][]const u8{"../.."}, "..\\..");
    try testResolveWindows(&[_][]const u8{ "C:foo", "../.." }, "C:..");
    try testResolveWindows(&[_][]const u8{ "d:foo", "../..\\.." }, "D:..\\..");

    // 本地设备路径将 \\.\ 或 \\?\ 视为“根”,其后所有内容均按普通路径部分处理。
    try testResolveWindows(&[_][]const u8{ "\\\\?\\C:\\foo", "../bar", "baz" }, "\\\\?\\C:\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "\\\\.\\C:/foo", "../../../../bar", "baz" }, "\\\\.\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "//./C:/foo", "../../../../bar", "baz" }, "\\\\.\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "\\\\.\\foo", ".." }, "\\\\.");
    try testResolveWindows(&[_][]const u8{ "\\\\.\\foo", "..\\.." }, "\\\\.");

    // 假定路径为 Win32 路径,因此将疑似 NT 路径的路径视为根相对路径。
    try testResolveWindows(&[_][]const u8{ "\\??\\C:\\foo", "/bar", "baz" }, "\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "C:\\", "\\??\\C:\\foo", "bar" }, "C:\\??\\C:\\foo\\bar");
}

std.fs.path.resolveAppend

函数

第 892 行

在 Windows 上调用 resolveAppendWindows;否则调用 resolveAppendPosix。

另请参见: resolveAlloc

pub fn resolveAppend(gpa: Allocator, al: *std.ArrayList(u8), paths: []const []const u8) Allocator.Error!void

参数

gpa: Allocator
al: *std.ArrayList(u8)
paths: []const []const u8

错误

OutOfMemory

std.fs.path.resolveAppendPosix

函数

第 1194 行

在无符号链接的虚拟文件系统上模拟一系列相对目录切换,将结果追加到 提供的数组列表中。

会解析 "." 和 "..",但不会将相对路径变为绝对路径。若结果路径为相对路径, 且没有更早的分量可抵消,则保留 ".." 分量。

结果不含末尾路径分隔符。

此函数不执行系统调用。在真实文件系统上执行相同的路径查找序列, 可能因符号链接而产生不同结果。

另请参见:

pub fn resolveAppendPosix(gpa: Allocator, al: *std.ArrayList(u8), paths: []const []const u8) Allocator.Error!void

参数

gpa: Allocator
al: *std.ArrayList(u8)
paths: []const []const u8

错误

OutOfMemory

std.fs.path.resolveAppendWindows

函数

第 959 行

在不含符号链接的虚拟文件系统上模拟一系列相对目录切换,并将结果 追加到提供的数组列表中。

路径分隔符规范化为 '\',盘符规范化为大写字母。

解析 "." 和 "..",但不会将相对路径转换为绝对路径。如果解析结果 是相对路径或驱动器相对路径,其中可能仍保留 ".." 分量。

结果不含末尾路径分隔符,但以下情况除外:

  • 结果是没有路径分量的驱动器绝对路径,例如 C:\。
  • 结果是只包含服务器名的 UNC 路径,且输入路径带有末尾分隔符, 例如 \\server\。
  • 结果是共享名之后没有路径分量的 UNC 路径,且输入路径带有 末尾分隔符,例如 \\server\share\。

每个驱动器都有独立的当前工作目录,且仅通过提供的路径确定。 如果解析结果包含无法仅凭这些路径确定的驱动器相对路径, 结果将保持为驱动器相对路径。同样,如果解析结果包含无法仅凭 这些路径确定的根相对路径,结果将保持为根相对路径。

此函数不执行任何系统调用。在实际文件系统上执行这些路径查找, 可能因符号链接而得到不同结果。

另请参见:

pub fn resolveAppendWindows(gpa: Allocator, al: *std.ArrayList(u8), paths: []const []const u8) Allocator.Error!void

参数

gpa: Allocator
al: *std.ArrayList(u8)
paths: []const []const u8

错误

OutOfMemory

std.fs.path.resolvePosix

别名

第 868 行

已弃用,改用 resolveAllocPosix。

别名目标 std.fs.path.resolveAllocPosix

std.fs.path.resolveWindows

别名

第 866 行

已弃用,请改用 resolveAllocWindows。

别名目标 std.fs.path.resolveAllocWindows

std.fs.path.sep

常量

第 28 行

std.fs.path.sep_posix

常量

第 27 行

u8

std.fs.path.sep_str

常量

第 35 行

std.fs.path.sep_str_posix

常量

第 34 行

std.fs.path.sep_str_windows

常量

第 33 行

std.fs.path.sep_windows

常量

第 26 行

u8

std.fs.path.std

别名

第 18 行

别名目标 std

std.fs.path.stem

函数

第 2119 行

返回此路径的最后一个分量,并移除扩展名(若存在):

  • "hello/world/lib.tar.gz" ⇒ "lib.tar"
  • "hello/world/lib.tar" ⇒ "lib"
  • "hello/world/lib" ⇒ "lib"
pub fn stem(path: []const u8) []const u8

参数

path: []const u8

用法示例

test stem {
    try testStem("hello/world/lib.tar.gz", "lib.tar");
    try testStem("hello/world/lib.tar", "lib");
    try testStem("hello/world/lib", "lib");
    try testStem("hello/lib/", "lib");
    try testStem("hello...", "hello..");
    try testStem("hello.", "hello");
    try testStem("/hello.", "hello");
    try testStem("hello/world/.gitignore", ".gitignore");
    try testStem("/.gitignore", ".gitignore");
    try testStem(".gitignore", ".gitignore");
    try testStem(".gitignore/", ".gitignore");
    try testStem("hello/world/.image.png", ".image");
    try testStem("/.image.png", ".image");
    try testStem(".image.png", ".image");
    try testStem(".image.png/", ".image");
    try testStem("file.ext", "file");
    try testStem("file.ext.", "file.ext");
    try testStem("a.b.c", "a.b");
    try testStem("a.b.c/", "a.b");
    try testStem(".a", ".a");
    try testStem("///", "");
    try testStem("..", ".");
    try testStem(".", ".");
    try testStem(" ", " ");
    try testStem("", "");
}

std.fs.path.testBasename

函数

第 1594 行

fn testBasename(input: []const u8, expected_output: []const u8) !void

参数

input: []const u8
expected_output: []const u8

std.fs.path.testBasenamePosix

函数

第 1598 行

fn testBasenamePosix(input: []const u8, expected_output: []const u8) !void

参数

input: []const u8
expected_output: []const u8

std.fs.path.testBasenameWindows

函数

第 1602 行

fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void

参数

input: []const u8
expected_output: []const u8

std.fs.path.testCompareDiskDesignators

函数

第 854 行

fn testCompareDiskDesignators(expected_result: bool, kind: DiskDesignatorKind, p1: []const u8, p2: []const u8) !void

参数

expected_result: bool
kind: DiskDesignatorKind
p1: []const u8
p2: []const u8

std.fs.path.testDirnamePosix

函数

第 1509 行

fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) !void

参数

input: []const u8
expected_output: ?[]const u8

std.fs.path.testDirnameWindows

函数

第 1517 行

fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) !void

参数

input: []const u8
expected_output: ?[]const u8

std.fs.path.testExtension

函数

第 2069 行

fn testExtension(path: []const u8, expected: []const u8) !void

参数

path: []const u8
expected: []const u8

std.fs.path.testing

别名

第 20 行

别名目标 std.testing

std.fs.path.testIsAbsolutePosix

函数

第 361 行

fn testIsAbsolutePosix(path: []const u8, expected_result: bool) !void

参数

path: []const u8
expected_result: bool

std.fs.path.testIsAbsoluteWindows

函数

第 353 行

fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) !void

参数

path: []const u8
expected_result: bool

std.fs.path.testJoinMaybeZPosix

函数

第 195 行

fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bool) !void

参数

paths: []const []const u8
expected: []const u8
zero: bool

std.fs.path.testJoinMaybeZPosix.isSep

函数

第 197 行

fn isSep(byte: u8) bool

参数

byte: u8

std.fs.path.testJoinMaybeZUefi

函数

第 173 行

fn testJoinMaybeZUefi(paths: []const []const u8, expected: []const u8, zero: bool) !void

参数

paths: []const []const u8
expected: []const u8
zero: bool

std.fs.path.testJoinMaybeZUefi.isSep

函数

第 175 行

fn isSep(byte: u8) bool

参数

byte: u8

std.fs.path.testJoinMaybeZWindows

函数

第 184 行

fn testJoinMaybeZWindows(paths: []const []const u8, expected: []const u8, zero: bool) !void

参数

paths: []const []const u8
expected: []const u8
zero: bool

std.fs.path.testJoinMaybeZWindows.isSep

函数

第 186 行

fn isSep(byte: u8) bool

参数

byte: u8

std.fs.path.testRelativePosix

函数

第 2007 行

fn testRelativePosix(from: []const u8, to: []const u8, expected_output: []const u8) !void

参数

from: []const u8
to: []const u8
expected_output: []const u8

std.fs.path.testRelativeWindows

函数

第 2028 行

fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []const u8) !void

参数

from: []const u8
to: []const u8
expected_output: []const u8

std.fs.path.testResolvePosix

函数

第 1397 行

fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void

参数

paths: []const []const u8
expected: []const u8

std.fs.path.testResolveWindows

函数

第 1376 行

fn testResolveWindows(paths: []const []const u8, expected: []const u8) !void

参数

paths: []const []const u8
expected: []const u8

std.fs.path.testStem

函数

第 2126 行

fn testStem(path: []const u8, expected: []const u8) !void

参数

path: []const u8
expected: []const u8

std.fs.path.testWindowsParsePathHarmony

函数

第 674 行

fn testWindowsParsePathHarmony(wtf8: []const u8) !void

参数

wtf8: []const u8

std.fs.path.Win32PathType

容器

第 2807 行

类似 RTL_PATH_TYPE,但不包含 UNKNOWN 路径类型。

字段

unc_absolute

\\server\share\foo

drive_absolute

C:\foo

drive_relative

C:foo

rooted

\foo

relative

foo

local_device

\\.\foo, \\?\foo

root_local_device

\\., \\?

std.fs.path.windowsParsePath

函数

第 379 行

已弃用;参见 parsePathWindows

pub fn windowsParsePath(path: []const u8) WindowsPath

参数

path: []const u8

用法示例

test windowsParsePath {
    {
        const parsed = windowsParsePath("//a/b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "//a/b"));
    }
    {
        const parsed = windowsParsePath("\\\\a\\b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\b"));
    }
    {
        const parsed = windowsParsePath("\\\\a/b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a/b"));
    }
    {
        const parsed = windowsParsePath("\\/a\\");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\/a\\"));
    }
    {
        const parsed = windowsParsePath("\\\\a\\\\b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\\\b"));
    }
    {
        const parsed = windowsParsePath("\\\\a\\\\b\\c");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\\\b"));
    }
    {
        const parsed = windowsParsePath("/usr/local");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.None);
        try testing.expect(mem.eql(u8, parsed.disk_designator, ""));
    }
    {
        const parsed = windowsParsePath("c:../");
        try testing.expect(!parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.Drive);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "c:"));
    }
}

std.fs.path.WindowsPath

容器

第 366 行

已弃用;请参阅 WindowsPath2

字段

is_abs: bool
kind: Kind
disk_designator: []const u8

std.fs.path.WindowsPath.Kind

容器

第 371 行

字段

None
Drive
NetworkShare

std.fs.path.WindowsPath2

类型函数

第 515 行

pub fn WindowsPath2(comptime T: type) type

参数

T: type

字段

kind: Win32PathType
root: []const T

std.fs.path.windowsResolveAgainstCwd

函数

第 1804 行

fn windowsResolveAgainstCwd( gpa: Allocator, cwd: []const u8, environ_map: ?*const std.process.Environ.Map, path: []const u8, parsed: WindowsPath2(u8), ) ![]u8

参数

gpa: Allocator
cwd: []const u8
environ_map: ?*const std.process.Environ.Map
path: []const u8
parsed: WindowsPath2(u8)

std.fs.path.WindowsUNC

类型函数

第 704 行

fn WindowsUNC(comptime T: type) type

参数

T: type

字段

server: []const T
sep_after_server: bool
share: []const T
sep_after_share: bool
源码

std/fs/path.zig

//! POSIX 路径是任意 `u8` 序列,不规定编码。
//!
//! Windows 路径是任意 `u16` 序列(WTF-16)。
//! 对于处理 `u8` 序列的跨平台 API,Zig 将 Windows
//! 路径编码为 [WTF-8](https://wtf-8.codeberg.page/)。
//! WTF-8 是 UTF-8 的超集,允许编码代理码点,
//! 从而在与 WTF-16 互转时实现无损往返
//! (前提是 WTF-8 编码的代理码点不构成一对)。
//!
//! WASI 路径是有效 Unicode 标量值序列,
//! 因此 WASI 无法处理不能编码为
//! 格式良好的 UTF-8/UTF-16 的路径。
//! https://github.com/WebAssembly/wasi-filesystem/issues/17#issuecomment-1430639353

const builtin = @import("builtin");
const native_os = builtin.target.os.tag;

const std = @import("../std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const Allocator = std.mem.Allocator;
const eqlIgnoreCaseWtf8 = std.os.windows.eqlIgnoreCaseWtf8;
const eqlIgnoreCaseWtf16 = std.os.windows.eqlIgnoreCaseWtf16;

pub const sep_windows: u8 = '\\';
pub const sep_posix: u8 = '/';
pub const sep = switch (native_os) {
    .windows, .uefi => sep_windows,
    else => sep_posix,
};

pub const sep_str_windows = "\\";
pub const sep_str_posix = "/";
pub const sep_str = switch (native_os) {
    .windows, .uefi => sep_str_windows,
    else => sep_str_posix,
};

pub const delimiter_windows: u8 = ';';
pub const delimiter_posix: u8 = ':';
pub const delimiter = if (native_os == .windows) delimiter_windows else delimiter_posix;

/// 返回给定字节是否为有效路径分隔符
pub fn isSep(byte: u8) bool {
    return switch (native_os) {
        .windows => byte == '/' or byte == '\\',
        .uefi => byte == '\\',
        else => byte == '/',
    };
}

pub const PathType = enum {
    windows,
    uefi,
    posix,

    /// 若 `c` 是 `path_type` 的有效路径分隔符,返回 true。
    /// 若 `T` 为 `u16`,假定 `c` 为小端序。
    pub inline fn isSep(comptime path_type: PathType, comptime T: type, c: T) bool {
        return switch (path_type) {
            .windows => c == mem.nativeToLittle(T, '/') or c == mem.nativeToLittle(T, '\\'),
            .posix => c == mem.nativeToLittle(T, '/'),
            .uefi => c == mem.nativeToLittle(T, '\\'),
        };
    }
};

/// 与 mem.join 不同:若连续两条路径的前一条末尾
/// 或后一条开头已有分隔符,则不会重复添加。
fn joinSepMaybeZ(allocator: Allocator, separator: u8, comptime sepPredicate: fn (u8) bool, paths: []const []const u8, zero: bool) ![]u8 {
    if (paths.len == 0) return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{};

    // 查找首个非空路径索引。
    const first_path_index = blk: {
        for (paths, 0..) |path, index| {
            if (path.len == 0) continue else break :blk index;
        }

        // 提供的所有路径均为空,因此提前返回。
        return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{};
    };

    // 计算拼接后路径缓冲区所需的长度。
    const total_len = blk: {
        var sum: usize = paths[first_path_index].len;
        var prev_path = paths[first_path_index];
        assert(prev_path.len > 0);
        var i: usize = first_path_index + 1;
        while (i < paths.len) : (i += 1) {
            const this_path = paths[i];
            if (this_path.len == 0) continue;
            const prev_sep = sepPredicate(prev_path[prev_path.len - 1]);
            const this_sep = sepPredicate(this_path[0]);
            sum += @intFromBool(!prev_sep and !this_sep);
            sum += if (prev_sep and this_sep) this_path.len - 1 else this_path.len;
            prev_path = this_path;
        }

        if (zero) sum += 1;
        break :blk sum;
    };

    const buf = try allocator.alloc(u8, total_len);
    errdefer allocator.free(buf);

    @memcpy(buf[0..paths[first_path_index].len], paths[first_path_index]);
    var buf_index: usize = paths[first_path_index].len;
    var prev_path = paths[first_path_index];
    assert(prev_path.len > 0);
    var i: usize = first_path_index + 1;
    while (i < paths.len) : (i += 1) {
        const this_path = paths[i];
        if (this_path.len == 0) continue;
        const prev_sep = sepPredicate(prev_path[prev_path.len - 1]);
        const this_sep = sepPredicate(this_path[0]);
        if (!prev_sep and !this_sep) {
            buf[buf_index] = separator;
            buf_index += 1;
        }
        const adjusted_path = if (prev_sep and this_sep) this_path[1..] else this_path;
        @memcpy(buf[buf_index..][0..adjusted_path.len], adjusted_path);
        buf_index += adjusted_path.len;
        prev_path = this_path;
    }

    if (zero) buf[buf.len - 1] = 0;

    // 无需缩减,因为 buf 的大小恰好正确。
    return buf;
}

/// 使用原生路径分隔符直接组合一系列路径。
/// 为结果分配内存,必须由调用方释放。
pub fn join(allocator: Allocator, paths: []const []const u8) ![]u8 {
    return joinSepMaybeZ(allocator, sep, isSep, paths, false);
}

/// 使用原生路径分隔符和空终止符,直接组合一系列路径。
/// 为结果分配内存,调用方必须释放。
pub fn joinZ(allocator: Allocator, paths: []const []const u8) ![:0]u8 {
    const out = try joinSepMaybeZ(allocator, sep, isSep, paths, true);
    return out[0 .. out.len - 1 :0];
}

pub fn fmtJoin(paths: []const []const u8) std.fmt.Alt([]const []const u8, formatJoin) {
    return .{ .data = paths };
}

fn formatJoin(paths: []const []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void {
    const first_path_idx = for (paths, 0..) |p, idx| {
        if (p.len != 0) break idx;
    } else return;

    try w.writeAll(paths[first_path_idx]); // 第一个分量
    var prev_path = paths[first_path_idx];
    for (paths[first_path_idx + 1 ..]) |this_path| {
        if (this_path.len == 0) continue; // 跳过空路径分量
        const prev_sep = isSep(prev_path[prev_path.len - 1]);
        const this_sep = isSep(this_path[0]);
        if (!prev_sep and !this_sep) {
            try w.writeByte(sep);
        }
        if (prev_sep and this_sep) {
            try w.writeAll(this_path[1..]); // 跳过多余的分隔符
        } else {
            try w.writeAll(this_path);
        }
        prev_path = this_path;
    }
}

fn testJoinMaybeZUefi(paths: []const []const u8, expected: []const u8, zero: bool) !void {
    const uefiIsSep = struct {
        fn isSep(byte: u8) bool {
            return byte == '\\';
        }
    }.isSep;
    const actual = try joinSepMaybeZ(testing.allocator, sep_windows, uefiIsSep, paths, zero);
    defer testing.allocator.free(actual);
    try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
}

fn testJoinMaybeZWindows(paths: []const []const u8, expected: []const u8, zero: bool) !void {
    const windowsIsSep = struct {
        fn isSep(byte: u8) bool {
            return byte == '/' or byte == '\\';
        }
    }.isSep;
    const actual = try joinSepMaybeZ(testing.allocator, sep_windows, windowsIsSep, paths, zero);
    defer testing.allocator.free(actual);
    try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
}

fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bool) !void {
    const posixIsSep = struct {
        fn isSep(byte: u8) bool {
            return byte == '/';
        }
    }.isSep;
    const actual = try joinSepMaybeZ(testing.allocator, sep_posix, posixIsSep, paths, zero);
    defer testing.allocator.free(actual);
    try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
}

test join {
    {
        const actual: []u8 = try join(testing.allocator, &[_][]const u8{});
        defer testing.allocator.free(actual);
        try testing.expectEqualSlices(u8, "", actual);
    }
    {
        const actual: [:0]u8 = try joinZ(testing.allocator, &[_][]const u8{});
        defer testing.allocator.free(actual);
        try testing.expectEqualSlices(u8, "", actual);
    }
    for (&[_]bool{ false, true }) |zero| {
        try testJoinMaybeZWindows(&[_][]const u8{}, "", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b\\", "\\c" }, "c:\\a\\b\\c", zero);

        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b\\", "c" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\", "b\\", "c" }, "c:\\a\\b\\c", zero);

        try testJoinMaybeZWindows(
            &[_][]const u8{ "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "ab.zig" },
            "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\ab.zig",
            zero,
        );

        try testJoinMaybeZUefi(&[_][]const u8{ "EFI", "Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);
        try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);
        try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\", "\\Boot", "bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);
        try testJoinMaybeZUefi(&[_][]const u8{ "EFI\\", "\\Boot\\", "\\bootx64.efi" }, "EFI\\Boot\\bootx64.efi", zero);

        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b/", "c" }, "c:\\a\\b/c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "b\\", "/c" }, "c:\\a/b\\c", zero);

        try testJoinMaybeZWindows(&[_][]const u8{ "", "c:\\", "", "", "a", "b\\", "c", "" }, "c:\\a\\b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "", "b\\", "", "/c" }, "c:\\a/b\\c", zero);
        try testJoinMaybeZWindows(&[_][]const u8{ "", "" }, "", zero);

        try testJoinMaybeZPosix(&[_][]const u8{}, "", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/b/", "c" }, "/a/b/c", zero);

        try testJoinMaybeZPosix(&[_][]const u8{ "/", "a", "b/", "c" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "b/", "c" }, "/a/b/c", zero);

        try testJoinMaybeZPosix(
            &[_][]const u8{ "/home/andy/dev/zig/build/lib/zig/std", "ab.zig" },
            "/home/andy/dev/zig/build/lib/zig/std/ab.zig",
            zero,
        );

        try testJoinMaybeZPosix(&[_][]const u8{ "a", "/c" }, "a/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "a/", "/c" }, "a/c", zero);

        try testJoinMaybeZPosix(&[_][]const u8{ "", "/", "a", "", "b/", "c", "" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "", "", "b/", "c" }, "/a/b/c", zero);
        try testJoinMaybeZPosix(&[_][]const u8{ "", "" }, "", zero);
    }
}

pub fn isAbsoluteZ(path_c: [*:0]const u8) bool {
    if (native_os == .windows) {
        return isAbsoluteWindowsZ(path_c);
    } else {
        return isAbsolutePosixZ(path_c);
    }
}

pub fn isAbsolute(path: []const u8) bool {
    if (native_os == .windows) {
        return isAbsoluteWindows(path);
    } else {
        return isAbsolutePosix(path);
    }
}

fn isAbsoluteWindowsImpl(comptime T: type, path: []const T) bool {
    return switch (getWin32PathType(T, path)) {
        // 明确为绝对路径
        .drive_absolute, .unc_absolute, .local_device, .root_local_device => true,
        // 明确为相对路径
        .relative => false,
        // 有歧义,更接近绝对路径而非相对路径
        .rooted => true,
        // 存在歧义,但更倾向于相对路径而非绝对路径
        .drive_relative => false,
    };
}

pub fn isAbsoluteWindows(path: []const u8) bool {
    return isAbsoluteWindowsImpl(u8, path);
}

pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool {
    return isAbsoluteWindowsImpl(u16, mem.sliceTo(path_w, 0));
}

pub fn isAbsoluteWindowsWtf16(path: []const u16) bool {
    return isAbsoluteWindowsImpl(u16, path);
}

pub fn isAbsoluteWindowsZ(path_c: [*:0]const u8) bool {
    return isAbsoluteWindowsImpl(u8, mem.sliceTo(path_c, 0));
}

pub fn isAbsolutePosix(path: []const u8) bool {
    return path.len > 0 and path[0] == sep_posix;
}

pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool {
    return isAbsolutePosix(mem.sliceTo(path_c, 0));
}

test isAbsoluteWindows {
    try testIsAbsoluteWindows("", false);
    try testIsAbsoluteWindows("/", true);
    try testIsAbsoluteWindows("//", true);
    try testIsAbsoluteWindows("//server", true);
    try testIsAbsoluteWindows("//server/file", true);
    try testIsAbsoluteWindows("\\\\server\\file", true);
    try testIsAbsoluteWindows("\\\\server", true);
    try testIsAbsoluteWindows("\\\\", true);
    try testIsAbsoluteWindows("c", false);
    try testIsAbsoluteWindows("c:", false);
    try testIsAbsoluteWindows("c:\\", true);
    try testIsAbsoluteWindows("c:/", true);
    try testIsAbsoluteWindows("c://", true);
    try testIsAbsoluteWindows("C:/Users/", true);
    try testIsAbsoluteWindows("C:\\Users\\", true);
    try testIsAbsoluteWindows("C:cwd/another", false);
    try testIsAbsoluteWindows("C:cwd\\another", false);
    try testIsAbsoluteWindows("λ:\\", true);
    try testIsAbsoluteWindows("λ:", false);
    try testIsAbsoluteWindows("\u{10000}:\\", false);
    try testIsAbsoluteWindows("directory/directory", false);
    try testIsAbsoluteWindows("directory\\directory", false);
    try testIsAbsoluteWindows("/usr/local", true);
}

test isAbsolutePosix {
    try testIsAbsolutePosix("", false);
    try testIsAbsolutePosix("/home/foo", true);
    try testIsAbsolutePosix("/home/foo/..", true);
    try testIsAbsolutePosix("bar/", false);
    try testIsAbsolutePosix("./baz", false);
}

fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) !void {
    try testing.expectEqual(expected_result, isAbsoluteWindows(path));
    const path_w = try std.unicode.wtf8ToWtf16LeAllocZ(std.testing.allocator, path);
    defer std.testing.allocator.free(path_w);
    try testing.expectEqual(expected_result, isAbsoluteWindowsW(path_w));
    try testing.expectEqual(expected_result, isAbsoluteWindowsWtf16(path_w));
}

fn testIsAbsolutePosix(path: []const u8, expected_result: bool) !void {
    try testing.expectEqual(expected_result, isAbsolutePosix(path));
}

/// 已弃用;请参阅 `WindowsPath2`
pub const WindowsPath = struct {
    is_abs: bool,
    kind: Kind,
    disk_designator: []const u8,

    pub const Kind = enum {
        None,
        Drive,
        NetworkShare,
    };
};

/// 已弃用;参见 `parsePathWindows`
pub fn windowsParsePath(path: []const u8) WindowsPath {
    if (path.len >= 2 and path[1] == ':') {
        return WindowsPath{
            .is_abs = isAbsoluteWindows(path),
            .kind = WindowsPath.Kind.Drive,
            .disk_designator = path[0..2],
        };
    }
    if (path.len >= 1 and (path[0] == '/' or path[0] == '\\') and
        (path.len == 1 or (path[1] != '/' and path[1] != '\\')))
    {
        return WindowsPath{
            .is_abs = true,
            .kind = WindowsPath.Kind.None,
            .disk_designator = path[0..0],
        };
    }
    const relative_path = WindowsPath{
        .kind = WindowsPath.Kind.None,
        .disk_designator = &[_]u8{},
        .is_abs = false,
    };

    if (path.len >= 2 and PathType.windows.isSep(u8, path[0]) and PathType.windows.isSep(u8, path[1])) {
        const root_end = root_end: {
            var server_end = mem.findAnyPos(u8, path, 2, "/\\") orelse break :root_end path.len;
            while (server_end < path.len and PathType.windows.isSep(u8, path[server_end])) server_end += 1;
            break :root_end mem.findAnyPos(u8, path, server_end, "/\\") orelse path.len;
        };
        return WindowsPath{
            .is_abs = true,
            .kind = WindowsPath.Kind.NetworkShare,
            .disk_designator = path[0..root_end],
        };
    }
    return relative_path;
}

test windowsParsePath {
    {
        const parsed = windowsParsePath("//a/b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "//a/b"));
    }
    {
        const parsed = windowsParsePath("\\\\a\\b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\b"));
    }
    {
        const parsed = windowsParsePath("\\\\a/b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a/b"));
    }
    {
        const parsed = windowsParsePath("\\/a\\");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\/a\\"));
    }
    {
        const parsed = windowsParsePath("\\\\a\\\\b");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\\\b"));
    }
    {
        const parsed = windowsParsePath("\\\\a\\\\b\\c");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\\\b"));
    }
    {
        const parsed = windowsParsePath("/usr/local");
        try testing.expect(parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.None);
        try testing.expect(mem.eql(u8, parsed.disk_designator, ""));
    }
    {
        const parsed = windowsParsePath("c:../");
        try testing.expect(!parsed.is_abs);
        try testing.expect(parsed.kind == WindowsPath.Kind.Drive);
        try testing.expect(mem.eql(u8, parsed.disk_designator, "c:"));
    }
}

/// Windows 上调用 `parsePathWindows`,POSIX 上调用 `parsePathPosix`。
///
/// 返回平台相关结构体,包含 `root` 和 `kind` 两个字段。
/// `root` 是 `path` 的切片;POSIX 绝对路径中为 `/`,Windows 路径中
/// 则为 `C:\`、`\\server\share\` 等。
/// 若路径种类为 `.relative`,`root` 长度为零。
pub fn parsePath(path: []const u8) switch (native_os) {
    .windows => WindowsPath2(u8),
    else => PosixPath,
} {
    switch (native_os) {
        .windows => return parsePathWindows(u8, path),
        else => return parsePathPosix(path),
    }
}

const PosixPath = struct {
    kind: enum { relative, absolute },
    root: []const u8,
};

pub fn parsePathPosix(path: []const u8) PosixPath {
    const abs = isAbsolutePosix(path);
    return .{
        .kind = if (abs) .absolute else .relative,
        .root = if (abs) path[0..1] else path[0..0],
    };
}

test parsePathPosix {
    {
        const parsed = parsePathPosix("a/b");
        try testing.expectEqual(.relative, parsed.kind);
        try testing.expectEqualStrings("", parsed.root);
    }
    {
        const parsed = parsePathPosix("/a/b");
        try testing.expectEqual(.absolute, parsed.kind);
        try testing.expectEqualStrings("/", parsed.root);
    }
    {
        const parsed = parsePathPosix("///a/b");
        try testing.expectEqual(.absolute, parsed.kind);
        try testing.expectEqualStrings("/", parsed.root);
    }
}

pub fn WindowsPath2(comptime T: type) type {
    return struct {
        kind: Win32PathType,
        root: []const T,
    };
}

pub fn parsePathWindows(comptime T: type, path: []const T) WindowsPath2(T) {
    const kind = getWin32PathType(T, path);
    const root = root: switch (kind) {
        .drive_absolute, .drive_relative => {
            const drive_letter_len = getDriveLetter(T, path).len;
            break :root path[0 .. drive_letter_len + @as(usize, if (kind == .drive_absolute) 2 else 1)];
        },
        .relative => path[0..0],
        .local_device => path[0..4],
        .root_local_device => path,
        .rooted => path[0..1],
        .unc_absolute => {
            const unc = parseUNC(T, path);
            // 服务器名与共享名之间可能存在任意数量的路径分隔符,
            // 因此通过指针运算计算差值以处理这一情况。
            var root_len = 2 + (unc.share.ptr - unc.server.ptr) + unc.share.len;
            if (unc.sep_after_share) root_len += 1;
            break :root path[0..root_len];
        },
    };
    return .{
        .kind = kind,
        .root = root,
    };
}

test parsePathWindows {
    {
        const path = "//a/b";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("//a/b", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\b";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\b", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\/a/b/c";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\/a/b/", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\b\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\b\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\a\\/b\\/";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\a\\/b\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\кириллица\\ελληνικά\\português";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.unc_absolute, parsed.kind);
        try testing.expectEqualStrings("\\\\кириллица\\ελληνικά\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "/usr/local";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.rooted, parsed.kind);
        try testing.expectEqualStrings("/", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\.";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.root_local_device, parsed.kind);
        try testing.expectEqualStrings("\\\\.", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\\\\.\\a";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.local_device, parsed.kind);
        try testing.expectEqualStrings("\\\\.\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "c:../";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_relative, parsed.kind);
        try testing.expectEqualStrings("c:", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "C:\\../";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_absolute, parsed.kind);
        try testing.expectEqualStrings("C:\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        // 编码为单个 WTF-16 代码单元的非 ASCII 码点被视为有效驱动器盘符。
        const path = "€:\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_absolute, parsed.kind);
        try testing.expectEqualStrings("€:\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "€:";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.drive_relative, parsed.kind);
        try testing.expectEqualStrings("€:", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        // 但编码为两个 WTF-16 代码单元的码点不在此列
        const path = "\u{10000}:\\";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.relative, parsed.kind);
        try testing.expectEqualStrings("", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        const path = "\u{10000}:";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.relative, parsed.kind);
        try testing.expectEqualStrings("", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
    {
        // 假定路径位于 Win32 命名空间,因此尽管它
        // 可能是 NT 命名空间路径,仍按根路径处理。
        const path = "\\??\\foo";
        const parsed = parsePathWindows(u8, path);
        try testing.expectEqual(.rooted, parsed.kind);
        try testing.expectEqualStrings("\\", parsed.root);
        try testWindowsParsePathHarmony(path);
    }
}

fn testWindowsParsePathHarmony(wtf8: []const u8) !void {
    var wtf16_buf: [256]u16 = undefined;
    const wtf16_len = try std.unicode.wtf8ToWtf16Le(&wtf16_buf, wtf8);
    const wtf16 = wtf16_buf[0..wtf16_len];

    const wtf8_parsed = parsePathWindows(u8, wtf8);
    const wtf16_parsed = parsePathWindows(u16, wtf16);

    var wtf8_buf: [256]u8 = undefined;
    const wtf16_root_as_wtf8_len = std.unicode.wtf16LeToWtf8(&wtf8_buf, wtf16_parsed.root);
    const wtf16_root_as_wtf8 = wtf8_buf[0..wtf16_root_as_wtf8_len];

    try std.testing.expectEqual(wtf8_parsed.kind, wtf16_parsed.kind);
    try std.testing.expectEqualStrings(wtf8_parsed.root, wtf16_root_as_wtf8);
}

/// 已弃用;使用 `parsePath`
pub fn diskDesignator(path: []const u8) []const u8 {
    if (native_os == .windows) {
        return diskDesignatorWindows(path);
    } else {
        return "";
    }
}

/// 已弃用;请使用 `parsePathWindows`
pub fn diskDesignatorWindows(path: []const u8) []const u8 {
    return windowsParsePath(path).disk_designator;
}

fn WindowsUNC(comptime T: type) type {
    return struct {
        server: []const T,
        sep_after_server: bool,
        share: []const T,
        sep_after_share: bool,
    };
}

/// 断言 `path` 以两个路径分隔符开头
fn parseUNC(comptime T: type, path: []const T) WindowsUNC(T) {
    assert(path.len >= 2 and PathType.windows.isSep(T, path[0]) and PathType.windows.isSep(T, path[1]));
    const any_sep = switch (T) {
        u8 => "/\\",
        u16 => std.unicode.wtf8ToWtf16LeStringLiteral("/\\"),
        else => @compileError("only u8 (WTF-8) and u16 (WTF-16LE) are supported"),
    };
    // 对于服务器名称,开头两个路径分隔符之后的第一个分隔符
    // 始终是服务器名称的终止符,
    // 即使这意味着服务器名称长度为零。
    const server_end = mem.findAnyPos(T, path, 2, any_sep) orelse return .{
        .server = path[2..path.len],
        .sep_after_server = false,
        .share = path[path.len..path.len],
        .sep_after_share = false,
    };
    // 对于共享路径,服务器与共享名之间可以有任意数量的
    // 路径分隔符,因此需要跳过全部分隔符,
    // 而非仅查找第一个。
    var it = mem.tokenizeAny(T, path[server_end + 1 ..], any_sep);
    const share = it.next() orelse return .{
        .server = path[2..server_end],
        .sep_after_server = true,
        .share = path[server_end + 1 .. server_end + 1],
        .sep_after_share = false,
    };
    return .{
        .server = path[2..server_end],
        .sep_after_server = true,
        .share = share,
        .sep_after_share = it.index != it.buffer.len,
    };
}

test parseUNC {
    {
        const unc = parseUNC(u8, "//");
        try std.testing.expectEqualStrings("", unc.server);
        try std.testing.expect(!unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\s");
        try std.testing.expectEqualStrings("s", unc.server);
        try std.testing.expect(!unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\s/");
        try std.testing.expectEqualStrings("s", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\/server\\share");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("share", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "/\\server\\share/");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("share", unc.share);
        try std.testing.expect(unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\server/\\share\\/");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("share", unc.share);
        try std.testing.expect(unc.sep_after_share);
    }
    {
        const unc = parseUNC(u8, "\\\\server\\/\\\\");
        try std.testing.expectEqualStrings("server", unc.server);
        try std.testing.expect(unc.sep_after_server);
        try std.testing.expectEqualStrings("", unc.share);
        try std.testing.expect(!unc.sep_after_share);
    }
}

const DiskDesignatorKind = enum { drive, unc };

/// 假定 `p1` 和 `p2` 均属于给定的 `kind`。
fn compareDiskDesignators(comptime T: type, kind: DiskDesignatorKind, p1: []const T, p2: []const T) bool {
    const eql = switch (T) {
        u8 => eqlIgnoreCaseWtf8,
        u16 => eqlIgnoreCaseWtf16,
        else => @compileError("only u8 (WTF-8) and u16 (WTF-16LE) is supported"),
    };
    switch (kind) {
        .drive => {
            const drive_letter1 = getDriveLetter(T, p1);
            const drive_letter2 = getDriveLetter(T, p2);

            return eql(drive_letter1, drive_letter2);
        },
        .unc => {
            const unc1 = parseUNC(T, p1);
            const unc2 = parseUNC(T, p2);

            return eql(unc1.server, unc2.server) and
                eql(unc1.share, unc2.share);
        },
    }
}

/// 假定 `path` 为驱动器相对路径或驱动器绝对路径。
fn getDriveLetter(comptime T: type, path: []const T) []const T {
    const len: usize = switch (T) {
        // getWin32PathType 仅在以下条件成立时返回 .drive_absolute/.drive_relative:
        // (1)码点有效;(2)码点 < U+10000。因此只需
        // 获取由首字节确定的长度。
        u8 => std.unicode.utf8ByteSequenceLength(path[0]) catch unreachable,
        u16 => 1,
        else => @compileError("unsupported type: " ++ @typeName(T)),
    };
    return path[0..len];
}

test compareDiskDesignators {
    try testCompareDiskDesignators(true, .drive, "c:", "C:\\");
    try testCompareDiskDesignators(true, .drive, "C:\\", "C:");
    try testCompareDiskDesignators(false, .drive, "C:\\", "D:\\");
    // 严格来说,不区分大小写规则也适用于非 ASCII 驱动器字母
    try testCompareDiskDesignators(true, .drive, "λ:\\", "Λ:");

    try testCompareDiskDesignators(true, .unc, "\\\\server", "//server//");
    try testCompareDiskDesignators(true, .unc, "\\\\server\\\\share", "/\\server/share");
    try testCompareDiskDesignators(true, .unc, "\\\\server\\\\share", "/\\server/share\\\\foo");
    try testCompareDiskDesignators(false, .unc, "\\\\server\\sharefoo", "/\\server/share\\foo");
    try testCompareDiskDesignators(false, .unc, "\\\\serverfoo\\\\share", "//server/share");
    try testCompareDiskDesignators(false, .unc, "\\\\server\\", "//server/share");
}

fn testCompareDiskDesignators(expected_result: bool, kind: DiskDesignatorKind, p1: []const u8, p2: []const u8) !void {
    var wtf16_buf1: [256]u16 = undefined;
    const w1_len = try std.unicode.wtf8ToWtf16Le(&wtf16_buf1, p1);
    var wtf16_buf2: [256]u16 = undefined;
    const w2_len = try std.unicode.wtf8ToWtf16Le(&wtf16_buf2, p2);
    try std.testing.expectEqual(expected_result, compareDiskDesignators(u8, kind, p1, p2));
    try std.testing.expectEqual(expected_result, compareDiskDesignators(u16, kind, wtf16_buf1[0..w1_len], wtf16_buf2[0..w2_len]));
}

/// 已弃用,改用 `resolveAlloc`。
pub const resolve = resolveAlloc;
/// 已弃用,请改用 `resolveAllocWindows`。
pub const resolveWindows = resolveAllocWindows;
/// 已弃用,改用 `resolveAllocPosix`。
pub const resolvePosix = resolveAllocPosix;

/// 已弃用,改用 `relativeAlloc`。
pub const relative = relativeAlloc;
/// 已弃用,请改用 `relativeAllocPosix`。
pub const relativePosix = relativeAllocPosix;
/// 已弃用,请改用 `relativeAllocWindows`。
pub const relativeWindows = relativeAllocWindows;

/// 在 Windows 上调用 `resolveAllocWindows`;否则调用 `resolveAllocPosix`。
///
/// 另请参见:
/// `resolveAppend`
pub fn resolveAlloc(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8 {
    switch (native_os) {
        .windows => return resolveAllocWindows(gpa, paths),
        else => return resolveAllocPosix(gpa, paths),
    }
}

/// 在 Windows 上调用 `resolveAppendWindows`;否则调用 `resolveAppendPosix`。
///
/// 另请参见:
/// `resolveAlloc`
pub fn resolveAppend(gpa: Allocator, al: *std.ArrayList(u8), paths: []const []const u8) Allocator.Error!void {
    switch (native_os) {
        .windows => return resolveAppendWindows(gpa, al, paths),
        else => return resolveAppendPosix(gpa, al, paths),
    }
}

/// 在没有符号链接的虚拟文件系统中模拟一系列相对目录切换,以分配的切片返回结果。
///
/// 路径分隔符规范化为 '\\',驱动器字母规范化为大写。
///
/// 解析 "." 和 "..",但不会将相对路径变为绝对路径。如果结果路径是相对路径或驱动器相对路径,".." 分量可能仍然保留。
///
/// 除以下情况外,结果末尾不包含路径分隔符:
/// - 结果是没有路径分量的驱动器绝对路径,例如 `C:\`。
/// - 结果是仅包含服务器名称的 UNC 路径,且输入末尾带分隔符,例如 `\\server\`。
/// - 结果是共享名称后没有其他分量的 UNC 路径,且输入末尾带分隔符,例如 `\\server\share\`。
///
/// 每个驱动器有自己的当前工作目录,仅通过给定路径解析。如果包含驱动器相对路径,但无法仅依据输入路径解析,则结果仍为驱动器相对路径。同理,无法仅依据输入解析的根相对路径,结果仍为根相对路径。
///
/// 此函数不执行系统调用。在真实文件系统中执行同样的路径查找序列,可能因符号链接而得到不同结果。
///
/// 另见:
/// * `resolveAlloc`
/// * `resolveAppendWindows`
///
///
///
///
///
///
///
///
pub fn resolveAllocWindows(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8 {
    var buffer: std.ArrayList(u8) = .empty;
    defer buffer.deinit(gpa);
    try resolveAppendWindows(gpa, &buffer, paths);
    try buffer.shrinkToLen(gpa);
    return buffer.toOwnedSliceAssert();
}

/// 在不含符号链接的虚拟文件系统上模拟一系列相对目录切换,并将结果
/// 追加到提供的数组列表中。
///
/// 路径分隔符规范化为 '\\',盘符规范化为大写字母。
///
/// 解析 "." 和 "..",但不会将相对路径转换为绝对路径。如果解析结果
/// 是相对路径或驱动器相对路径,其中可能仍保留 ".." 分量。
///
/// 结果不含末尾路径分隔符,但以下情况除外:
/// - 结果是没有路径分量的驱动器绝对路径,例如 `C:\`。
/// - 结果是只包含服务器名的 UNC 路径,且输入路径带有末尾分隔符,
///   例如 `\\server\`。
/// - 结果是共享名之后没有路径分量的 UNC 路径,且输入路径带有
///   末尾分隔符,例如 `\\server\share\`。
///
/// 每个驱动器都有独立的当前工作目录,且仅通过提供的路径确定。
/// 如果解析结果包含无法仅凭这些路径确定的驱动器相对路径,
/// 结果将保持为驱动器相对路径。同样,如果解析结果包含无法仅凭
/// 这些路径确定的根相对路径,结果将保持为根相对路径。
///
/// 此函数不执行任何系统调用。在实际文件系统上执行这些路径查找,
/// 可能因符号链接而得到不同结果。
///
/// 另请参见:
/// * `resolveAppend`
/// * `resolveAllocWindows`
pub fn resolveAppendWindows(gpa: Allocator, al: *std.ArrayList(u8), paths: []const []const u8) Allocator.Error!void {
    // 当 paths.len <= @bitSizeOf(usize) * 2 时避免堆分配。
    // 使用 `* 3`,因为 stackFallback 以一个 usize 存储长度。
    var buf: [3]usize = undefined;
    var bit_set_allocator_state: std.heap.BufferFirstAllocator = .init(@ptrCast(&buf), gpa);
    const bit_set_allocator = bit_set_allocator_state.allocator();
    var relevant_paths: std.bit_set.Dynamic = try .initEmpty(bit_set_allocator, paths.len);
    defer relevant_paths.deinit(bit_set_allocator);

    // 反向遍历路径,沿途标记相关路径。
    // 这样,一旦确定更早的路径均不相关,便可退出循环。
    var first_path_i: usize = paths.len;
    const effective_root_path: WindowsPath2(u8) = root: {
        var last_effective_root_path: WindowsPath2(u8) = .{ .kind = .relative, .root = "" };
        var last_rooted_path_i: ?usize = null;
        var last_drive_relative_path_i: usize = undefined;
        while (first_path_i > 0) {
            first_path_i -= 1;
            const parsed = parsePathWindows(u8, paths[first_path_i]);
            switch (parsed.kind) {
                .unc_absolute, .root_local_device, .local_device => {
                    switch (last_effective_root_path.kind) {
                        .rooted => {},
                        .drive_relative => continue,
                        else => {
                            relevant_paths.set(first_path_i);
                        },
                    }
                    break :root parsed;
                },
                .drive_relative, .drive_absolute => {
                    switch (last_effective_root_path.kind) {
                        .drive_relative => if (!compareDiskDesignators(u8, .drive, parsed.root, last_effective_root_path.root)) {
                            continue;
                        } else if (last_rooted_path_i != null) {
                            break :root .{ .kind = .drive_absolute, .root = parsed.root };
                        },
                        .relative => last_effective_root_path = parsed,
                        .rooted => {
                            // 到此即可停止,因为带根路径始终相对于
                            // 此驱动器号;即使当前路径相对于驱动器,
                            // 路径带根这一性质也使它不再相关。
                            //
                            // 因此,强制将有效根的类型设为驱动器绝对路径,
                            // 以正确地依据驱动器相对路径解析带根路径,
                            // 因为结果应始终为驱动器绝对路径。
                            break :root .{ .kind = .drive_absolute, .root = parsed.root };
                        },
                        .drive_absolute, .unc_absolute, .root_local_device, .local_device => unreachable,
                    }
                    relevant_paths.set(first_path_i);
                    last_drive_relative_path_i = first_path_i;
                    if (parsed.kind == .drive_absolute) {
                        break :root parsed;
                    }
                },
                .relative => {
                    switch (last_effective_root_path.kind) {
                        .rooted => continue,
                        .relative => last_effective_root_path = parsed,
                        else => {},
                    }
                    relevant_paths.set(first_path_i);
                },
                .rooted => {
                    switch (last_effective_root_path.kind) {
                        .drive_relative => {},
                        .relative => last_effective_root_path = parsed,
                        .rooted => continue,
                        .drive_absolute, .unc_absolute, .root_local_device, .local_device => unreachable,
                    }
                    if (last_rooted_path_i == null) {
                        last_rooted_path_i = first_path_i;
                        relevant_paths.set(first_path_i);
                    }
                },
            }
        }
        // 迭代结束后,若待定的有效根仍为驱动器相对形式,表示没有任何输入迫使根成为驱动器绝对形式;能够解析驱动器专属当前工作目录的路径会使循环提前结束。因此,此时必须忽略最近一个驱动器相对路径之前的所有路径。例如,解析:
        // { "\\rooted", "relative", "C:drive-relative" }
        // 时,必须忽略 `\rooted` 和 `relative`,因为若不知道当前工作目录,就无法确定根路径究竟相对于哪个根。
        //
        //
        //
        //
        if (last_effective_root_path.kind == .drive_relative) {
            for (0..last_drive_relative_path_i) |i| {
                relevant_paths.unset(i);
            }
        }
        break :root last_effective_root_path;
    };

    const prev_len = al.items.len;
    errdefer al.shrinkRetainingCapacity(prev_len);

    var want_path_sep_between_root_and_component = false;
    switch (effective_root_path.kind) {
        .root_local_device, .local_device => {
            try al.ensureUnusedCapacity(gpa, 3);
            al.appendSliceAssumeCapacity("\\\\");
            al.appendAssumeCapacity(effective_root_path.root[2]); // . 或 ?
            want_path_sep_between_root_and_component = true;
        },
        .drive_absolute, .drive_relative => {
            try al.ensureUnusedCapacity(gpa, effective_root_path.root.len);
            al.appendAssumeCapacity(std.ascii.toUpper(effective_root_path.root[0]));
            al.appendAssumeCapacity(':');
            if (effective_root_path.kind == .drive_absolute) {
                al.appendAssumeCapacity('\\');
            }
        },
        .unc_absolute => {
            const unc = parseUNC(u8, effective_root_path.root);

            const root_len = len: {
                var len: usize = 2 + unc.server.len + unc.share.len;
                if (unc.sep_after_server) len += 1;
                if (unc.sep_after_share) len += 1;
                break :len len;
            };
            try al.ensureUnusedCapacity(gpa, root_len);
            al.appendSliceAssumeCapacity("\\\\");
            if (unc.server.len > 0 or unc.sep_after_server) {
                al.appendSliceAssumeCapacity(unc.server);
                if (unc.sep_after_server)
                    al.appendAssumeCapacity('\\')
                else
                    want_path_sep_between_root_and_component = true;
            }
            if (unc.share.len > 0) {
                al.appendSliceAssumeCapacity(unc.share);
                if (unc.sep_after_share)
                    al.appendAssumeCapacity('\\')
                else
                    want_path_sep_between_root_and_component = true;
            }
        },
        .rooted => {
            try al.append(gpa, '\\');
        },
        .relative => {},
    }

    const root_len = al.items.len - prev_len;
    var negative_count: usize = 0;
    for (paths[first_path_i..], first_path_i..) |path, i| {
        if (!relevant_paths.isSet(i)) continue;

        const parsed = parsePathWindows(u8, path);
        const skip_len = parsed.root.len;
        var it = mem.tokenizeAny(u8, path[skip_len..], "/\\");
        while (it.next()) |component| {
            if (mem.eql(u8, component, ".")) {
                continue;
            } else if (mem.eql(u8, component, "..")) {
                if ((al.items.len - prev_len) == 0 or
                    ((al.items.len - prev_len) == root_len and effective_root_path.kind == .drive_relative))
                {
                    negative_count += 1;
                    continue;
                }
                while ((al.items.len - prev_len) != root_len) {
                    const end_with_sep = PathType.windows.isSep(u8, al.items[al.items.len - 1]);
                    al.items.len -= 1;
                    if (end_with_sep) break;
                }
            } else if ((al.items.len - prev_len) == root_len and !want_path_sep_between_root_and_component) {
                try al.appendSlice(gpa, component);
            } else {
                try al.ensureUnusedCapacity(gpa, 1 + component.len);
                al.appendAssumeCapacity('\\');
                al.appendSliceAssumeCapacity(component);
            }
        }
    }

    if (root_len != 0 and (al.items.len - prev_len) == root_len and negative_count == 0) return;

    if ((al.items.len - prev_len) == root_len) {
        if (negative_count == 0) {
            try al.resize(gpa, prev_len + 1);
            al.items[al.items.len - 1] = '.';
            return;
        }

        try al.ensureTotalCapacityPrecise(gpa, prev_len + 3 * negative_count - 1);
        for (0..negative_count - 1) |_| {
            al.appendSliceAssumeCapacity("..\\");
        }
        al.appendSliceAssumeCapacity("..");
    } else {
        const dest = try al.addManyAt(gpa, prev_len + root_len, 3 * negative_count);
        for (0..negative_count) |i| {
            dest[i * 3 ..][0..3].* = "..\\".*;
        }
    }
}

/// 在无符号链接的虚拟文件系统上模拟一系列相对目录切换,将结果
/// 作为已分配切片返回。
///
/// 会解析 "." 和 "..",但不会将相对路径变为绝对路径。若结果路径为相对路径,
/// 且没有更早的分量可抵消,则保留 ".." 分量。
///
/// 结果不含末尾路径分隔符。
///
/// 此函数不执行系统调用。在真实文件系统上执行相同的路径查找序列,
/// 可能因符号链接而产生不同结果。
///
/// 另请参见:
/// * `resolveAlloc`
/// * `resolveAppendPosix`
pub fn resolveAllocPosix(gpa: Allocator, paths: []const []const u8) Allocator.Error![]u8 {
    var buffer: std.ArrayList(u8) = .empty;
    defer buffer.deinit(gpa);
    try resolveAppendPosix(gpa, &buffer, paths);
    try buffer.shrinkToLen(gpa);
    return buffer.toOwnedSliceAssert();
}

/// 在无符号链接的虚拟文件系统上模拟一系列相对目录切换,将结果追加到
/// 提供的数组列表中。
///
/// 会解析 "." 和 "..",但不会将相对路径变为绝对路径。若结果路径为相对路径,
/// 且没有更早的分量可抵消,则保留 ".." 分量。
///
/// 结果不含末尾路径分隔符。
///
/// 此函数不执行系统调用。在真实文件系统上执行相同的路径查找序列,
/// 可能因符号链接而产生不同结果。
///
/// 另请参见:
/// * `resolveAppend`
/// * `resolveAllocPosix`
pub fn resolveAppendPosix(gpa: Allocator, al: *std.ArrayList(u8), paths: []const []const u8) Allocator.Error!void {
    assert(paths.len > 0);

    const prev_len = al.items.len;
    errdefer al.shrinkRetainingCapacity(prev_len);

    var negative_count: usize = 0;
    var is_abs = false;

    for (paths) |p| {
        if (isAbsolutePosix(p)) {
            is_abs = true;
            negative_count = 0;
            al.shrinkRetainingCapacity(prev_len);
        }
        var it = mem.tokenizeScalar(u8, p, '/');
        while (it.next()) |component| {
            if (mem.eql(u8, component, ".")) {
                continue;
            } else if (mem.eql(u8, component, "..")) {
                if ((al.items.len - prev_len) == 0) {
                    negative_count += @intFromBool(!is_abs);
                    continue;
                }
                while (true) {
                    const ends_with_slash = al.items[al.items.len - 1] == '/';
                    al.items.len -= 1;
                    if (ends_with_slash or (al.items.len - prev_len) == 0) break;
                }
            } else if ((al.items.len - prev_len) > 0 or is_abs) {
                try al.ensureUnusedCapacity(gpa, 1 + component.len);
                al.appendAssumeCapacity('/');
                al.appendSliceAssumeCapacity(component);
            } else {
                try al.appendSlice(gpa, component);
            }
        }
    }

    if ((al.items.len - prev_len) == 0) {
        if (is_abs) {
            try al.resize(gpa, prev_len + 1);
            al.items[al.items.len - 1] = '/';
        } else if (negative_count == 0) {
            try al.resize(gpa, prev_len + 1);
            al.items[al.items.len - 1] = '.';
        } else {
            try al.resize(gpa, prev_len + 3 * negative_count - 1);
            var count = negative_count - 1;
            var i: usize = prev_len;
            while (count > 0) : (count -= 1) {
                al.items[i..][0..3].* = "../".*;
                i += 3;
            }
            al.items[i..][0..2].* = "..".*;
        }
    } else if (negative_count != 0) {
        const dest = try al.addManyAt(gpa, prev_len, 3 * negative_count);
        for (0..negative_count) |i| dest[i * 3 ..][0..3].* = "../".*;
    }
}

test resolve {
    try testResolveWindows(&[_][]const u8{ "a", "..\\..\\.." }, "..\\..");
    try testResolveWindows(&[_][]const u8{ "..", "", "..\\..\\foo" }, "..\\..\\..\\foo");
    try testResolveWindows(&[_][]const u8{ "a\\b\\c\\", "..\\..\\.." }, ".");
    try testResolveWindows(&[_][]const u8{"."}, ".");
    try testResolveWindows(&[_][]const u8{""}, ".");

    try testResolvePosix(&[_][]const u8{ "a", "../../.." }, "../..");
    try testResolvePosix(&[_][]const u8{ "..", "", "../../foo" }, "../../../foo");
    try testResolvePosix(&[_][]const u8{ "a/b/c/", "../../.." }, ".");
    try testResolvePosix(&[_][]const u8{"."}, ".");
    try testResolvePosix(&[_][]const u8{""}, ".");
}

test resolveAllocWindows {
    try testResolveWindows(
        &[_][]const u8{ "Z:\\", "/usr/local", "lib\\zig\\std\\array_list.zig" },
        "Z:\\usr\\local\\lib\\zig\\std\\array_list.zig",
    );
    try testResolveWindows(
        &[_][]const u8{ "z:\\", "usr/local", "lib\\zig" },
        "Z:\\usr\\local\\lib\\zig",
    );

    try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c", "/hi", "ok" }, "C:\\hi\\ok");
    try testResolveWindows(&[_][]const u8{ "c:\\a\\b\\c\\", ".\\..\\foo" }, "C:\\a\\b\\foo");
    try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "c:../a" }, "C:\\blah\\a");
    try testResolveWindows(&[_][]const u8{ "c:/blah\\blah", "d:/games", "C:../a" }, "C:\\blah\\a");
    try testResolveWindows(&[_][]const u8{ "c:/ignore", "d:\\a/b\\c/d", "\\e.exe" }, "D:\\e.exe");
    try testResolveWindows(&[_][]const u8{ "c:/ignore", "c:/some/file" }, "C:\\some\\file");
    // 第一个路径“设置”当前工作目录,因此驱动器相对路径随后相对于它。
    try testResolveWindows(&[_][]const u8{ "d:/foo", "d:some/dir//", "D:another" }, "D:\\foo\\some\\dir\\another");
    try testResolveWindows(&[_][]const u8{ "//server/share", "..", "relative\\" }, "\\\\server\\share\\relative");
    try testResolveWindows(&[_][]const u8{ "\\\\server/share", "..", "relative\\" }, "\\\\server\\share\\relative");
    try testResolveWindows(&[_][]const u8{ "\\\\server/share/ignore", "//server/share/bar" }, "\\\\server\\share\\bar");
    try testResolveWindows(&[_][]const u8{ "\\/server\\share/", "..", "relative" }, "\\\\server\\share\\relative");
    try testResolveWindows(&[_][]const u8{ "\\\\server\\share", "C:drive-relative" }, "C:drive-relative");
    try testResolveWindows(&[_][]const u8{ "c:/", "//" }, "\\\\");
    try testResolveWindows(&[_][]const u8{ "c:/", "//server" }, "\\\\server");
    try testResolveWindows(&[_][]const u8{ "c:/", "//server/share" }, "\\\\server\\share");
    try testResolveWindows(&[_][]const u8{ "c:/", "//server//share////" }, "\\\\server\\share\\");
    try testResolveWindows(&[_][]const u8{ "c:/", "///some//dir" }, "\\\\\\some\\dir");
    try testResolveWindows(&[_][]const u8{ "c:foo", "bar" }, "C:foo\\bar");
    try testResolveWindows(&[_][]const u8{ "C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js" }, "C:\\foo\\tmp.3\\cycles\\root.js");
    // 若无法提供驱动器专属的当前工作目录,则驱动器相对路径仍保持驱动器相对形式
    try testResolveWindows(&[_][]const u8{ "relative", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "../..\\..", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "../..\\..", "\\rooted", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "C:\\foo", "../..\\..", "\\rooted", "d:foo" }, "D:foo");
    try testResolveWindows(&[_][]const u8{ "D:relevant", "../..\\..", "d:foo" }, "D:..\\..\\foo");
    try testResolveWindows(&[_][]const u8{ "D:relevant", "../..\\..", "\\\\.\\ignored", "C:\\ignored", "C:ignored", "\\\\ignored", "d:foo" }, "D:..\\..\\foo");
    try testResolveWindows(&[_][]const u8{ "ignored", "\\\\.\\ignored", "C:\\ignored", "C:ignored", "\\\\ignored", "d:foo" }, "D:foo");
    // 没有可用于解析"根"的绝对路径时,根路径仍保持根路径形式
    try testResolveWindows(&[_][]const u8{ "/foo", "bar" }, "\\foo\\bar");
    // 以 UNC 路径为根
    try testResolveWindows(&[_][]const u8{ "//server/share/ignore", "/foo", "bar" }, "\\\\server\\share\\foo\\bar");
    try testResolveWindows(&[_][]const u8{ "//server/share/", "/foo" }, "\\\\server\\share\\foo");
    try testResolveWindows(&[_][]const u8{ "//server/share", "/foo" }, "\\\\server\\share\\foo");
    try testResolveWindows(&[_][]const u8{ "//server/", "/foo" }, "\\\\server\\foo");
    try testResolveWindows(&[_][]const u8{ "//server", "/foo" }, "\\\\server\\foo");
    try testResolveWindows(&[_][]const u8{ "//", "/foo" }, "\\\\foo");
    // 相对于驱动器相对路径确定根
    try testResolveWindows(&[_][]const u8{ "C:", "/foo", "bar" }, "C:\\foo\\bar");
    try testResolveWindows(&[_][]const u8{ "C:\\ignore", "C:", "/foo", "bar" }, "C:\\foo\\bar");
    try testResolveWindows(&[_][]const u8{ "C:\\ignore", "\\foo", "C:bar" }, "C:\\foo\\bar");
    // 仅最后一个有根路径有意义
    try testResolveWindows(&[_][]const u8{ "\\ignore", "\\foo" }, "\\foo");
    try testResolveWindows(&[_][]const u8{ "c:ignore", "ignore", "\\ignore", "\\foo" }, "C:\\foo");
    // 仅当之前存在驱动器路径时,根路径才与驱动器相对路径有关
    try testResolveWindows(&[_][]const u8{ "\\ignore", "C:foo" }, "C:foo");
    try testResolveWindows(&[_][]const u8{ "\\ignore", "\\ignore2", "C:foo" }, "C:foo");
    try testResolveWindows(&[_][]const u8{ "c:ignore", "\\ignore", "\\rooted", "C:foo" }, "C:\\rooted\\foo");
    try testResolveWindows(&[_][]const u8{ "c:\\ignore", "\\ignore", "\\rooted", "C:foo" }, "C:\\rooted\\foo");
    try testResolveWindows(&[_][]const u8{ "d:\\ignore", "\\ignore", "\\ignore2", "C:foo" }, "C:foo");
    // 根本地设备路径
    try testResolveWindows(&[_][]const u8{"\\/."}, "\\\\.");
    try testResolveWindows(&[_][]const u8{ "\\/.", "C:drive-relative" }, "C:drive-relative");
    try testResolveWindows(&[_][]const u8{"/\\?"}, "\\\\?");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\.", "foo" }, "\\\\.\\foo");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\?", "foo" }, "\\\\?\\foo");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "//.", "ignore", "\\foo" }, "\\\\.\\foo");
    try testResolveWindows(&[_][]const u8{ "ignore", "c:\\ignore", "\\\\?", "ignore", "\\foo" }, "\\\\?\\foo");

    // 保持相对路径为相对形式。
    try testResolveWindows(&[_][]const u8{"a/b"}, "a\\b");
    try testResolveWindows(&[_][]const u8{".."}, "..");
    try testResolveWindows(&[_][]const u8{"../.."}, "..\\..");
    try testResolveWindows(&[_][]const u8{ "C:foo", "../.." }, "C:..");
    try testResolveWindows(&[_][]const u8{ "d:foo", "../..\\.." }, "D:..\\..");

    // 本地设备路径将 \\.\ 或 \\?\ 视为“根”,其后所有内容均按普通路径部分处理。
    try testResolveWindows(&[_][]const u8{ "\\\\?\\C:\\foo", "../bar", "baz" }, "\\\\?\\C:\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "\\\\.\\C:/foo", "../../../../bar", "baz" }, "\\\\.\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "//./C:/foo", "../../../../bar", "baz" }, "\\\\.\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "\\\\.\\foo", ".." }, "\\\\.");
    try testResolveWindows(&[_][]const u8{ "\\\\.\\foo", "..\\.." }, "\\\\.");

    // 假定路径为 Win32 路径,因此将疑似 NT 路径的路径视为根相对路径。
    try testResolveWindows(&[_][]const u8{ "\\??\\C:\\foo", "/bar", "baz" }, "\\bar\\baz");
    try testResolveWindows(&[_][]const u8{ "C:\\", "\\??\\C:\\foo", "bar" }, "C:\\??\\C:\\foo\\bar");
}

test resolveAllocPosix {
    try testResolvePosix(&.{ "/a/b", "c" }, "/a/b/c");
    try testResolvePosix(&.{ "/a/b", "c", "//d", "e///" }, "/d/e");
    try testResolvePosix(&.{ "/a/b/c", "..", "../" }, "/a");
    try testResolvePosix(&.{ "/", "..", ".." }, "/");
    try testResolvePosix(&.{"/a/b/c/"}, "/a/b/c");

    try testResolvePosix(&.{ "/var/lib", "../", "file/" }, "/var/file");
    try testResolvePosix(&.{ "/var/lib", "/../", "file/" }, "/file");
    try testResolvePosix(&.{ "/some/dir", ".", "/absolute/" }, "/absolute");
    try testResolvePosix(&.{ "/foo/tmp.3/", "../tmp.3/cycles/root.js" }, "/foo/tmp.3/cycles/root.js");

    // 保持相对路径为相对形式。
    try testResolvePosix(&.{"a/b"}, "a/b");
    try testResolvePosix(&.{"."}, ".");
    try testResolvePosix(&.{ ".", "src/test.zig", "..", "../test/cases.zig" }, "test/cases.zig");
}

fn testResolveWindows(paths: []const []const u8, expected: []const u8) !void {
    {
        const actual = try resolveAllocWindows(testing.allocator, paths);
        defer testing.allocator.free(actual);
        try testing.expectEqualStrings(expected, actual);
    }

    {
        var buffer: std.ArrayList(u8) = .empty;
        defer buffer.deinit(testing.allocator);
        try buffer.append(testing.allocator, 99);

        try resolveAppendWindows(testing.allocator, &buffer, paths);
        // 测试其是否保留了数组列表先前的内容。
        try testing.expectEqual(expected.len + 1, buffer.items.len);
        try testing.expectEqual(99, buffer.items[0]);
        const result = buffer.items[1..];
        try testing.expectEqualStrings(expected, result);
    }
}

fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void {
    {
        const actual = try resolveAllocPosix(testing.allocator, paths);
        defer testing.allocator.free(actual);
        try testing.expectEqualStrings(expected, actual);
    }

    {
        var buffer: std.ArrayList(u8) = .empty;
        defer buffer.deinit(testing.allocator);
        try buffer.append(testing.allocator, 99);

        try resolveAppendPosix(testing.allocator, &buffer, paths);
        // 测试其是否保留了数组列表先前的内容。
        try testing.expectEqual(expected.len + 1, buffer.items.len);
        try testing.expectEqual(99, buffer.items[0]);
        const result = buffer.items[1..];
        try testing.expectEqualStrings(expected, result);
    }
}

/// 移除文件路径的最后一个分量。
///
/// 若路径是当前目录中的文件(不包含目录分量),
/// 则返回 null。
///
/// 若路径是根目录,则返回 null。
pub fn dirname(path: []const u8) ?[]const u8 {
    if (native_os == .windows) {
        return dirnameWindows(path);
    } else {
        return dirnamePosix(path);
    }
}

pub fn dirnameWindows(path: []const u8) ?[]const u8 {
    return dirnameInner(.windows, path);
}

pub fn dirnamePosix(path: []const u8) ?[]const u8 {
    return dirnameInner(.posix, path);
}

fn dirnameInner(comptime path_type: PathType, path: []const u8) ?[]const u8 {
    var it: ComponentIterator(path_type, u8) = .init(path);
    _ = it.last() orelse return null;
    const up = it.previous() orelse return it.root();
    return up.path;
}

test dirnamePosix {
    try testDirnamePosix("/a/b/c", "/a/b");
    try testDirnamePosix("/a/b/c///", "/a/b");
    try testDirnamePosix("/a", "/");
    try testDirnamePosix("/", null);
    try testDirnamePosix("//", null);
    try testDirnamePosix("///", null);
    try testDirnamePosix("////", null);
    try testDirnamePosix("", null);
    try testDirnamePosix("a", null);
    try testDirnamePosix("a/", null);
    try testDirnamePosix("a//", null);
}

test dirnameWindows {
    try testDirnameWindows("c:\\", null);
    try testDirnameWindows("c:\\\\", null);
    try testDirnameWindows("c:\\foo", "c:\\");
    try testDirnameWindows("c:\\\\foo\\", "c:\\");
    try testDirnameWindows("c:\\foo\\bar", "c:\\foo");
    try testDirnameWindows("c:\\foo\\bar\\", "c:\\foo");
    try testDirnameWindows("c:\\\\foo\\bar\\baz", "c:\\\\foo\\bar");
    try testDirnameWindows("\\", null);
    try testDirnameWindows("\\foo", "\\");
    try testDirnameWindows("\\foo\\", "\\");
    try testDirnameWindows("\\foo\\bar", "\\foo");
    try testDirnameWindows("\\foo\\bar\\", "\\foo");
    try testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar");
    try testDirnameWindows("c:", null);
    try testDirnameWindows("c:foo", "c:");
    try testDirnameWindows("c:foo\\", "c:");
    try testDirnameWindows("c:foo\\bar", "c:foo");
    try testDirnameWindows("c:foo\\bar\\", "c:foo");
    try testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar");
    try testDirnameWindows("file:stream", null);
    try testDirnameWindows("dir\\file:stream", "dir");
    try testDirnameWindows("\\\\unc\\share", null);
    try testDirnameWindows("\\\\unc\\share\\\\", null);
    try testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\");
    try testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\");
    try testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo");
    try testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo");
    try testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar");
    try testDirnameWindows("\\\\.", null);
    try testDirnameWindows("\\\\.\\", null);
    try testDirnameWindows("\\\\.\\device", "\\\\.\\");
    try testDirnameWindows("\\\\.\\device\\", "\\\\.\\");
    try testDirnameWindows("\\\\.\\device\\foo", "\\\\.\\device");
    try testDirnameWindows("\\\\?", null);
    try testDirnameWindows("\\\\?\\", null);
    try testDirnameWindows("\\\\?\\device", "\\\\?\\");
    try testDirnameWindows("\\\\?\\device\\", "\\\\?\\");
    try testDirnameWindows("\\\\?\\device\\foo", "\\\\?\\device");
    try testDirnameWindows("/a/b/", "/a");
    try testDirnameWindows("/a/b", "/a");
    try testDirnameWindows("/a", "/");
    try testDirnameWindows("", null);
    try testDirnameWindows("/", null);
    try testDirnameWindows("////", null);
    try testDirnameWindows("foo", null);
}

fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) !void {
    if (dirnamePosix(input)) |output| {
        try testing.expect(mem.eql(u8, output, expected_output.?));
    } else {
        try testing.expect(expected_output == null);
    }
}

fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) !void {
    if (dirnameWindows(input)) |output| {
        try testing.expectEqualStrings(expected_output.?, output);
    } else {
        try testing.expect(expected_output == null);
    }
}

pub fn basename(path: []const u8) []const u8 {
    if (native_os == .windows) {
        return basenameWindows(path);
    } else {
        return basenamePosix(path);
    }
}

pub fn basenamePosix(path: []const u8) []const u8 {
    return basenameInner(.posix, path);
}

pub fn basenameWindows(path: []const u8) []const u8 {
    return basenameInner(.windows, path);
}

fn basenameInner(comptime path_type: PathType, path: []const u8) []const u8 {
    var it: ComponentIterator(path_type, u8) = .init(path);
    const last = it.last() orelse return &[_]u8{};
    return last.name;
}

test basename {
    try testBasename("", "");
    try testBasename("/", "");
    try testBasename("/dir/basename.ext", "basename.ext");
    try testBasename("/basename.ext", "basename.ext");
    try testBasename("basename.ext", "basename.ext");
    try testBasename("basename.ext/", "basename.ext");
    try testBasename("basename.ext//", "basename.ext");
    try testBasename("/aaa/bbb", "bbb");
    try testBasename("/aaa/", "aaa");
    try testBasename("/aaa/b", "b");
    try testBasename("/a/b", "b");

    // 在 Windows 上,这是仅包含服务器名称部分的 UNC 路径。
    try testBasename("//a", if (native_os == .windows) "" else "a");

    try testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext");
    try testBasenamePosix("\\basename.ext", "\\basename.ext");
    try testBasenamePosix("basename.ext", "basename.ext");
    try testBasenamePosix("basename.ext\\", "basename.ext\\");
    try testBasenamePosix("basename.ext\\\\", "basename.ext\\\\");
    try testBasenamePosix("foo", "foo");

    try testBasenameWindows("\\dir\\basename.ext", "basename.ext");
    try testBasenameWindows("\\basename.ext", "basename.ext");
    try testBasenameWindows("basename.ext", "basename.ext");
    try testBasenameWindows("basename.ext\\", "basename.ext");
    try testBasenameWindows("basename.ext\\\\", "basename.ext");
    try testBasenameWindows("foo", "foo");
    try testBasenameWindows("C:", "");
    try testBasenameWindows("C:.", ".");
    try testBasenameWindows("C:\\", "");
    try testBasenameWindows("C:\\dir\\base.ext", "base.ext");
    try testBasenameWindows("C:\\basename.ext", "basename.ext");
    try testBasenameWindows("C:basename.ext", "basename.ext");
    try testBasenameWindows("C:basename.ext\\", "basename.ext");
    try testBasenameWindows("C:basename.ext\\\\", "basename.ext");
    try testBasenameWindows("\\\\.", "");
    try testBasenameWindows("\\\\.\\", "");
    try testBasenameWindows("\\\\.\\basename.ext", "basename.ext");
    try testBasenameWindows("\\\\?", "");
    try testBasenameWindows("\\\\?\\", "");
    try testBasenameWindows("\\\\?\\basename.ext", "basename.ext");
    try testBasenameWindows("C:foo", "foo");
    try testBasenameWindows("file:stream", "file:stream");
}

fn testBasename(input: []const u8, expected_output: []const u8) !void {
    try testing.expectEqualSlices(u8, expected_output, basename(input));
}

fn testBasenamePosix(input: []const u8, expected_output: []const u8) !void {
    try testing.expectEqualSlices(u8, expected_output, basenamePosix(input));
}

fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void {
    try testing.expectEqualSlices(u8, expected_output, basenameWindows(input));
}

/// 以已分配切片形式,返回从 `from` 到 `to` 的非绝对路径。
///
/// 除内存分配外,此函数为纯函数:结果仅取决于输入参数。
///
/// 若 `from` 与 `to` 分别经 `resolve` 解析后得到相同路径,则返回零长度字符串。
///
/// 参见 `relativePosix` 和 `relativeWindows`,了解操作系统专用细节及 `environ_map` 的使用方式。
///
/// 另见:
/// * `relativeAppend`
///
pub fn relativeAlloc(
    gpa: Allocator,
    cwd: []const u8,
    environ_map: ?*const std.process.Environ.Map,
    from: []const u8,
    to: []const u8,
) Allocator.Error![]u8 {
    if (native_os == .windows) {
        return relativeAllocWindows(gpa, cwd, environ_map, from, to);
    } else {
        return relativeAllocPosix(gpa, cwd, from, to);
    }
}

/// 将从 `from` 到 `to` 的非绝对路径追加到给定数组列表。
///
/// 除修改给定数组列表外,此函数为纯函数:结果仅取决于输入参数,不执行文件系统操作。
///
/// 若 `from` 与 `to` 分别经 `resolveAppend` 解析后得到相同路径,则返回零长度字符串。
///
/// 参见 `relativeAppendPosix` 和 `relativeAppendWindows`,了解操作系统专用细节及 `environ_map` 的使用方式。
///
/// 另见:
/// * `relativeAlloc`
///
///
///
pub fn relativeAppend(
    gpa: Allocator,
    al: *std.ArrayList(u8),
    cwd: []const u8,
    environ_map: ?*const std.process.Environ.Map,
    from: []const u8,
    to: []const u8,
) Allocator.Error!void {
    if (native_os == .windows) {
        return relativeAppendWindows(gpa, al, cwd, environ_map, from, to);
    } else {
        return relativeAppendPosix(gpa, al, cwd, from, to);
    }
}

/// 按照 Windows 规则,将从 `from` 到 `to` 的非绝对路径作为已分配的切片返回。
///
/// 除内存分配外,这是纯函数;结果完全由输入参数决定。
///
/// 如果 `from` 和 `to` 分别解析后(调用各自的 `resolve`)得到同一路径,则返回长度为零的字符串。
///
/// 结果不保证是相对路径,因为路径可能位于不同卷上。此时结果将是 `to` 的规范化绝对路径。
///
/// 每个驱动器的当前工作目录存储在特殊的半隐藏环境变量中,格式为 `=<drive-letter>:`,例如 `=C:`。
/// 这类当前工作目录纯粹是 shell 概念,因此不能保证它已设置,也不能保证其准确性。这就是提供 `environ_map` 参数的唯一原因。若该环境变量不存在,则将 `null` 视为等同情况。
///
/// 另见:
/// `relativeAlloc`
/// `relativeAppendWindows`
///
///
///
///
pub fn relativeAllocWindows(
    gpa: Allocator,
    cwd: []const u8,
    environ_map: ?*const std.process.Environ.Map,
    from: []const u8,
    to: []const u8,
) Allocator.Error![]u8 {
    const parsed_from = parsePathWindows(u8, from);
    const parsed_to = parsePathWindows(u8, to);

    const result_is_always_to = x: {
        if (parsed_from.kind != parsed_to.kind) {
            break :x false;
        }
        switch (parsed_from.kind) {
            .drive_relative, .drive_absolute => {
                break :x !compareDiskDesignators(u8, .drive, parsed_from.root, parsed_to.root);
            },
            .unc_absolute => {
                break :x !compareDiskDesignators(u8, .unc, parsed_from.root, parsed_to.root);
            },
            .relative, .rooted, .local_device => break :x false,
            .root_local_device => break :x true,
        }
    };

    if (result_is_always_to) {
        return windowsResolveAgainstCwd(gpa, cwd, environ_map, to, parsed_to);
    }

    const resolved_from = try windowsResolveAgainstCwd(gpa, cwd, environ_map, from, parsed_from);
    defer gpa.free(resolved_from);
    var clean_up_resolved_to = true;
    const resolved_to = try windowsResolveAgainstCwd(gpa, cwd, environ_map, to, parsed_to);
    defer if (clean_up_resolved_to) gpa.free(resolved_to);

    const parsed_resolved_from = parsePathWindows(u8, resolved_from);
    const parsed_resolved_to = parsePathWindows(u8, resolved_to);

    const result_is_to = x: {
        if (parsed_resolved_from.kind != parsed_resolved_to.kind) {
            break :x true;
        }
        switch (parsed_resolved_from.kind) {
            .drive_absolute, .drive_relative => {
                break :x !compareDiskDesignators(u8, .drive, parsed_resolved_from.root, parsed_resolved_to.root);
            },
            .unc_absolute => {
                break :x !compareDiskDesignators(u8, .unc, parsed_resolved_from.root, parsed_resolved_to.root);
            },
            .relative, .rooted, .local_device => break :x false,
            .root_local_device => break :x true,
        }
    };

    if (result_is_to) {
        clean_up_resolved_to = false;
        return resolved_to;
    }

    var from_it = mem.tokenizeAny(u8, resolved_from[parsed_resolved_from.root.len..], "/\\");
    var to_it = mem.tokenizeAny(u8, resolved_to[parsed_resolved_to.root.len..], "/\\");
    while (true) {
        const from_component = from_it.next() orelse return gpa.dupe(u8, to_it.rest());
        const to_rest = to_it.rest();
        if (to_it.next()) |to_component| {
            if (eqlIgnoreCaseWtf8(from_component, to_component))
                continue;
        }
        var up_index_end = "..".len;
        while (from_it.next()) |_| {
            up_index_end += "\\..".len;
        }
        const result = try gpa.alloc(u8, up_index_end + @intFromBool(to_rest.len > 0) + to_rest.len);
        errdefer gpa.free(result);

        result[0..2].* = "..".*;
        var result_index: usize = 2;
        while (result_index < up_index_end) {
            result[result_index..][0..3].* = "\\..".*;
            result_index += 3;
        }

        var rest_it = mem.tokenizeAny(u8, to_rest, "/\\");
        while (rest_it.next()) |to_component| {
            result[result_index] = '\\';
            result_index += 1;
            @memcpy(result[result_index..][0..to_component.len], to_component);
            result_index += to_component.len;
        }

        return gpa.realloc(result, result_index);
    }
    return [_]u8{};
}

/// 按照 Windows 规则,将从 `from` 到 `to` 的非绝对路径追加到提供的数组列表。
///
/// 除内存分配外,这是纯函数;结果完全由输入参数决定。
///
/// 如果 `from` 和 `to` 分别解析后(调用各自的 `resolve`)得到同一路径,则返回长度为零的字符串。
///
/// 结果不保证是相对路径,因为路径可能位于不同卷上。此时结果将是 `to` 的规范化绝对路径。
///
/// 每个驱动器的当前工作目录存储在特殊的半隐藏环境变量中,格式为 `=<drive-letter>:`,例如 `=C:`。
/// 这类当前工作目录纯粹是 shell 概念,因此不能保证它已设置,也不能保证其准确性。这就是提供 `environ_map` 参数的唯一原因。若该环境变量不存在,则将 `null` 视为等同情况。
///
/// 另见:
/// `relativeAppend`
/// `relativeAllocWindows`
///
///
///
///
pub fn relativeAppendWindows(
    gpa: Allocator,
    al: *std.ArrayList(u8),
    cwd: []const u8,
    environ_map: ?*const std.process.Environ.Map,
    from: []const u8,
    to: []const u8,
) Allocator.Error!void {
    const result = try relativeAllocWindows(gpa, cwd, environ_map, from, to);
    defer gpa.free(result);
    try al.appendSlice(gpa, result);
}

fn windowsResolveAgainstCwd(
    gpa: Allocator,
    cwd: []const u8,
    environ_map: ?*const std.process.Environ.Map,
    path: []const u8,
    parsed: WindowsPath2(u8),
) ![]u8 {
    // 容纳 256 个 WTF-16 代码单元的空间;每个代码单元最多对应 3 个 WTF-8 字节。
    var buf: [256 * 3]u8 = undefined;
    var temp_allocator_state: std.heap.BufferFirstAllocator = .init(&buf, gpa);
    return switch (parsed.kind) {
        .drive_absolute,
        .unc_absolute,
        .root_local_device,
        .local_device,
        => try resolveAllocWindows(gpa, &.{path}),

        .relative => try resolveAllocWindows(gpa, &.{ cwd, path }),

        .rooted => blk: {
            const parsed_cwd = parsePathWindows(u8, cwd);
            switch (parsed_cwd.kind) {
                .drive_absolute => {
                    var drive_buf = "_:\\".*;
                    drive_buf[0] = cwd[0];
                    break :blk try resolveAllocWindows(gpa, &.{ &drive_buf, path });
                },
                .unc_absolute => {
                    break :blk try resolveAllocWindows(gpa, &.{ parsed_cwd.root, path });
                },
                // 实际相当于格式错误的当前工作目录,放弃并直接返回规范化路径
                else => break :blk try resolveAllocWindows(gpa, &.{path}),
            }
        },
        .drive_relative => blk: {
            const temp_allocator = temp_allocator_state.allocator();
            const drive_cwd = drive_cwd: {
                const parsed_cwd = parsePathWindows(u8, cwd);

                if (parsed_cwd.kind == .drive_absolute) {
                    const drive_letter_w = parsed_cwd.root[0];
                    const drive_letters_match = drive_letter_w <= 0x7F and
                        std.ascii.toUpper(@intCast(drive_letter_w)) == std.ascii.toUpper(parsed.root[0]);
                    if (drive_letters_match)
                        break :drive_cwd cwd;

                    if (environ_map) |m| {
                        if (m.get(&.{ '=', parsed.root[0], ':' })) |v| {
                            break :drive_cwd try temp_allocator.dupe(u8, v);
                        }
                    }
                }

                const drive_buf = try temp_allocator.alloc(u8, 3);
                drive_buf[0] = parsed.root[0];
                drive_buf[1] = ':';
                drive_buf[2] = '\\';
                break :drive_cwd drive_buf;
            };
            defer temp_allocator.free(drive_cwd);
            break :blk try resolveAllocWindows(gpa, &.{ drive_cwd, path });
        },
    };
}

/// 按照 POSIX 规则,返回从 `from` 到 `to` 的非绝对路径,作为已分配切片。
///
/// 除内存分配外,这是纯函数;结果仅取决于输入参数。
///
/// 如果 `from` 和 `to` 分别调用 `resolve` 后解析为同一路径,
/// 则返回零长度字符串。
///
/// 另请参见:
/// * `relativeAlloc`
/// * `relativeAppendPosix`
pub fn relativeAllocPosix(gpa: Allocator, cwd: []const u8, from: []const u8, to: []const u8) Allocator.Error![]u8 {
    var buffer: std.ArrayList(u8) = .empty;
    defer buffer.deinit(gpa);
    try relativeAppendPosix(gpa, &buffer, cwd, from, to);
    try buffer.shrinkToLen(gpa);
    return buffer.toOwnedSliceAssert();
}

/// 按 POSIX 规则,将从 `from` 到 `to` 的非绝对路径追加到给定数组列表。
///
/// 除修改给定数组列表外,此函数为纯函数:结果仅取决于输入参数,不执行文件系统操作。
///
/// 若 `from` 与 `to` 分别经 `resolveAppend` 解析后得到相同路径,则不向数组列表追加任何内容。
///
/// 另见:
/// * `relativeAppend`
/// * `relativeAllocPosix`
///
///
pub fn relativeAppendPosix(
    gpa: Allocator,
    al: *std.ArrayList(u8),
    cwd: []const u8,
    from: []const u8,
    to: []const u8,
) Allocator.Error!void {
    const orig_len = al.items.len;
    errdefer al.items.len = orig_len;

    const resolved_from_start = al.items.len;
    try resolveAppendPosix(gpa, al, &.{ cwd, from });
    const resolved_from_end = al.items.len;

    const resolved_to_start = al.items.len;
    try resolveAppendPosix(gpa, al, &.{ cwd, to });
    const resolved_to_end = al.items.len;

    var from_it = mem.tokenizeScalar(u8, al.items[resolved_from_start..resolved_from_end], '/');
    var to_it = mem.tokenizeScalar(u8, al.items[resolved_to_start..resolved_to_end], '/');
    while (true) {
        const from_component = from_it.next() orelse {
            const result = to_it.rest();
            @memmove(al.items[orig_len..][0..result.len], result);
            al.shrinkRetainingCapacity(orig_len + result.len);
            return;
        };
        const to_rest = to_it.rest();
        if (to_it.next()) |to_component| {
            if (mem.eql(u8, from_component, to_component))
                continue;
        }
        var up_count: usize = 1;
        while (from_it.next()) |_| up_count += 1;
        const up_index_end = up_count * "../".len;
        const result = al.items[orig_len..];

        var result_index: usize = 0;
        while (result_index < up_index_end) {
            result[result_index..][0..3].* = "../".*;
            result_index += 3;
        }
        if (to_rest.len == 0) {
            // 去除末尾斜杠。
            al.shrinkRetainingCapacity(orig_len + result_index - 1);
            return;
        }
        @memmove(result[result_index..][0..to_rest.len], to_rest);
        al.shrinkRetainingCapacity(orig_len + result_index + to_rest.len);
        return;
    }

    al.shrinkRetainingCapacity(orig_len);
}

test relative {
    try testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games");
    try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", "..");
    try testRelativeWindows("c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc");
    try testRelativeWindows("c:/aaaa/bbbb", "C:/aaaa/bbbb", "");
    try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc");
    try testRelativeWindows("c:/aaaa/", "c:/aaaa/cccc", "cccc");
    try testRelativeWindows("c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb");
    try testRelativeWindows("c:/aaaa/bbbb", "d:\\", "D:\\");
    try testRelativeWindows("c:/AaAa/bbbb", "c:/aaaa/bbbb", "");
    try testRelativeWindows("c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc");
    try testRelativeWindows("C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\..");
    try testRelativeWindows("C:\\foo\\test", "C:\\foo\\test\\bar\\package.json", "bar\\package.json");
    try testRelativeWindows("C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz");
    try testRelativeWindows("C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux");
    try testRelativeWindows("\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz");
    try testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar", "..");
    try testRelativeWindows("\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz");
    try testRelativeWindows("\\\\foo/bar\\baz-quux", "//foo\\bar/baz", "..\\baz");
    try testRelativeWindows("\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux");
    try testRelativeWindows("C:\\baz-quux", "C:\\baz", "..\\baz");
    try testRelativeWindows("C:\\baz", "C:\\baz-quux", "..\\baz-quux");
    try testRelativeWindows("\\\\foo\\baz-quux", "\\\\foo\\baz", "\\\\foo\\baz");
    try testRelativeWindows("\\\\foo\\baz", "\\\\foo\\baz-quux", "\\\\foo\\baz-quux");
    try testRelativeWindows("C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz");
    try testRelativeWindows("\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz");

    try testRelativeWindows("c:blah\\blah", "c:foo", "..\\..\\foo");
    try testRelativeWindows("c:foo", "c:foo\\bar", "bar");
    try testRelativeWindows("\\blah\\blah", "\\foo", "..\\..\\foo");
    try testRelativeWindows("\\foo", "\\foo\\bar", "bar");

    try testRelativeWindows("a/b/c", "a\\b", "..");
    try testRelativeWindows("a/b/c", "a", "..\\..");
    try testRelativeWindows("a/b/c", "a\\b\\c\\d", "d");

    try testRelativeWindows("\\\\FOO\\bar\\baz", "\\\\foo\\BAR\\BAZ", "");
    // 支持 Unicode 的不区分大小写路径比较
    try testRelativeWindows("\\\\кириллица\\ελληνικά\\português", "\\\\КИРИЛЛИЦА\\ΕΛΛΗΝΙΚΆ\\PORTUGUÊS", "");

    try testRelativePosix("/var/lib", "/var", "..");
    try testRelativePosix("/var/lib", "/bin", "../../bin");
    try testRelativePosix("/var/lib", "/var/lib", "");
    try testRelativePosix("/var/lib", "/var/apache", "../apache");
    try testRelativePosix("/var/", "/var/lib", "lib");
    try testRelativePosix("/", "/var/lib", "var/lib");
    try testRelativePosix("/foo/test", "/foo/test/bar/package.json", "bar/package.json");
    try testRelativePosix("/Users/a/web/b/test/mails", "/Users/a/web/b", "../..");
    try testRelativePosix("/foo/bar/baz-quux", "/foo/bar/baz", "../baz");
    try testRelativePosix("/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux");
    try testRelativePosix("/baz-quux", "/baz", "../baz");
    try testRelativePosix("/baz", "/baz-quux", "../baz-quux");
}

fn testRelativePosix(from: []const u8, to: []const u8, expected_output: []const u8) !void {
    {
        const result = try relativePosix(testing.allocator, ".", from, to);
        defer testing.allocator.free(result);
        try testing.expectEqualStrings(expected_output, result);
    }

    {
        var buffer: std.ArrayList(u8) = .empty;
        defer buffer.deinit(testing.allocator);
        try buffer.append(testing.allocator, 99);

        try relativeAppendPosix(testing.allocator, &buffer, ".", from, to);
        // 测试其是否保留了数组列表先前的内容。
        try testing.expectEqual(expected_output.len + 1, buffer.items.len);
        try testing.expectEqual(99, buffer.items[0]);
        const result = buffer.items[1..];
        try testing.expectEqualStrings(expected_output, result);
    }
}

fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []const u8) !void {
    {
        const result = try relativeAllocWindows(testing.allocator, ".", null, from, to);
        defer testing.allocator.free(result);
        try testing.expectEqualStrings(expected_output, result);
    }
    {
        var buffer: std.ArrayList(u8) = .empty;
        defer buffer.deinit(testing.allocator);
        try buffer.append(testing.allocator, 99);

        try relativeAppendWindows(testing.allocator, &buffer, ".", null, from, to);
        // 测试其是否保留了数组列表先前的内容。
        try testing.expectEqual(expected_output.len + 1, buffer.items.len);
        try testing.expectEqual(99, buffer.items[0]);
        const result = buffer.items[1..];
        try testing.expectEqualStrings(expected_output, result);
    }
}

/// 查找由 `.` 分隔的文件扩展名,并返回该 `.` 起的字符串。
/// 文件名以 `.` 开头且名称中没有其他 `.` 时,
/// 视为没有扩展名,此时返回 ""。
/// 示例:
/// - `"main.zig"`      ⇒ `".zig"`
/// - `"src/main.zig"`  ⇒ `".zig"`
/// - `".gitignore"`    ⇒ `""`
/// - `".image.png"`    ⇒ `".png"`
/// - `"keep."`         ⇒ `"."`
/// - `"src.keep.me"`   ⇒ `".me"`
/// - `"/src/keep.me"`  ⇒ `".me"`
/// - `"/src/keep.me/"` ⇒ `".me"`
/// 即使切片长度为零,也保证返回切片的指针位于
/// `path` 的起始和末尾指针所界定的地址范围内。
pub fn extension(path: []const u8) []const u8 {
    const filename = basename(path);
    const index = mem.findScalarLast(u8, filename, '.') orelse return path[path.len..];
    if (index == 0) return path[path.len..];
    return filename[index..];
}

fn testExtension(path: []const u8, expected: []const u8) !void {
    try testing.expectEqualStrings(expected, extension(path));
}

test extension {
    try testExtension("", "");
    try testExtension(".", "");
    try testExtension("a.", ".");
    try testExtension("abc.", ".");
    try testExtension(".a", "");
    try testExtension(".file", "");
    try testExtension(".gitignore", "");
    try testExtension(".image.png", ".png");
    try testExtension("file.ext", ".ext");
    try testExtension("file.ext.", ".");
    try testExtension("very-long-file.bruh", ".bruh");
    try testExtension("a.b.c", ".c");
    try testExtension("a.b.c/", ".c");

    try testExtension("/", "");
    try testExtension("/.", "");
    try testExtension("/a.", ".");
    try testExtension("/abc.", ".");
    try testExtension("/.a", "");
    try testExtension("/.file", "");
    try testExtension("/.gitignore", "");
    try testExtension("/file.ext", ".ext");
    try testExtension("/file.ext.", ".");
    try testExtension("/very-long-file.bruh", ".bruh");
    try testExtension("/a.b.c", ".c");
    try testExtension("/a.b.c/", ".c");

    try testExtension("/foo/bar/bam/", "");
    try testExtension("/foo/bar/bam/.", "");
    try testExtension("/foo/bar/bam/a.", ".");
    try testExtension("/foo/bar/bam/abc.", ".");
    try testExtension("/foo/bar/bam/.a", "");
    try testExtension("/foo/bar/bam/.file", "");
    try testExtension("/foo/bar/bam/.gitignore", "");
    try testExtension("/foo/bar/bam/file.ext", ".ext");
    try testExtension("/foo/bar/bam/file.ext.", ".");
    try testExtension("/foo/bar/bam/very-long-file.bruh", ".bruh");
    try testExtension("/foo/bar/bam/a.b.c", ".c");
    try testExtension("/foo/bar/bam/a.b.c/", ".c");
}

/// 返回此路径的最后一个分量,并移除扩展名(若存在):
/// - "hello/world/lib.tar.gz" ⇒ "lib.tar"
/// - "hello/world/lib.tar"    ⇒ "lib"
/// - "hello/world/lib"        ⇒ "lib"
pub fn stem(path: []const u8) []const u8 {
    const filename = basename(path);
    const index = mem.findScalarLast(u8, filename, '.') orelse return filename;
    if (index == 0) return filename;
    return filename[0..index];
}

fn testStem(path: []const u8, expected: []const u8) !void {
    try testing.expectEqualStrings(expected, stem(path));
}

test stem {
    try testStem("hello/world/lib.tar.gz", "lib.tar");
    try testStem("hello/world/lib.tar", "lib");
    try testStem("hello/world/lib", "lib");
    try testStem("hello/lib/", "lib");
    try testStem("hello...", "hello..");
    try testStem("hello.", "hello");
    try testStem("/hello.", "hello");
    try testStem("hello/world/.gitignore", ".gitignore");
    try testStem("/.gitignore", ".gitignore");
    try testStem(".gitignore", ".gitignore");
    try testStem(".gitignore/", ".gitignore");
    try testStem("hello/world/.image.png", ".image");
    try testStem("/.image.png", ".image");
    try testStem(".image.png", ".image");
    try testStem(".image.png/", ".image");
    try testStem("file.ext", "file");
    try testStem("file.ext.", "file.ext");
    try testStem("a.b.c", "a.b");
    try testStem("a.b.c/", "a.b");
    try testStem(".a", ".a");
    try testStem("///", "");
    try testStem("..", ".");
    try testStem(".", ".");
    try testStem(" ", " ");
    try testStem("", "");
}

/// 可向前及向后移动的路径分量迭代器。
/// 路径的“根”,POSIX 为 `/`,Windows 为 `C:\`、`\\server\share\` 等,
/// 会特殊处理,绝不会由
/// `first`、`last`、`next` 或 `previous` 返回。
/// 迭代时会跳过连续多个路径分隔符,
/// 将其视为单个分隔符。
/// 返回的所有分量名/路径都是原始路径的切片。
/// 迭代时不对路径进行规范化。
pub fn ComponentIterator(comptime path_type: PathType, comptime T: type) type {
    return struct {
        path: []const T,
        /// 根路径的长度,最多包含一个末尾路径分隔符(例如 `C:/`)。
        root_len: usize,
        /// 根路径的长度,包含所有尾随路径分隔符(例如 `C://///`)。
        root_end_index: usize,
        start_index: usize = 0,
        end_index: usize = 0,

        const Self = @This();

        pub const Component = struct {
            /// 当前组件的路径名称,例如“b”。其中永远不会包含路径分隔符。
            ///
            name: []const T,
            /// 截至并包含当前组件的完整路径,例如“/a/b”。
            /// 末尾永远不会有路径分隔符。
            path: []const T,
        };

        /// 调用 `init` 后,`next` 将返回根之后的第一个分量
        /// (无需在 `init` 后调用 `first`)。
        /// 要反向迭代(从路径末尾到开头),请在 `init` 后调用 `last`,
        /// 再通过调用 `previous` 迭代。
        /// 对于 Windows 路径,假定路径位于 Win32 命名空间。
        pub fn init(path: []const T) Self {
            const root_len: usize = switch (path_type) {
                .posix, .uefi => posix: {
                    // UEFI 与 POSIX 的根路径仅路径分隔符不同。
                    break :posix if (path.len > 0 and path_type.isSep(T, path[0])) 1 else 0;
                },
                .windows => windows: {
                    break :windows parsePathWindows(T, path).root.len;
                },
            };
            // 若根目录之后紧跟重复的路径分隔符,
            // 则记录该信息,避免在遍历路径部分时
            // 再次处理。
            var root_end_index = root_len;
            for (path[root_len..]) |c| {
                if (!path_type.isSep(T, c)) break;
                root_end_index += 1;
            }
            return .{
                .path = path,
                .root_len = root_len,
                .root_end_index = root_end_index,
                .start_index = root_end_index,
                .end_index = root_end_index,
            };
        }

        /// 如果路径不是相对路径,则返回其根;否则返回 null。
        /// POSIX 路径的根为 `/`。
        /// Windows 路径的根形如 `C:\`、`\\server\share\` 等。
        /// UEFI 路径的根为 `\`。
        pub fn root(self: Self) ?[]const T {
            if (self.root_end_index == 0) return null;
            return self.path[0..self.root_len];
        }

        /// 返回从路径开头计算的第一个分量。
        /// 例如,路径为 `/a/b/c` 时,返回 `a` 分量。
        /// 调用 `first` 后,`previous` 始终返回 `null`,`next` 则返回 `first` 所返回分量右侧的分量,若存在。
        ///
        pub fn first(self: *Self) ?Component {
            self.start_index = self.root_end_index;
            self.end_index = self.start_index;
            while (self.end_index < self.path.len and !path_type.isSep(T, self.path[self.end_index])) {
                self.end_index += 1;
            }
            if (self.end_index == self.start_index) return null;
            return .{
                .name = self.path[self.start_index..self.end_index],
                .path = self.path[0..self.end_index],
            };
        }

        /// 返回从路径末尾计算的最后一个分量。
        /// 例如,路径为 `/a/b/c` 时,返回 `c` 分量。
        /// 调用 `last` 后,`next` 始终返回 `null`,`previous` 则返回 `last` 所返回分量左侧的分量,若存在。
        ///
        pub fn last(self: *Self) ?Component {
            self.end_index = self.path.len;
            while (true) {
                if (self.end_index == self.root_end_index) {
                    self.start_index = self.end_index;
                    return null;
                }
                if (!path_type.isSep(T, self.path[self.end_index - 1])) break;
                self.end_index -= 1;
            }
            self.start_index = self.end_index;
            while (true) {
                if (self.start_index == self.root_end_index) break;
                if (path_type.isSep(T, self.path[self.start_index - 1])) break;
                self.start_index -= 1;
            }
            if (self.start_index == self.end_index) return null;
            return .{
                .name = self.path[self.start_index..self.end_index],
                .path = self.path[0..self.end_index],
            };
        }

        /// 返回下一个分量(最近返回分量右侧的
        /// 分量);不存在时返回 null。
        /// 例如,路径为 `/a/b/c`,最近返回的分量
        /// 为 `b` 时,这里返回分量 `c`。
        pub fn next(self: *Self) ?Component {
            const peek_result = self.peekNext() orelse return null;
            self.start_index = peek_result.path.len - peek_result.name.len;
            self.end_index = peek_result.path.len;
            return peek_result;
        }

        /// 类似于 `next`,但不修改迭代器状态。
        pub fn peekNext(self: Self) ?Component {
            var start_index = self.end_index;
            while (start_index < self.path.len and path_type.isSep(T, self.path[start_index])) {
                start_index += 1;
            }
            var end_index = start_index;
            while (end_index < self.path.len and !path_type.isSep(T, self.path[end_index])) {
                end_index += 1;
            }
            if (start_index == end_index) return null;
            return .{
                .name = self.path[start_index..end_index],
                .path = self.path[0..end_index],
            };
        }

        /// 返回上一个分量(最近返回分量左侧的
        /// 分量);不存在时返回 null。
        /// 例如,路径为 `/a/b/c`,最近返回的分量
        /// 为 `b` 时,这里返回分量 `a`。
        pub fn previous(self: *Self) ?Component {
            const peek_result = self.peekPrevious() orelse return null;
            self.start_index = peek_result.path.len - peek_result.name.len;
            self.end_index = peek_result.path.len;
            return peek_result;
        }

        /// 类似于 `previous`,但不修改迭代器状态。
        pub fn peekPrevious(self: Self) ?Component {
            var end_index = self.start_index;
            while (true) {
                if (end_index == self.root_end_index) return null;
                if (!path_type.isSep(T, self.path[end_index - 1])) break;
                end_index -= 1;
            }
            var start_index = end_index;
            while (true) {
                if (start_index == self.root_end_index) break;
                if (path_type.isSep(T, self.path[start_index - 1])) break;
                start_index -= 1;
            }
            if (start_index == end_index) return null;
            return .{
                .name = self.path[start_index..end_index],
                .path = self.path[0..end_index],
            };
        }
    };
}

pub const NativeComponentIterator = ComponentIterator(switch (native_os) {
    .windows => .windows,
    .uefi => .uefi,
    else => .posix,
}, u8);

pub fn componentIterator(path: []const u8) NativeComponentIterator {
    return .init(path);
}

test "ComponentIterator posix" {
    const PosixComponentIterator = ComponentIterator(.posix, u8);
    {
        const path = "a/b/c/";
        var it: PosixComponentIterator = .init(path);
        try std.testing.expectEqual(0, it.root_len);
        try std.testing.expectEqual(0, it.root_end_index);
        try std.testing.expect(null == it.root());
        {
            try std.testing.expect(null == it.previous());

            const first_via_next = it.next().?;
            try std.testing.expectEqualStrings("a", first_via_next.name);
            try std.testing.expectEqualStrings("a", first_via_next.path);

            const first = it.first().?;
            try std.testing.expectEqualStrings("a", first.name);
            try std.testing.expectEqualStrings("a", first.path);

            try std.testing.expect(null == it.previous());

            const second = it.next().?;
            try std.testing.expectEqualStrings("b", second.name);
            try std.testing.expectEqualStrings("a/b", second.path);

            const third = it.next().?;
            try std.testing.expectEqualStrings("c", third.name);
            try std.testing.expectEqualStrings("a/b/c", third.path);

            try std.testing.expect(null == it.next());
        }
        {
            const last = it.last().?;
            try std.testing.expectEqualStrings("c", last.name);
            try std.testing.expectEqualStrings("a/b/c", last.path);

            try std.testing.expect(null == it.next());

            const second_to_last = it.previous().?;
            try std.testing.expectEqualStrings("b", second_to_last.name);
            try std.testing.expectEqualStrings("a/b", second_to_last.path);

            const third_to_last = it.previous().?;
            try std.testing.expectEqualStrings("a", third_to_last.name);
            try std.testing.expectEqualStrings("a", third_to_last.path);

            try std.testing.expect(null == it.previous());
        }
    }

    {
        const path = "/a/b/c/";
        var it: PosixComponentIterator = .init(path);
        try std.testing.expectEqual(1, it.root_len);
        try std.testing.expectEqual(1, it.root_end_index);
        try std.testing.expectEqualStrings("/", it.root().?);
        {
            try std.testing.expect(null == it.previous());

            const first_via_next = it.next().?;
            try std.testing.expectEqualStrings("a", first_via_next.name);
            try std.testing.expectEqualStrings("/a", first_via_next.path);

            const first = it.first().?;
            try std.testing.expectEqualStrings("a", first.name);
            try std.testing.expectEqualStrings("/a", first.path);

            try std.testing.expect(null == it.previous());

            const second = it.next().?;
            try std.testing.expectEqualStrings("b", second.name);
            try std.testing.expectEqualStrings("/a/b", second.path);

            const third = it.next().?;
            try std.testing.expectEqualStrings("c", third.name);
            try std.testing.expectEqualStrings("/a/b/c", third.path);

            try std.testing.expect(null == it.next());
        }
        {
            const last = it.last().?;
            try std.testing.expectEqualStrings("c", last.name);
            try std.testing.expectEqualStrings("/a/b/c", last.path);

            try std.testing.expect(null == it.next());

            const second_to_last = it.previous().?;
            try std.testing.expectEqualStrings("b", second_to_last.name);
            try std.testing.expectEqualStrings("/a/b", second_to_last.path);

            const third_to_last = it.previous().?;
            try std.testing.expectEqualStrings("a", third_to_last.name);
            try std.testing.expectEqualStrings("/a", third_to_last.path);

            try std.testing.expect(null == it.previous());
        }
    }

    {
        const path = "////a///b///c////";
        var it: PosixComponentIterator = .init(path);
        try std.testing.expectEqual(1, it.root_len);
        try std.testing.expectEqual(4, it.root_end_index);
        try std.testing.expectEqualStrings("/", it.root().?);
        {
            try std.testing.expect(null == it.previous());

            const first_via_next = it.next().?;
            try std.testing.expectEqualStrings("a", first_via_next.name);
            try std.testing.expectEqualStrings("////a", first_via_next.path);

            const first = it.first().?;
            try std.testing.expectEqualStrings("a", first.name);
            try std.testing.expectEqualStrings("////a", first.path);

            try std.testing.expect(null == it.previous());

            const second = it.next().?;
            try std.testing.expectEqualStrings("b", second.name);
            try std.testing.expectEqualStrings("////a///b", second.path);

            const third = it.next().?;
            try std.testing.expectEqualStrings("c", third.name);
            try std.testing.expectEqualStrings("////a///b///c", third.path);

            try std.testing.expect(null == it.next());
        }
        {
            const last = it.last().?;
            try std.testing.expectEqualStrings("c", last.name);
            try std.testing.expectEqualStrings("////a///b///c", last.path);

            try std.testing.expect(null == it.next());

            const second_to_last = it.previous().?;
            try std.testing.expectEqualStrings("b", second_to_last.name);
            try std.testing.expectEqualStrings("////a///b", second_to_last.path);

            const third_to_last = it.previous().?;
            try std.testing.expectEqualStrings("a", third_to_last.name);
            try std.testing.expectEqualStrings("////a", third_to_last.path);

            try std.testing.expect(null == it.previous());
        }
    }

    {
        const path = "/";
        var it: PosixComponentIterator = .init(path);
        try std.testing.expectEqual(1, it.root_len);
        try std.testing.expectEqual(1, it.root_end_index);
        try std.testing.expectEqualStrings("/", it.root().?);

        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.next());

        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.next());
    }

    {
        const path = "";
        var it: PosixComponentIterator = .init(path);
        try std.testing.expectEqual(0, it.root_len);
        try std.testing.expectEqual(0, it.root_end_index);
        try std.testing.expect(null == it.root());

        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.next());

        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.next());
    }
}

test "ComponentIterator windows" {
    const WindowsComponentIterator = ComponentIterator(.windows, u8);
    {
        const path = "a/b\\c//";
        var it: WindowsComponentIterator = .init(path);
        try std.testing.expectEqual(0, it.root_len);
        try std.testing.expectEqual(0, it.root_end_index);
        try std.testing.expect(null == it.root());
        {
            try std.testing.expect(null == it.previous());

            const first_via_next = it.next().?;
            try std.testing.expectEqualStrings("a", first_via_next.name);
            try std.testing.expectEqualStrings("a", first_via_next.path);

            const first = it.first().?;
            try std.testing.expectEqualStrings("a", first.name);
            try std.testing.expectEqualStrings("a", first.path);

            try std.testing.expect(null == it.previous());

            const second = it.next().?;
            try std.testing.expectEqualStrings("b", second.name);
            try std.testing.expectEqualStrings("a/b", second.path);

            const third = it.next().?;
            try std.testing.expectEqualStrings("c", third.name);
            try std.testing.expectEqualStrings("a/b\\c", third.path);

            try std.testing.expect(null == it.next());
        }
        {
            const last = it.last().?;
            try std.testing.expectEqualStrings("c", last.name);
            try std.testing.expectEqualStrings("a/b\\c", last.path);

            try std.testing.expect(null == it.next());

            const second_to_last = it.previous().?;
            try std.testing.expectEqualStrings("b", second_to_last.name);
            try std.testing.expectEqualStrings("a/b", second_to_last.path);

            const third_to_last = it.previous().?;
            try std.testing.expectEqualStrings("a", third_to_last.name);
            try std.testing.expectEqualStrings("a", third_to_last.path);

            try std.testing.expect(null == it.previous());
        }
    }

    {
        const path = "C:\\a/b/c/";
        var it: WindowsComponentIterator = .init(path);
        try std.testing.expectEqual(3, it.root_len);
        try std.testing.expectEqual(3, it.root_end_index);
        try std.testing.expectEqualStrings("C:\\", it.root().?);
        {
            const first = it.first().?;
            try std.testing.expectEqualStrings("a", first.name);
            try std.testing.expectEqualStrings("C:\\a", first.path);

            const second = it.next().?;
            try std.testing.expectEqualStrings("b", second.name);
            try std.testing.expectEqualStrings("C:\\a/b", second.path);

            const third = it.next().?;
            try std.testing.expectEqualStrings("c", third.name);
            try std.testing.expectEqualStrings("C:\\a/b/c", third.path);

            try std.testing.expect(null == it.next());
        }
        {
            const last = it.last().?;
            try std.testing.expectEqualStrings("c", last.name);
            try std.testing.expectEqualStrings("C:\\a/b/c", last.path);

            const second_to_last = it.previous().?;
            try std.testing.expectEqualStrings("b", second_to_last.name);
            try std.testing.expectEqualStrings("C:\\a/b", second_to_last.path);

            const third_to_last = it.previous().?;
            try std.testing.expectEqualStrings("a", third_to_last.name);
            try std.testing.expectEqualStrings("C:\\a", third_to_last.path);

            try std.testing.expect(null == it.previous());
        }
    }

    {
        const path = "C:\\\\//a/\\/\\b///c////";
        var it: WindowsComponentIterator = .init(path);
        try std.testing.expectEqual(3, it.root_len);
        try std.testing.expectEqual(6, it.root_end_index);
        try std.testing.expectEqualStrings("C:\\", it.root().?);
        {
            const first = it.first().?;
            try std.testing.expectEqualStrings("a", first.name);
            try std.testing.expectEqualStrings("C:\\\\//a", first.path);

            const second = it.next().?;
            try std.testing.expectEqualStrings("b", second.name);
            try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b", second.path);

            const third = it.next().?;
            try std.testing.expectEqualStrings("c", third.name);
            try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b///c", third.path);

            try std.testing.expect(null == it.next());
        }
        {
            const last = it.last().?;
            try std.testing.expectEqualStrings("c", last.name);
            try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b///c", last.path);

            const second_to_last = it.previous().?;
            try std.testing.expectEqualStrings("b", second_to_last.name);
            try std.testing.expectEqualStrings("C:\\\\//a/\\/\\b", second_to_last.path);

            const third_to_last = it.previous().?;
            try std.testing.expectEqualStrings("a", third_to_last.name);
            try std.testing.expectEqualStrings("C:\\\\//a", third_to_last.path);

            try std.testing.expect(null == it.previous());
        }
    }

    {
        const path = "/";
        var it: WindowsComponentIterator = .init(path);
        try std.testing.expectEqual(1, it.root_len);
        try std.testing.expectEqual(1, it.root_end_index);
        try std.testing.expectEqualStrings("/", it.root().?);

        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.next());

        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.next());
    }

    {
        const path = "";
        var it: WindowsComponentIterator = .init(path);
        try std.testing.expectEqual(0, it.root_len);
        try std.testing.expectEqual(0, it.root_end_index);
        try std.testing.expect(null == it.root());

        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.first());
        try std.testing.expect(null == it.next());

        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.previous());
        try std.testing.expect(null == it.last());
        try std.testing.expect(null == it.next());
    }
}

test "ComponentIterator windows WTF-16" {
    const WindowsComponentIterator = ComponentIterator(.windows, u16);
    const L = std.unicode.utf8ToUtf16LeStringLiteral;

    const path = L("C:\\a/b/c/");
    var it: WindowsComponentIterator = .init(path);
    try std.testing.expectEqual(3, it.root_len);
    try std.testing.expectEqual(3, it.root_end_index);
    try std.testing.expectEqualSlices(u16, L("C:\\"), it.root().?);
    {
        const first = it.first().?;
        try std.testing.expectEqualSlices(u16, L("a"), first.name);
        try std.testing.expectEqualSlices(u16, L("C:\\a"), first.path);

        const second = it.next().?;
        try std.testing.expectEqualSlices(u16, L("b"), second.name);
        try std.testing.expectEqualSlices(u16, L("C:\\a/b"), second.path);

        const third = it.next().?;
        try std.testing.expectEqualSlices(u16, L("c"), third.name);
        try std.testing.expectEqualSlices(u16, L("C:\\a/b/c"), third.path);

        try std.testing.expect(null == it.next());
    }
    {
        const last = it.last().?;
        try std.testing.expectEqualSlices(u16, L("c"), last.name);
        try std.testing.expectEqualSlices(u16, L("C:\\a/b/c"), last.path);

        const second_to_last = it.previous().?;
        try std.testing.expectEqualSlices(u16, L("b"), second_to_last.name);
        try std.testing.expectEqualSlices(u16, L("C:\\a/b"), second_to_last.path);

        const third_to_last = it.previous().?;
        try std.testing.expectEqualSlices(u16, L("a"), third_to_last.name);
        try std.testing.expectEqualSlices(u16, L("C:\\a"), third_to_last.path);

        try std.testing.expect(null == it.previous());
    }
}

test "ComponentIterator roots" {
    // UEFI
    {
        var it: ComponentIterator(.uefi, u8) = .init("\\\\a");
        try std.testing.expectEqualStrings("\\", it.root().?);

        it = .init("//a");
        try std.testing.expect(null == it.root());
    }
    // POSIX
    {
        var it: ComponentIterator(.posix, u8) = .init("//a");
        try std.testing.expectEqualStrings("/", it.root().?);

        it = .init("\\\\a");
        try std.testing.expect(null == it.root());
    }
    // Windows
    {
        // 驱动器相对路径
        var it: ComponentIterator(.windows, u8) = .init("C:a");
        try std.testing.expectEqualStrings("C:", it.root().?);

        // 驱动器绝对路径
        it = .init("C:/a");
        try std.testing.expectEqualStrings("C:/", it.root().?);
        it = .init("C:\\a");
        try std.testing.expectEqualStrings("C:\\", it.root().?);
        it = .init("C:///a");
        try std.testing.expectEqualStrings("C:/", it.root().?);

        // 有根路径
        it = .init("\\a");
        try std.testing.expectEqualStrings("\\", it.root().?);
        it = .init("/a");
        try std.testing.expectEqualStrings("/", it.root().?);

        // 根本地设备
        it = .init("\\\\.");
        try std.testing.expectEqualStrings("\\\\.", it.root().?);
        it = .init("//?");
        try std.testing.expectEqualStrings("//?", it.root().?);

        // UNC 绝对路径
        it = .init("//");
        try std.testing.expectEqualStrings("//", it.root().?);
        it = .init("\\\\a");
        try std.testing.expectEqualStrings("\\\\a", it.root().?);
        it = .init("\\\\a\\b\\\\c");
        try std.testing.expectEqualStrings("\\\\a\\b\\", it.root().?);
        it = .init("//a");
        try std.testing.expectEqualStrings("//a", it.root().?);
        it = .init("//a/b//c");
        try std.testing.expectEqualStrings("//a/b/", it.root().?);
        // UNC 路径格式错误,服务器名称为空
        it = .init("\\\\\\a\\b\\c");
        try std.testing.expectEqualStrings("\\\\\\a\\", it.root().?);
    }
}

/// 将字节编码的路径格式化为 UTF-8,以供显示。
/// 返回给定路径的 Formatter。格式化时将路径转换为有效 UTF-8;若路径包含任何结构不良的 UTF-8,则此转换有损。
/// 根据 Unicode 标准第 3 章“用 U+FFFD 替换最大子部分”及 https://encoding.spec.whatwg.org/#utf-8-decoder 的规定,将结构不良的 UTF-8 字节序列替换为替换字符 U+FFFD。
///
///
///
pub const fmtAsUtf8Lossy = std.unicode.fmtUtf8;

/// 格式化以 WTF-16 LE 编码的路径,供 UTF-8 显示使用。
/// 返回用于 UTF-16 LE 路径(可能格式不正确)的 Formatter。
/// 格式化期间会将路径转换为有效的 UTF-8。如果路径包含
/// 未配对代理码元,则此转换有损。
/// 未配对代理码元会替换为替换字符(U+FFFD)。
pub const fmtWtf16LeAsUtf8Lossy = std.unicode.fmtUtf16Le;

/// 类似 `RTL_PATH_TYPE`,但不包含 `UNKNOWN` 路径类型。
pub const Win32PathType = enum {
    /// `\\server\share\foo`
    unc_absolute,
    /// `C:\foo`
    drive_absolute,
    /// `C:foo`
    drive_relative,
    /// `\foo`
    rooted,
    /// `foo`
    relative,
    /// `\\.\foo`, `\\?\foo`
    local_device,
    /// `\\.`, `\\?`
    root_local_device,
};

/// 获取 Win32 命名空间路径的路径类型。
/// 类似 `RtlDetermineDosPathNameType_U`。
/// 若 `T` 为 `u16`,则 `path` 应采用 WTF-16LE 编码。
pub fn getWin32PathType(comptime T: type, path: []const T) Win32PathType {
    if (path.len < 1) return .relative;

    const windows_path = std.fs.path.PathType.windows;
    if (windows_path.isSep(T, path[0])) {
        // \x
        if (path.len < 2 or !windows_path.isSep(T, path[1])) return .rooted;
        // \\. 或 \\?
        if (path.len > 2 and (path[2] == mem.nativeToLittle(T, '.') or path[2] == mem.nativeToLittle(T, '?'))) {
            // 恰为 \\. 或 \\?,且无尾随内容
            if (path.len == 3) return .root_local_device;
            // \\.\x or \\?\x
            if (windows_path.isSep(T, path[3])) return .local_device;
        }
        // \\x
        return .unc_absolute;
    } else {
        // 必须决定如何处理作为盘符的非 ASCII 代码点,因为
        // WTF-16 与 WTF-8 中 path[0] 的大小不同,可能导致 WTF-8 路径
        // 与等价的 WTF-16 路径分类不一致。例如,`€:\` 的 WTF-16 编码为三个代码
        // 单元 `<0x20AC>:\`,而 `€:\` 的 WTF-8 编码为六个代码单元 `<0xE2><0x82><0xAC>:\`;
        // 因此,检查 path[0]、path[1] 和 path[2] 在两种编码下的行为不同。
        //
        // `RtlDetermineDosPathNameType_U` 只处理 WTF-16,
        // 会将 `€:\` 视为驱动器绝对路径,但占用两个 WTF-16 代码单元的代码点
        // 会被分类为相对路径;例如将 U+20000 用作盘符时,
        // 其 WTF-16 编码为 `<0xD840><0xDC00>:\`,被视为相对路径。
        //
        // 这里选择同时对 WTF-16 和 WTF-8 模拟 `RtlDetermineDosPathNameType_U` 的行为。
        // 原因在于,尽管不常见且磁盘管理器的图形界面不支持,
        // 盘符实际上并不局限于 A-Z。使用 `SetVolumeMountPointW` 可以
        // 将任意字节值设为盘符;通过 `IOCTL_MOUNTMGR_CREATE_POINT` 则
        // 可以将任意 WTF-16 代码单元设为盘符。
        //
        // 非 A-Z 盘符与 Windows 的多数功能不能良好协作,但部分功能仍然有效,例如
        // `cd /D €:\` 可以正常工作,文件系统函数也仍然可用。
        //
        // 遗憾的是,这使 WTF-8 的处理更加复杂,因为不能
        // 仅检查 path[0]、path[1] 和 path[2]。
        const colon_i: usize = switch (T) {
            u8 => i: {
                const code_point_len = std.unicode.utf8ByteSequenceLength(path[0]) catch return .relative;
                // WTF-8 的 4 字节序列与 WTF-16 的
                // 双码元序列具有相同的起始码点,便于处理。
                if (code_point_len > 3) return .relative;
                break :i code_point_len;
            },
            u16 => 1,
            else => @compileError("unsupported type: " ++ @typeName(T)),
        };
        // x
        if (path.len < colon_i + 1 or path[colon_i] != mem.nativeToLittle(T, ':')) return .relative;
        // x:\
        if (path.len > colon_i + 1 and windows_path.isSep(T, path[colon_i + 1])) return .drive_absolute;
        // x:
        return .drive_relative;
    }
}

test getWin32PathType {
    try std.testing.expectEqual(.relative, getWin32PathType(u8, ""));
    try std.testing.expectEqual(.relative, getWin32PathType(u8, "x"));
    try std.testing.expectEqual(.relative, getWin32PathType(u8, "x\\"));

    try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "//."));
    try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "/\\?"));
    try std.testing.expectEqual(.root_local_device, getWin32PathType(u8, "\\\\?"));

    try std.testing.expectEqual(.local_device, getWin32PathType(u8, "//./x"));
    try std.testing.expectEqual(.local_device, getWin32PathType(u8, "/\\?\\x"));
    try std.testing.expectEqual(.local_device, getWin32PathType(u8, "\\\\?\\x"));
    // 本地设备路径的根之后必须有路径分隔符,否则会被视为 UNC 路径。
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "\\\\?x"));
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//.x"));

    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//"));
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "\\\\x"));
    try std.testing.expectEqual(.unc_absolute, getWin32PathType(u8, "//x"));

    try std.testing.expectEqual(.rooted, getWin32PathType(u8, "\\x"));
    try std.testing.expectEqual(.rooted, getWin32PathType(u8, "/"));

    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:"));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:abc"));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "x:a/b/c"));

    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:\\"));
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:\\abc"));
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "x:/a/b/c"));

    // 编码为单个 WTF-16 代码单元的非 ASCII 码点被视为有效驱动器盘符。
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u8, "€:\\"));
    try std.testing.expectEqual(.drive_absolute, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("€:\\")));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u8, "€:"));
    try std.testing.expectEqual(.drive_relative, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("€:")));
    // 但编码为两个 WTF-16 代码单元的码点不在此列
    try std.testing.expectEqual(.relative, getWin32PathType(u8, "\u{10000}:\\"));
    try std.testing.expectEqual(.relative, getWin32PathType(u16, std.unicode.wtf8ToWtf16LeStringLiteral("\u{10000}:\\")));
}