std: Convert deprecated aliases to compile errors and fix usages

Deprecated aliases that are now compile errors:

- `std.fs.MAX_PATH_BYTES` (renamed to `std.fs.max_path_bytes`)
- `std.mem.tokenize` (split into `tokenizeAny`, `tokenizeSequence`, `tokenizeScalar`)
- `std.mem.split` (split into `splitSequence`, `splitAny`, `splitScalar`)
- `std.mem.splitBackwards` (split into `splitBackwardsSequence`, `splitBackwardsAny`, `splitBackwardsScalar`)
- `std.unicode`
  + `utf16leToUtf8Alloc`, `utf16leToUtf8AllocZ`, `utf16leToUtf8`, `fmtUtf16le` (all renamed to have capitalized `Le`)
  + `utf8ToUtf16LeWithNull` (renamed to `utf8ToUtf16LeAllocZ`)
- `std.zig.CrossTarget` (moved to `std.Target.Query`)

Deprecated `lib/std/std.zig` decls were deleted instead of made a `@compileError` because the `refAllDecls` in the test block would trigger the `@compileError`. The deleted top-level `std` namespaces are:

- `std.rand` (renamed to `std.Random`)
- `std.TailQueue` (renamed to `std.DoublyLinkedList`)
- `std.ChildProcess` (renamed/moved to `std.process.Child`)

This is not exhaustive. Deprecated aliases that I didn't touch:
  + `std.io.*`
  + `std.Build.*`
  + `std.builtin.Mode`
  + `std.zig.c_translation.CIntLiteralRadix`
  + anything in `src/`
This commit is contained in:
Ryan Liptak 2024-05-02 20:20:41 -07:00 committed by Andrew Kelley
parent 4aa15440c7
commit 76fb2b685b
47 changed files with 136 additions and 150 deletions

View File

@ -15,7 +15,7 @@ const stack_size = 32 * 1024 * 1024;
pub fn build(b: *std.Build) !void { pub fn build(b: *std.Build) !void {
const only_c = b.option(bool, "only-c", "Translate the Zig compiler to C code, with only the C backend enabled") orelse false; const only_c = b.option(bool, "only-c", "Translate the Zig compiler to C code, with only the C backend enabled") orelse false;
const target = t: { const target = t: {
var default_target: std.zig.CrossTarget = .{}; var default_target: std.Target.Query = .{};
default_target.ofmt = b.option(std.Target.ObjectFormat, "ofmt", "Object format to target") orelse if (only_c) .c else null; default_target.ofmt = b.option(std.Target.ObjectFormat, "ofmt", "Object format to target") orelse if (only_c) .c else null;
break :t b.standardTargetOptions(.{ .default_target = default_target }); break :t b.standardTargetOptions(.{ .default_target = default_target });
}; };
@ -559,7 +559,7 @@ pub fn build(b: *std.Build) !void {
fn addWasiUpdateStep(b: *std.Build, version: [:0]const u8) !void { fn addWasiUpdateStep(b: *std.Build, version: [:0]const u8) !void {
const semver = try std.SemanticVersion.parse(version); const semver = try std.SemanticVersion.parse(version);
var target_query: std.zig.CrossTarget = .{ var target_query: std.Target.Query = .{
.cpu_arch = .wasm32, .cpu_arch = .wasm32,
.os_tag = .wasi, .os_tag = .wasi,
}; };

View File

@ -792,7 +792,7 @@ pub fn invokeLinker(d: *Driver, tc: *Toolchain, comptime fast_exit: bool) !void
var argv = std.ArrayList([]const u8).init(d.comp.gpa); var argv = std.ArrayList([]const u8).init(d.comp.gpa);
defer argv.deinit(); defer argv.deinit();
var linker_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var linker_path_buf: [std.fs.max_path_bytes]u8 = undefined;
const linker_path = try tc.getLinkerPath(&linker_path_buf); const linker_path = try tc.getLinkerPath(&linker_path_buf);
try argv.append(linker_path); try argv.append(linker_path);

View File

@ -46,7 +46,7 @@ fn canExecuteFake(entries: []const Filesystem.Entry, path: []const u8) bool {
fn existsFake(entries: []const Filesystem.Entry, path: []const u8) bool { fn existsFake(entries: []const Filesystem.Entry, path: []const u8) bool {
@setCold(true); @setCold(true);
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&buf); var fib = std.heap.FixedBufferAllocator.init(&buf);
const resolved = std.fs.path.resolvePosix(fib.allocator(), &.{path}) catch return false; const resolved = std.fs.path.resolvePosix(fib.allocator(), &.{path}) catch return false;
for (entries) |entry| { for (entries) |entry| {
@ -181,7 +181,7 @@ pub const Filesystem = union(enum) {
} }
pub fn joinedExists(fs: Filesystem, parts: []const []const u8) bool { pub fn joinedExists(fs: Filesystem, parts: []const []const u8) bool {
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&buf); var fib = std.heap.FixedBufferAllocator.init(&buf);
const joined = std.fs.path.join(fib.allocator(), parts) catch return false; const joined = std.fs.path.join(fib.allocator(), parts) catch return false;
return fs.exists(joined); return fs.exists(joined);

View File

@ -397,7 +397,7 @@ fn collectLibDirsAndTriples(
} }
pub fn discover(self: *GCCDetector, tc: *Toolchain) !void { pub fn discover(self: *GCCDetector, tc: *Toolchain) !void {
var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var path_buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&path_buf); var fib = std.heap.FixedBufferAllocator.init(&path_buf);
const target = tc.getTarget(); const target = tc.getTarget();
@ -589,7 +589,7 @@ fn scanLibDirForGCCTriple(
gcc_dir_exists: bool, gcc_dir_exists: bool,
gcc_cross_dir_exists: bool, gcc_cross_dir_exists: bool,
) !void { ) !void {
var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var path_buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&path_buf); var fib = std.heap.FixedBufferAllocator.init(&path_buf);
for (0..2) |i| { for (0..2) |i| {
if (i == 0 and !gcc_dir_exists) continue; if (i == 0 and !gcc_dir_exists) continue;

View File

@ -221,7 +221,7 @@ pub fn addFilePathLibArgs(tc: *const Toolchain, argv: *std.ArrayList([]const u8)
/// If not found there, just use `name` /// If not found there, just use `name`
/// Writes the result to `buf` and returns a slice of it /// Writes the result to `buf` and returns a slice of it
fn getProgramPath(tc: *const Toolchain, name: []const u8, buf: []u8) []const u8 { fn getProgramPath(tc: *const Toolchain, name: []const u8, buf: []u8) []const u8 {
var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var path_buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&path_buf); var fib = std.heap.FixedBufferAllocator.init(&path_buf);
var tool_specific_buf: [64]u8 = undefined; var tool_specific_buf: [64]u8 = undefined;
@ -251,7 +251,7 @@ pub fn getSysroot(tc: *const Toolchain) []const u8 {
/// Search for `name` in a variety of places /// Search for `name` in a variety of places
/// TODO: cache results based on `name` so we're not repeatedly allocating the same strings? /// TODO: cache results based on `name` so we're not repeatedly allocating the same strings?
pub fn getFilePath(tc: *const Toolchain, name: []const u8) ![]const u8 { pub fn getFilePath(tc: *const Toolchain, name: []const u8) ![]const u8 {
var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var path_buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&path_buf); var fib = std.heap.FixedBufferAllocator.init(&path_buf);
const allocator = fib.allocator(); const allocator = fib.allocator();
@ -304,7 +304,7 @@ const PathKind = enum {
/// Join `components` into a path. If the path exists, dupe it into the toolchain arena and /// Join `components` into a path. If the path exists, dupe it into the toolchain arena and
/// add it to the specified path list. /// add it to the specified path list.
pub fn addPathIfExists(tc: *Toolchain, components: []const []const u8, dest_kind: PathKind) !void { pub fn addPathIfExists(tc: *Toolchain, components: []const []const u8, dest_kind: PathKind) !void {
var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var path_buf: [std.fs.max_path_bytes]u8 = undefined;
var fib = std.heap.FixedBufferAllocator.init(&path_buf); var fib = std.heap.FixedBufferAllocator.init(&path_buf);
const candidate = try std.fs.path.join(fib.allocator(), components); const candidate = try std.fs.path.join(fib.allocator(), components);

View File

@ -706,7 +706,7 @@ pub fn printString(bytes: []const u8, ty: Type, comp: *const Compilation, w: any
switch (size) { switch (size) {
inline .@"1", .@"2" => |sz| { inline .@"1", .@"2" => |sz| {
const data_slice: []const sz.Type() = @alignCast(std.mem.bytesAsSlice(sz.Type(), without_null)); const data_slice: []const sz.Type() = @alignCast(std.mem.bytesAsSlice(sz.Type(), without_null));
const formatter = if (sz == .@"1") std.zig.fmtEscapes(data_slice) else std.unicode.fmtUtf16le(data_slice); const formatter = if (sz == .@"1") std.zig.fmtEscapes(data_slice) else std.unicode.fmtUtf16Le(data_slice);
try w.print("\"{}\"", .{formatter}); try w.print("\"{}\"", .{formatter});
}, },
.@"4" => { .@"4" => {

View File

@ -478,7 +478,7 @@ test Linux {
var argv = std.ArrayList([]const u8).init(driver.comp.gpa); var argv = std.ArrayList([]const u8).init(driver.comp.gpa);
defer argv.deinit(); defer argv.deinit();
var linker_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var linker_path_buf: [std.fs.max_path_bytes]u8 = undefined;
const linker_path = try toolchain.getLinkerPath(&linker_path_buf); const linker_path = try toolchain.getLinkerPath(&linker_path_buf);
try argv.append(linker_path); try argv.append(linker_path);

View File

@ -846,7 +846,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn
arg_i += 1; arg_i += 1;
break :next_arg; break :next_arg;
}; };
var tokenizer = std.mem.tokenize(u8, value.slice, "="); var tokenizer = std.mem.tokenizeScalar(u8, value.slice, '=');
// guaranteed to exist since an empty value.slice would invoke // guaranteed to exist since an empty value.slice would invoke
// the 'missing symbol to define' branch above // the 'missing symbol to define' branch above
const symbol = tokenizer.next().?; const symbol = tokenizer.next().?;

View File

@ -3405,7 +3405,7 @@ test "StringTable" {
} }
break :ids buf; break :ids buf;
}; };
var prng = std.rand.DefaultPrng.init(0); var prng = std.Random.DefaultPrng.init(0);
var random = prng.random(); var random = prng.random();
random.shuffle(u16, &ids); random.shuffle(u16, &ids);

View File

@ -214,7 +214,7 @@ pub fn handleLineEnd(allocator: Allocator, post_processed_line_number: usize, ma
// TODO: Might want to provide diagnostics on invalid line commands instead of just returning // TODO: Might want to provide diagnostics on invalid line commands instead of just returning
pub fn handleLineCommand(allocator: Allocator, line_command: []const u8, current_mapping: *CurrentMapping) error{OutOfMemory}!void { pub fn handleLineCommand(allocator: Allocator, line_command: []const u8, current_mapping: *CurrentMapping) error{OutOfMemory}!void {
// TODO: Are there other whitespace characters that should be included? // TODO: Are there other whitespace characters that should be included?
var tokenizer = std.mem.tokenize(u8, line_command, " \t"); var tokenizer = std.mem.tokenizeAny(u8, line_command, " \t");
const line_directive = tokenizer.next() orelse return; // #line const line_directive = tokenizer.next() orelse return; // #line
if (!std.mem.eql(u8, line_directive, "#line")) return; if (!std.mem.eql(u8, line_directive, "#line")) return;
const linenum_str = tokenizer.next() orelse return; const linenum_str = tokenizer.next() orelse return;

View File

@ -1212,7 +1212,7 @@ fn unindent(s: []const u8, indent: usize) []const u8 {
} }
fn appendUnindented(out: *std.ArrayListUnmanaged(u8), s: []const u8, indent: usize) !void { fn appendUnindented(out: *std.ArrayListUnmanaged(u8), s: []const u8, indent: usize) !void {
var it = std.mem.split(u8, s, "\n"); var it = std.mem.splitScalar(u8, s, '\n');
var is_first_line = true; var is_first_line = true;
while (it.next()) |line| { while (it.next()) |line| {
if (is_first_line) { if (is_first_line) {

View File

@ -1112,7 +1112,7 @@ fn testRender(input: []const u8, expected: []const u8) !void {
var parser = try Parser.init(testing.allocator); var parser = try Parser.init(testing.allocator);
defer parser.deinit(); defer parser.deinit();
var lines = std.mem.split(u8, input, "\n"); var lines = std.mem.splitScalar(u8, input, '\n');
while (lines.next()) |line| { while (lines.next()) |line| {
try parser.feedLine(line); try parser.feedLine(line);
} }

View File

@ -49,7 +49,7 @@ pub fn openFile(
sub_path: []const u8, sub_path: []const u8,
flags: fs.File.OpenFlags, flags: fs.File.OpenFlags,
) !fs.File { ) !fs.File {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const joined_path = if (p.sub_path.len == 0) sub_path else p: { const joined_path = if (p.sub_path.len == 0) sub_path else p: {
break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{ break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{
p.sub_path, sub_path, p.sub_path, sub_path,
@ -59,7 +59,7 @@ pub fn openFile(
} }
pub fn makeOpenPath(p: Path, sub_path: []const u8, opts: fs.OpenDirOptions) !fs.Dir { pub fn makeOpenPath(p: Path, sub_path: []const u8, opts: fs.OpenDirOptions) !fs.Dir {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const joined_path = if (p.sub_path.len == 0) sub_path else p: { const joined_path = if (p.sub_path.len == 0) sub_path else p: {
break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{ break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{
p.sub_path, sub_path, p.sub_path, sub_path,
@ -69,7 +69,7 @@ pub fn makeOpenPath(p: Path, sub_path: []const u8, opts: fs.OpenDirOptions) !fs.
} }
pub fn statFile(p: Path, sub_path: []const u8) !fs.Dir.Stat { pub fn statFile(p: Path, sub_path: []const u8) !fs.Dir.Stat {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const joined_path = if (p.sub_path.len == 0) sub_path else p: { const joined_path = if (p.sub_path.len == 0) sub_path else p: {
break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{ break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{
p.sub_path, sub_path, p.sub_path, sub_path,
@ -82,7 +82,7 @@ pub fn atomicFile(
p: Path, p: Path,
sub_path: []const u8, sub_path: []const u8,
options: fs.Dir.AtomicFileOptions, options: fs.Dir.AtomicFileOptions,
buf: *[fs.MAX_PATH_BYTES]u8, buf: *[fs.max_path_bytes]u8,
) !fs.AtomicFile { ) !fs.AtomicFile {
const joined_path = if (p.sub_path.len == 0) sub_path else p: { const joined_path = if (p.sub_path.len == 0) sub_path else p: {
break :p std.fmt.bufPrint(buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{ break :p std.fmt.bufPrint(buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{
@ -93,7 +93,7 @@ pub fn atomicFile(
} }
pub fn access(p: Path, sub_path: []const u8, flags: fs.File.OpenFlags) !void { pub fn access(p: Path, sub_path: []const u8, flags: fs.File.OpenFlags) !void {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const joined_path = if (p.sub_path.len == 0) sub_path else p: { const joined_path = if (p.sub_path.len == 0) sub_path else p: {
break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{ break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{
p.sub_path, sub_path, p.sub_path, sub_path,
@ -103,7 +103,7 @@ pub fn access(p: Path, sub_path: []const u8, flags: fs.File.OpenFlags) !void {
} }
pub fn makePath(p: Path, sub_path: []const u8) !void { pub fn makePath(p: Path, sub_path: []const u8) !void {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const joined_path = if (p.sub_path.len == 0) sub_path else p: { const joined_path = if (p.sub_path.len == 0) sub_path else p: {
break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{ break :p std.fmt.bufPrint(&buf, "{s}" ++ fs.path.sep_str ++ "{s}", .{
p.sub_path, sub_path, p.sub_path, sub_path,

View File

@ -9,7 +9,7 @@ const math = std.math;
const mem = std.mem; const mem = std.mem;
const assert = std.debug.assert; const assert = std.debug.assert;
const maxInt = std.math.maxInt; const maxInt = std.math.maxInt;
pub const Random = @This(); // Remove pub when `std.rand` namespace is removed. const Random = @This();
/// Fast unbiased random numbers. /// Fast unbiased random numbers.
pub const DefaultPrng = Xoshiro256; pub const DefaultPrng = Xoshiro256;

View File

@ -1298,7 +1298,7 @@ pub fn readElfDebugInfo(
if (readElfDebugInfo(allocator, path, null, separate_debug_crc, &sections, mapped_mem)) |debug_info| return debug_info else |_| {} if (readElfDebugInfo(allocator, path, null, separate_debug_crc, &sections, mapped_mem)) |debug_info| return debug_info else |_| {}
} }
var cwd_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var cwd_buf: [fs.max_path_bytes]u8 = undefined;
const cwd_path = posix.realpath(".", &cwd_buf) catch break :blk; const cwd_path = posix.realpath(".", &cwd_buf) catch break :blk;
// <global debug directory>/<absolute folder of current binary>/<gnu_debuglink> // <global debug directory>/<absolute folder of current binary>/<gnu_debuglink>

View File

@ -35,8 +35,7 @@ pub const realpathW = posix.realpathW;
pub const getAppDataDir = @import("fs/get_app_data_dir.zig").getAppDataDir; pub const getAppDataDir = @import("fs/get_app_data_dir.zig").getAppDataDir;
pub const GetAppDataDirError = @import("fs/get_app_data_dir.zig").GetAppDataDirError; pub const GetAppDataDirError = @import("fs/get_app_data_dir.zig").GetAppDataDirError;
/// Deprecated: use `max_path_bytes`. pub const MAX_PATH_BYTES = @compileError("deprecated; renamed to max_path_bytes");
pub const MAX_PATH_BYTES = max_path_bytes;
/// The maximum length of a file path that the operating system will accept. /// The maximum length of a file path that the operating system will accept.
/// ///
@ -417,20 +416,20 @@ pub fn deleteTreeAbsolute(absolute_path: []const u8) !void {
/// On Windows, `pathname` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/). /// On Windows, `pathname` should be encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
/// On WASI, `pathname` should be encoded as valid UTF-8. /// On WASI, `pathname` should be encoded as valid UTF-8.
/// On other platforms, `pathname` is an opaque sequence of bytes with no particular encoding. /// On other platforms, `pathname` is an opaque sequence of bytes with no particular encoding.
pub fn readLinkAbsolute(pathname: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { pub fn readLinkAbsolute(pathname: []const u8, buffer: *[max_path_bytes]u8) ![]u8 {
assert(path.isAbsolute(pathname)); assert(path.isAbsolute(pathname));
return posix.readlink(pathname, buffer); return posix.readlink(pathname, buffer);
} }
/// Windows-only. Same as `readlinkW`, except the path parameter is null-terminated, WTF16 /// Windows-only. Same as `readlinkW`, except the path parameter is null-terminated, WTF16
/// encoded. /// encoded.
pub fn readlinkAbsoluteW(pathname_w: [*:0]const u16, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { pub fn readlinkAbsoluteW(pathname_w: [*:0]const u16, buffer: *[max_path_bytes]u8) ![]u8 {
assert(path.isAbsoluteWindowsW(pathname_w)); assert(path.isAbsoluteWindowsW(pathname_w));
return posix.readlinkW(pathname_w, buffer); return posix.readlinkW(pathname_w, buffer);
} }
/// Same as `readLink`, except the path parameter is null-terminated. /// Same as `readLink`, except the path parameter is null-terminated.
pub fn readLinkAbsoluteZ(pathname_c: [*:0]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { pub fn readLinkAbsoluteZ(pathname_c: [*:0]const u8, buffer: *[max_path_bytes]u8) ![]u8 {
assert(path.isAbsoluteZ(pathname_c)); assert(path.isAbsoluteZ(pathname_c));
return posix.readlinkZ(pathname_c, buffer); return posix.readlinkZ(pathname_c, buffer);
} }
@ -504,9 +503,9 @@ pub fn openSelfExe(flags: File.OpenFlags) OpenSelfExeError!File {
const prefixed_path_w = try windows.wToPrefixedFileW(null, image_path_name); const prefixed_path_w = try windows.wToPrefixedFileW(null, image_path_name);
return cwd().openFileW(prefixed_path_w.span(), flags); return cwd().openFileW(prefixed_path_w.span(), flags);
} }
// Use of MAX_PATH_BYTES here is valid as the resulting path is immediately // Use of max_path_bytes here is valid as the resulting path is immediately
// opened with no modification. // opened with no modification.
var buf: [MAX_PATH_BYTES]u8 = undefined; var buf: [max_path_bytes]u8 = undefined;
const self_exe_path = try selfExePath(&buf); const self_exe_path = try selfExePath(&buf);
buf[self_exe_path.len] = 0; buf[self_exe_path.len] = 0;
return openFileAbsoluteZ(buf[0..self_exe_path.len :0].ptr, flags); return openFileAbsoluteZ(buf[0..self_exe_path.len :0].ptr, flags);
@ -554,14 +553,14 @@ pub const SelfExePathError = error{
/// `selfExePath` except allocates the result on the heap. /// `selfExePath` except allocates the result on the heap.
/// Caller owns returned memory. /// Caller owns returned memory.
pub fn selfExePathAlloc(allocator: Allocator) ![]u8 { pub fn selfExePathAlloc(allocator: Allocator) ![]u8 {
// Use of MAX_PATH_BYTES here is justified as, at least on one tested Linux // Use of max_path_bytes here is justified as, at least on one tested Linux
// system, readlink will completely fail to return a result larger than // system, readlink will completely fail to return a result larger than
// PATH_MAX even if given a sufficiently large buffer. This makes it // PATH_MAX even if given a sufficiently large buffer. This makes it
// fundamentally impossible to get the selfExePath of a program running in // fundamentally impossible to get the selfExePath of a program running in
// a very deeply nested directory chain in this way. // a very deeply nested directory chain in this way.
// TODO(#4812): Investigate other systems and whether it is possible to get // TODO(#4812): Investigate other systems and whether it is possible to get
// this path by trying larger and larger buffers until one succeeds. // this path by trying larger and larger buffers until one succeeds.
var buf: [MAX_PATH_BYTES]u8 = undefined; var buf: [max_path_bytes]u8 = undefined;
return allocator.dupe(u8, try selfExePath(&buf)); return allocator.dupe(u8, try selfExePath(&buf));
} }
@ -581,12 +580,12 @@ pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8 {
if (is_darwin) { if (is_darwin) {
// Note that _NSGetExecutablePath() will return "a path" to // Note that _NSGetExecutablePath() will return "a path" to
// the executable not a "real path" to the executable. // the executable not a "real path" to the executable.
var symlink_path_buf: [MAX_PATH_BYTES:0]u8 = undefined; var symlink_path_buf: [max_path_bytes:0]u8 = undefined;
var u32_len: u32 = MAX_PATH_BYTES + 1; // include the sentinel var u32_len: u32 = max_path_bytes + 1; // include the sentinel
const rc = std.c._NSGetExecutablePath(&symlink_path_buf, &u32_len); const rc = std.c._NSGetExecutablePath(&symlink_path_buf, &u32_len);
if (rc != 0) return error.NameTooLong; if (rc != 0) return error.NameTooLong;
var real_path_buf: [MAX_PATH_BYTES]u8 = undefined; var real_path_buf: [max_path_bytes]u8 = undefined;
const real_path = std.posix.realpathZ(&symlink_path_buf, &real_path_buf) catch |err| switch (err) { const real_path = std.posix.realpathZ(&symlink_path_buf, &real_path_buf) catch |err| switch (err) {
error.InvalidWtf8 => unreachable, // Windows-only error.InvalidWtf8 => unreachable, // Windows-only
error.NetworkNotFound => unreachable, // Windows-only error.NetworkNotFound => unreachable, // Windows-only
@ -634,7 +633,7 @@ pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8 {
const argv0 = mem.span(std.os.argv[0]); const argv0 = mem.span(std.os.argv[0]);
if (mem.indexOf(u8, argv0, "/") != null) { if (mem.indexOf(u8, argv0, "/") != null) {
// argv[0] is a path (relative or absolute): use realpath(3) directly // argv[0] is a path (relative or absolute): use realpath(3) directly
var real_path_buf: [MAX_PATH_BYTES]u8 = undefined; var real_path_buf: [max_path_bytes]u8 = undefined;
const real_path = posix.realpathZ(std.os.argv[0], &real_path_buf) catch |err| switch (err) { const real_path = posix.realpathZ(std.os.argv[0], &real_path_buf) catch |err| switch (err) {
error.InvalidWtf8 => unreachable, // Windows-only error.InvalidWtf8 => unreachable, // Windows-only
error.NetworkNotFound => unreachable, // Windows-only error.NetworkNotFound => unreachable, // Windows-only
@ -650,13 +649,13 @@ pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8 {
const PATH = posix.getenvZ("PATH") orelse return error.FileNotFound; const PATH = posix.getenvZ("PATH") orelse return error.FileNotFound;
var path_it = mem.tokenizeScalar(u8, PATH, path.delimiter); var path_it = mem.tokenizeScalar(u8, PATH, path.delimiter);
while (path_it.next()) |a_path| { while (path_it.next()) |a_path| {
var resolved_path_buf: [MAX_PATH_BYTES - 1:0]u8 = undefined; var resolved_path_buf: [max_path_bytes - 1:0]u8 = undefined;
const resolved_path = std.fmt.bufPrintZ(&resolved_path_buf, "{s}/{s}", .{ const resolved_path = std.fmt.bufPrintZ(&resolved_path_buf, "{s}/{s}", .{
a_path, a_path,
std.os.argv[0], std.os.argv[0],
}) catch continue; }) catch continue;
var real_path_buf: [MAX_PATH_BYTES]u8 = undefined; var real_path_buf: [max_path_bytes]u8 = undefined;
if (posix.realpathZ(resolved_path, &real_path_buf)) |real_path| { if (posix.realpathZ(resolved_path, &real_path_buf)) |real_path| {
// found a file, and hope it is the right file // found a file, and hope it is the right file
if (real_path.len > out_buffer.len) if (real_path.len > out_buffer.len)
@ -689,14 +688,14 @@ pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8 {
/// `selfExeDirPath` except allocates the result on the heap. /// `selfExeDirPath` except allocates the result on the heap.
/// Caller owns returned memory. /// Caller owns returned memory.
pub fn selfExeDirPathAlloc(allocator: Allocator) ![]u8 { pub fn selfExeDirPathAlloc(allocator: Allocator) ![]u8 {
// Use of MAX_PATH_BYTES here is justified as, at least on one tested Linux // Use of max_path_bytes here is justified as, at least on one tested Linux
// system, readlink will completely fail to return a result larger than // system, readlink will completely fail to return a result larger than
// PATH_MAX even if given a sufficiently large buffer. This makes it // PATH_MAX even if given a sufficiently large buffer. This makes it
// fundamentally impossible to get the selfExeDirPath of a program running // fundamentally impossible to get the selfExeDirPath of a program running
// in a very deeply nested directory chain in this way. // in a very deeply nested directory chain in this way.
// TODO(#4812): Investigate other systems and whether it is possible to get // TODO(#4812): Investigate other systems and whether it is possible to get
// this path by trying larger and larger buffers until one succeeds. // this path by trying larger and larger buffers until one succeeds.
var buf: [MAX_PATH_BYTES]u8 = undefined; var buf: [max_path_bytes]u8 = undefined;
return allocator.dupe(u8, try selfExeDirPath(&buf)); return allocator.dupe(u8, try selfExeDirPath(&buf));
} }
@ -716,13 +715,13 @@ pub fn selfExeDirPath(out_buffer: []u8) SelfExePathError![]const u8 {
/// On other platforms, the result is an opaque sequence of bytes with no particular encoding. /// On other platforms, the result is an opaque sequence of bytes with no particular encoding.
/// See also `Dir.realpath`. /// See also `Dir.realpath`.
pub fn realpathAlloc(allocator: Allocator, pathname: []const u8) ![]u8 { pub fn realpathAlloc(allocator: Allocator, pathname: []const u8) ![]u8 {
// Use of MAX_PATH_BYTES here is valid as the realpath function does not // Use of max_path_bytes here is valid as the realpath function does not
// have a variant that takes an arbitrary-size buffer. // have a variant that takes an arbitrary-size buffer.
// TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008 // TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008
// NULL out parameter (GNU's canonicalize_file_name) to handle overelong // NULL out parameter (GNU's canonicalize_file_name) to handle overelong
// paths. musl supports passing NULL but restricts the output to PATH_MAX // paths. musl supports passing NULL but restricts the output to PATH_MAX
// anyway. // anyway.
var buf: [MAX_PATH_BYTES]u8 = undefined; var buf: [max_path_bytes]u8 = undefined;
return allocator.dupe(u8, try posix.realpath(pathname, &buf)); return allocator.dupe(u8, try posix.realpath(pathname, &buf));
} }

View File

@ -1309,7 +1309,7 @@ pub fn realpathZ(self: Dir, pathname: [*:0]const u8, out_buffer: []u8) RealPathE
}; };
defer posix.close(fd); defer posix.close(fd);
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const out_path = try std.os.getFdPath(fd, &buffer); const out_path = try std.os.getFdPath(fd, &buffer);
if (out_path.len > out_buffer.len) { if (out_path.len > out_buffer.len) {
@ -1347,7 +1347,7 @@ pub fn realpathW(self: Dir, pathname: []const u16, out_buffer: []u8) RealPathErr
var wide_buf: [w.PATH_MAX_WIDE]u16 = undefined; var wide_buf: [w.PATH_MAX_WIDE]u16 = undefined;
const wide_slice = try w.GetFinalPathNameByHandle(h_file, .{}, &wide_buf); const wide_slice = try w.GetFinalPathNameByHandle(h_file, .{}, &wide_buf);
var big_out_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var big_out_buf: [fs.max_path_bytes]u8 = undefined;
const end_index = std.unicode.wtf16LeToWtf8(&big_out_buf, wide_slice); const end_index = std.unicode.wtf16LeToWtf8(&big_out_buf, wide_slice);
if (end_index > out_buffer.len) if (end_index > out_buffer.len)
return error.NameTooLong; return error.NameTooLong;
@ -1361,13 +1361,13 @@ pub const RealPathAllocError = RealPathError || Allocator.Error;
/// Same as `Dir.realpath` except caller must free the returned memory. /// Same as `Dir.realpath` except caller must free the returned memory.
/// See also `Dir.realpath`. /// See also `Dir.realpath`.
pub fn realpathAlloc(self: Dir, allocator: Allocator, pathname: []const u8) RealPathAllocError![]u8 { pub fn realpathAlloc(self: Dir, allocator: Allocator, pathname: []const u8) RealPathAllocError![]u8 {
// Use of MAX_PATH_BYTES here is valid as the realpath function does not // Use of max_path_bytes here is valid as the realpath function does not
// have a variant that takes an arbitrary-size buffer. // have a variant that takes an arbitrary-size buffer.
// TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008 // TODO(#4812): Consider reimplementing realpath or using the POSIX.1-2008
// NULL out parameter (GNU's canonicalize_file_name) to handle overelong // NULL out parameter (GNU's canonicalize_file_name) to handle overelong
// paths. musl supports passing NULL but restricts the output to PATH_MAX // paths. musl supports passing NULL but restricts the output to PATH_MAX
// anyway. // anyway.
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
return allocator.dupe(u8, try self.realpath(pathname, buf[0..])); return allocator.dupe(u8, try self.realpath(pathname, buf[0..]));
} }
@ -2192,10 +2192,10 @@ fn deleteTreeMinStackSizeWithKindHint(self: Dir, sub_path: []const u8, kind_hint
var cleanup_dir = true; var cleanup_dir = true;
defer if (cleanup_dir) dir.close(); defer if (cleanup_dir) dir.close();
// Valid use of MAX_PATH_BYTES because dir_name_buf will only // Valid use of max_path_bytes because dir_name_buf will only
// ever store a single path component that was returned from the // ever store a single path component that was returned from the
// filesystem. // filesystem.
var dir_name_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var dir_name_buf: [fs.max_path_bytes]u8 = undefined;
var dir_name: []const u8 = sub_path; var dir_name: []const u8 = sub_path;
// Here we must avoid recursion, in order to provide O(1) memory guarantee of this function. // Here we must avoid recursion, in order to provide O(1) memory guarantee of this function.

View File

@ -42,7 +42,7 @@ pub fn getAppDataDir(allocator: mem.Allocator, appname: []const u8) GetAppDataDi
return fs.path.join(allocator, &[_][]const u8{ home_dir, ".local", "share", appname }); return fs.path.join(allocator, &[_][]const u8{ home_dir, ".local", "share", appname });
}, },
.haiku => { .haiku => {
var dir_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined;
const rc = std.c.find_directory(.B_USER_SETTINGS_DIRECTORY, -1, true, &dir_path_buf, dir_path_buf.len); const rc = std.c.find_directory(.B_USER_SETTINGS_DIRECTORY, -1, true, &dir_path_buf, dir_path_buf.len);
const settings_dir = try allocator.dupeZ(u8, mem.sliceTo(&dir_path_buf, 0)); const settings_dir = try allocator.dupeZ(u8, mem.sliceTo(&dir_path_buf, 0));
defer allocator.free(settings_dir); defer allocator.free(settings_dir);

View File

@ -43,7 +43,7 @@ const PathType = enum {
fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 { fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 {
// The final path may not actually exist which would cause realpath to fail. // The final path may not actually exist which would cause realpath to fail.
// So instead, we get the path of the dir and join it with the relative path. // So instead, we get the path of the dir and join it with the relative path.
var fd_path_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var fd_path_buf: [fs.max_path_bytes]u8 = undefined;
const dir_path = try std.os.getFdPath(dir.fd, &fd_path_buf); const dir_path = try std.os.getFdPath(dir.fd, &fd_path_buf);
return fs.path.joinZ(allocator, &.{ dir_path, relative_path }); return fs.path.joinZ(allocator, &.{ dir_path, relative_path });
} }
@ -52,7 +52,7 @@ const PathType = enum {
fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 { fn transform(allocator: mem.Allocator, dir: Dir, relative_path: [:0]const u8) TransformError![:0]const u8 {
// Any drive absolute path (C:\foo) can be converted into a UNC path by // Any drive absolute path (C:\foo) can be converted into a UNC path by
// using '127.0.0.1' as the server name and '<drive letter>$' as the share name. // using '127.0.0.1' as the server name and '<drive letter>$' as the share name.
var fd_path_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var fd_path_buf: [fs.max_path_bytes]u8 = undefined;
const dir_path = try std.os.getFdPath(dir.fd, &fd_path_buf); const dir_path = try std.os.getFdPath(dir.fd, &fd_path_buf);
const windows_path_type = windows.getUnprefixedPathType(u8, dir_path); const windows_path_type = windows.getUnprefixedPathType(u8, dir_path);
switch (windows_path_type) { switch (windows_path_type) {
@ -206,13 +206,13 @@ test "Dir.readLink" {
} }
fn testReadLink(dir: Dir, target_path: []const u8, symlink_path: []const u8) !void { fn testReadLink(dir: Dir, target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const actual = try dir.readLink(symlink_path, buffer[0..]); const actual = try dir.readLink(symlink_path, buffer[0..]);
try testing.expectEqualStrings(target_path, actual); try testing.expectEqualStrings(target_path, actual);
} }
fn testReadLinkAbsolute(target_path: []const u8, symlink_path: []const u8) !void { fn testReadLinkAbsolute(target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const given = try fs.readLinkAbsolute(symlink_path, buffer[0..]); const given = try fs.readLinkAbsolute(symlink_path, buffer[0..]);
try testing.expectEqualStrings(target_path, given); try testing.expectEqualStrings(target_path, given);
} }
@ -611,7 +611,7 @@ test "Dir.realpath smoke test" {
const allocator = ctx.arena.allocator(); const allocator = ctx.arena.allocator();
const test_file_path = try ctx.transformPath("test_file"); const test_file_path = try ctx.transformPath("test_file");
const test_dir_path = try ctx.transformPath("test_dir"); const test_dir_path = try ctx.transformPath("test_dir");
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
// FileNotFound if the path doesn't exist // FileNotFound if the path doesn't exist
try testing.expectError(error.FileNotFound, ctx.dir.realpathAlloc(allocator, test_file_path)); try testing.expectError(error.FileNotFound, ctx.dir.realpathAlloc(allocator, test_file_path));
@ -1041,7 +1041,7 @@ test "openSelfExe" {
test "selfExePath" { test "selfExePath" {
if (native_os == .wasi) return error.SkipZigTest; if (native_os == .wasi) return error.SkipZigTest;
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const buf_self_exe_path = try std.fs.selfExePath(&buf); const buf_self_exe_path = try std.fs.selfExePath(&buf);
const alloc_self_exe_path = try std.fs.selfExePathAlloc(testing.allocator); const alloc_self_exe_path = try std.fs.selfExePathAlloc(testing.allocator);
defer testing.allocator.free(alloc_self_exe_path); defer testing.allocator.free(alloc_self_exe_path);
@ -2061,7 +2061,7 @@ test "invalid UTF-8/WTF-8 paths" {
try testing.expectError(expected_err, fs.deleteFileAbsolute(invalid_path)); try testing.expectError(expected_err, fs.deleteFileAbsolute(invalid_path));
try testing.expectError(expected_err, fs.deleteFileAbsoluteZ(invalid_path)); try testing.expectError(expected_err, fs.deleteFileAbsoluteZ(invalid_path));
try testing.expectError(expected_err, fs.deleteTreeAbsolute(invalid_path)); try testing.expectError(expected_err, fs.deleteTreeAbsolute(invalid_path));
var readlink_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var readlink_buf: [fs.max_path_bytes]u8 = undefined;
try testing.expectError(expected_err, fs.readLinkAbsolute(invalid_path, &readlink_buf)); try testing.expectError(expected_err, fs.readLinkAbsolute(invalid_path, &readlink_buf));
try testing.expectError(expected_err, fs.readLinkAbsoluteZ(invalid_path, &readlink_buf)); try testing.expectError(expected_err, fs.readLinkAbsoluteZ(invalid_path, &readlink_buf));
try testing.expectError(expected_err, fs.symLinkAbsolute(invalid_path, invalid_path, .{})); try testing.expectError(expected_err, fs.symLinkAbsolute(invalid_path, invalid_path, .{}));

View File

@ -2083,8 +2083,7 @@ test byteSwapAllFields {
}, k); }, k);
} }
/// Deprecated: use `tokenizeAny`, `tokenizeSequence`, or `tokenizeScalar` pub const tokenize = @compileError("deprecated; use tokenizeAny, tokenizeSequence, or tokenizeScalar");
pub const tokenize = tokenizeAny;
/// Returns an iterator that iterates over the slices of `buffer` that are not /// Returns an iterator that iterates over the slices of `buffer` that are not
/// any of the items in `delimiters`. /// any of the items in `delimiters`.
@ -2284,8 +2283,7 @@ test "tokenize (reset)" {
} }
} }
/// Deprecated: use `splitSequence`, `splitAny`, or `splitScalar` pub const split = @compileError("deprecated; use splitSequence, splitAny, or splitScalar");
pub const split = splitSequence;
/// Returns an iterator that iterates over the slices of `buffer` that /// Returns an iterator that iterates over the slices of `buffer` that
/// are separated by the byte sequence in `delimiter`. /// are separated by the byte sequence in `delimiter`.
@ -2486,8 +2484,7 @@ test "split (reset)" {
} }
} }
/// Deprecated: use `splitBackwardsSequence`, `splitBackwardsAny`, or `splitBackwardsScalar` pub const splitBackwards = @compileError("deprecated; use splitBackwardsSequence, splitBackwardsAny, or splitBackwardsScalar");
pub const splitBackwards = splitBackwardsSequence;
/// Returns an iterator that iterates backwards over the slices of `buffer` that /// Returns an iterator that iterates backwards over the slices of `buffer` that
/// are separated by the sequence in `delimiter`. /// are separated by the sequence in `delimiter`.

View File

@ -21,7 +21,7 @@ const mem = std.mem;
const elf = std.elf; const elf = std.elf;
const fs = std.fs; const fs = std.fs;
const dl = @import("dynamic_library.zig"); const dl = @import("dynamic_library.zig");
const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES; const max_path_bytes = std.fs.max_path_bytes;
const posix = std.posix; const posix = std.posix;
pub const linux = @import("os/linux.zig"); pub const linux = @import("os/linux.zig");
@ -99,7 +99,7 @@ pub fn isGetFdPathSupportedOnTarget(os: std.Target.Os) bool {
/// * On other platforms, the result is an opaque sequence of bytes with no particular encoding. /// * On other platforms, the result is an opaque sequence of bytes with no particular encoding.
/// ///
/// Calling this function is usually a bug. /// Calling this function is usually a bug.
pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.RealPathError![]u8 { pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[max_path_bytes]u8) std.posix.RealPathError![]u8 {
if (!comptime isGetFdPathSupportedOnTarget(builtin.os)) { if (!comptime isGetFdPathSupportedOnTarget(builtin.os)) {
@compileError("querying for canonical path of a handle is unsupported on this host"); @compileError("querying for canonical path of a handle is unsupported on this host");
} }
@ -114,7 +114,7 @@ pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.
.macos, .ios, .watchos, .tvos, .visionos => { .macos, .ios, .watchos, .tvos, .visionos => {
// On macOS, we can use F.GETPATH fcntl command to query the OS for // On macOS, we can use F.GETPATH fcntl command to query the OS for
// the path to the file descriptor. // the path to the file descriptor.
@memset(out_buffer[0..MAX_PATH_BYTES], 0); @memset(out_buffer[0..max_path_bytes], 0);
switch (posix.errno(posix.system.fcntl(fd, posix.F.GETPATH, out_buffer))) { switch (posix.errno(posix.system.fcntl(fd, posix.F.GETPATH, out_buffer))) {
.SUCCESS => {}, .SUCCESS => {},
.BADF => return error.FileNotFound, .BADF => return error.FileNotFound,
@ -123,7 +123,7 @@ pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.
// errno values to expect when command is F.GETPATH... // errno values to expect when command is F.GETPATH...
else => |err| return posix.unexpectedErrno(err), else => |err| return posix.unexpectedErrno(err),
} }
const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse MAX_PATH_BYTES; const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse max_path_bytes;
return out_buffer[0..len]; return out_buffer[0..len];
}, },
.linux => { .linux => {
@ -163,7 +163,7 @@ pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.
.BADF => return error.FileNotFound, .BADF => return error.FileNotFound,
else => |err| return posix.unexpectedErrno(err), else => |err| return posix.unexpectedErrno(err),
} }
const len = mem.indexOfScalar(u8, &kfile.path, 0) orelse MAX_PATH_BYTES; const len = mem.indexOfScalar(u8, &kfile.path, 0) orelse max_path_bytes;
if (len == 0) return error.NameTooLong; if (len == 0) return error.NameTooLong;
const result = out_buffer[0..len]; const result = out_buffer[0..len];
@memcpy(result, kfile.path[0..len]); @memcpy(result, kfile.path[0..len]);
@ -196,7 +196,7 @@ pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.
while (i < len) { while (i < len) {
const kf: *align(1) std.c.kinfo_file = @ptrCast(&buf[i]); const kf: *align(1) std.c.kinfo_file = @ptrCast(&buf[i]);
if (kf.fd == fd) { if (kf.fd == fd) {
len = mem.indexOfScalar(u8, &kf.path, 0) orelse MAX_PATH_BYTES; len = mem.indexOfScalar(u8, &kf.path, 0) orelse max_path_bytes;
if (len == 0) return error.NameTooLong; if (len == 0) return error.NameTooLong;
const result = out_buffer[0..len]; const result = out_buffer[0..len];
@memcpy(result, kf.path[0..len]); @memcpy(result, kf.path[0..len]);
@ -208,18 +208,18 @@ pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.
} }
}, },
.dragonfly => { .dragonfly => {
@memset(out_buffer[0..MAX_PATH_BYTES], 0); @memset(out_buffer[0..max_path_bytes], 0);
switch (posix.errno(std.c.fcntl(fd, posix.F.GETPATH, out_buffer))) { switch (posix.errno(std.c.fcntl(fd, posix.F.GETPATH, out_buffer))) {
.SUCCESS => {}, .SUCCESS => {},
.BADF => return error.FileNotFound, .BADF => return error.FileNotFound,
.RANGE => return error.NameTooLong, .RANGE => return error.NameTooLong,
else => |err| return posix.unexpectedErrno(err), else => |err| return posix.unexpectedErrno(err),
} }
const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse MAX_PATH_BYTES; const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse max_path_bytes;
return out_buffer[0..len]; return out_buffer[0..len];
}, },
.netbsd => { .netbsd => {
@memset(out_buffer[0..MAX_PATH_BYTES], 0); @memset(out_buffer[0..max_path_bytes], 0);
switch (posix.errno(std.c.fcntl(fd, posix.F.GETPATH, out_buffer))) { switch (posix.errno(std.c.fcntl(fd, posix.F.GETPATH, out_buffer))) {
.SUCCESS => {}, .SUCCESS => {},
.ACCES => return error.AccessDenied, .ACCES => return error.AccessDenied,
@ -229,7 +229,7 @@ pub fn getFdPath(fd: std.posix.fd_t, out_buffer: *[MAX_PATH_BYTES]u8) std.posix.
.RANGE => return error.NameTooLong, .RANGE => return error.NameTooLong,
else => |err| return posix.unexpectedErrno(err), else => |err| return posix.unexpectedErrno(err),
} }
const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse MAX_PATH_BYTES; const len = mem.indexOfScalar(u8, out_buffer[0..], 0) orelse max_path_bytes;
return out_buffer[0..len]; return out_buffer[0..len];
}, },
else => unreachable, // made unreachable by isGetFdPathSupportedOnTarget above else => unreachable, // made unreachable by isGetFdPathSupportedOnTarget above

View File

@ -3995,7 +3995,7 @@ test "ring mapped buffers recv" {
defer fds.close(); defer fds.close();
// for random user_data in sqe/cqe // for random user_data in sqe/cqe
var Rnd = std.rand.DefaultPrng.init(0); var Rnd = std.Random.DefaultPrng.init(0);
var rnd = Rnd.random(); var rnd = Rnd.random();
var round: usize = 4; // repeat send/recv cycle round times var round: usize = 4; // repeat send/recv cycle round times
@ -4081,7 +4081,7 @@ test "ring mapped buffers multishot recv" {
defer fds.close(); defer fds.close();
// for random user_data in sqe/cqe // for random user_data in sqe/cqe
var Rnd = std.rand.DefaultPrng.init(0); var Rnd = std.Random.DefaultPrng.init(0);
var rnd = Rnd.random(); var rnd = Rnd.random();
var round: usize = 4; // repeat send/recv cycle round times var round: usize = 4; // repeat send/recv cycle round times

View File

@ -285,16 +285,16 @@ pub fn openat(dirfd: i32, path: [*:0]const u8, flags: u32, _: mode_t) usize {
if (dirfd == AT.FDCWD) { // openat(AT_FDCWD, ...) == open(...) if (dirfd == AT.FDCWD) { // openat(AT_FDCWD, ...) == open(...)
return open(path, flags); return open(path, flags);
} }
var dir_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var dir_path_buf: [std.fs.max_path_bytes]u8 = undefined;
var total_path_buf: [std.fs.MAX_PATH_BYTES + 1]u8 = undefined; var total_path_buf: [std.fs.max_path_bytes + 1]u8 = undefined;
const rc = fd2path(dirfd, &dir_path_buf, std.fs.MAX_PATH_BYTES); const rc = fd2path(dirfd, &dir_path_buf, std.fs.max_path_bytes);
if (rc != 0) return rc; if (rc != 0) return rc;
var fba = std.heap.FixedBufferAllocator.init(&total_path_buf); var fba = std.heap.FixedBufferAllocator.init(&total_path_buf);
var alloc = fba.allocator(); var alloc = fba.allocator();
const dir_path = std.mem.span(@as([*:0]u8, @ptrCast(&dir_path_buf))); const dir_path = std.mem.span(@as([*:0]u8, @ptrCast(&dir_path_buf)));
const total_path = std.fs.path.join(alloc, &.{ dir_path, std.mem.span(path) }) catch unreachable; // the allocation shouldn't fail because it should not exceed MAX_PATH_BYTES const total_path = std.fs.path.join(alloc, &.{ dir_path, std.mem.span(path) }) catch unreachable; // the allocation shouldn't fail because it should not exceed max_path_bytes
fba.reset(); fba.reset();
const total_path_z = alloc.dupeZ(u8, total_path) catch unreachable; // should not exceed MAX_PATH_BYTES + 1 const total_path_z = alloc.dupeZ(u8, total_path) catch unreachable; // should not exceed max_path_bytes + 1
return open(total_path_z.ptr, flags); return open(total_path_z.ptr, flags);
} }

View File

@ -30,7 +30,7 @@ fn testToPrefixedFileNoOracle(comptime path: []const u8, comptime expected_path:
const expected_path_utf16 = std.unicode.utf8ToUtf16LeStringLiteral(expected_path); const expected_path_utf16 = std.unicode.utf8ToUtf16LeStringLiteral(expected_path);
const actual_path = try windows.wToPrefixedFileW(null, path_utf16); const actual_path = try windows.wToPrefixedFileW(null, path_utf16);
std.testing.expectEqualSlices(u16, expected_path_utf16, actual_path.span()) catch |e| { std.testing.expectEqualSlices(u16, expected_path_utf16, actual_path.span()) catch |e| {
std.debug.print("got '{s}', expected '{s}'\n", .{ std.unicode.fmtUtf16Le(actual_path.span()), std.unicode.fmtUtf16le(expected_path_utf16) }); std.debug.print("got '{s}', expected '{s}'\n", .{ std.unicode.fmtUtf16Le(actual_path.span()), std.unicode.fmtUtf16Le(expected_path_utf16) });
return e; return e;
}; };
} }
@ -48,7 +48,7 @@ fn testToPrefixedFileOnlyOracle(comptime path: []const u8) !void {
const zig_result = try windows.wToPrefixedFileW(null, path_utf16); const zig_result = try windows.wToPrefixedFileW(null, path_utf16);
const win32_api_result = try RtlDosPathNameToNtPathName_U(path_utf16); const win32_api_result = try RtlDosPathNameToNtPathName_U(path_utf16);
std.testing.expectEqualSlices(u16, win32_api_result.span(), zig_result.span()) catch |e| { std.testing.expectEqualSlices(u16, win32_api_result.span(), zig_result.span()) catch |e| {
std.debug.print("got '{s}', expected '{s}'\n", .{ std.unicode.fmtUtf16Le(zig_result.span()), std.unicode.fmtUtf16le(win32_api_result.span()) }); std.debug.print("got '{s}', expected '{s}'\n", .{ std.unicode.fmtUtf16Le(zig_result.span()), std.unicode.fmtUtf16Le(win32_api_result.span()) });
return e; return e;
}; };
} }

View File

@ -19,7 +19,7 @@ const root = @import("root");
const std = @import("std.zig"); const std = @import("std.zig");
const mem = std.mem; const mem = std.mem;
const fs = std.fs; const fs = std.fs;
const max_path_bytes = fs.MAX_PATH_BYTES; const max_path_bytes = fs.max_path_bytes;
const maxInt = std.math.maxInt; const maxInt = std.math.maxInt;
const cast = std.math.cast; const cast = std.math.cast;
const assert = std.debug.assert; const assert = std.debug.assert;

View File

@ -31,13 +31,13 @@ test "chdir smoke test" {
} }
// Get current working directory path // Get current working directory path
var old_cwd_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var old_cwd_buf: [fs.max_path_bytes]u8 = undefined;
const old_cwd = try posix.getcwd(old_cwd_buf[0..]); const old_cwd = try posix.getcwd(old_cwd_buf[0..]);
{ {
// Firstly, changing to itself should have no effect // Firstly, changing to itself should have no effect
try posix.chdir(old_cwd); try posix.chdir(old_cwd);
var new_cwd_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var new_cwd_buf: [fs.max_path_bytes]u8 = undefined;
const new_cwd = try posix.getcwd(new_cwd_buf[0..]); const new_cwd = try posix.getcwd(new_cwd_buf[0..]);
try expect(mem.eql(u8, old_cwd, new_cwd)); try expect(mem.eql(u8, old_cwd, new_cwd));
} }
@ -50,7 +50,7 @@ test "chdir smoke test" {
// Restore cwd because process may have other tests that do not tolerate chdir. // Restore cwd because process may have other tests that do not tolerate chdir.
defer posix.chdir(old_cwd) catch unreachable; defer posix.chdir(old_cwd) catch unreachable;
var new_cwd_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var new_cwd_buf: [fs.max_path_bytes]u8 = undefined;
const new_cwd = try posix.getcwd(new_cwd_buf[0..]); const new_cwd = try posix.getcwd(new_cwd_buf[0..]);
try expect(mem.eql(u8, parent, new_cwd)); try expect(mem.eql(u8, parent, new_cwd));
} }
@ -58,7 +58,7 @@ test "chdir smoke test" {
// Next, change current working directory to a temp directory one level below // Next, change current working directory to a temp directory one level below
{ {
// Create a tmp directory // Create a tmp directory
var tmp_dir_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var tmp_dir_buf: [fs.max_path_bytes]u8 = undefined;
const tmp_dir_path = path: { const tmp_dir_path = path: {
var allocator = std.heap.FixedBufferAllocator.init(&tmp_dir_buf); var allocator = std.heap.FixedBufferAllocator.init(&tmp_dir_buf);
break :path try fs.path.resolve(allocator.allocator(), &[_][]const u8{ old_cwd, "zig-test-tmp" }); break :path try fs.path.resolve(allocator.allocator(), &[_][]const u8{ old_cwd, "zig-test-tmp" });
@ -68,11 +68,11 @@ test "chdir smoke test" {
// Change current working directory to tmp directory // Change current working directory to tmp directory
try posix.chdir("zig-test-tmp"); try posix.chdir("zig-test-tmp");
var new_cwd_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var new_cwd_buf: [fs.max_path_bytes]u8 = undefined;
const new_cwd = try posix.getcwd(new_cwd_buf[0..]); const new_cwd = try posix.getcwd(new_cwd_buf[0..]);
// On Windows, fs.path.resolve returns an uppercase drive letter, but the drive letter returned by getcwd may be lowercase // On Windows, fs.path.resolve returns an uppercase drive letter, but the drive letter returned by getcwd may be lowercase
var resolved_cwd_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var resolved_cwd_buf: [fs.max_path_bytes]u8 = undefined;
const resolved_cwd = path: { const resolved_cwd = path: {
var allocator = std.heap.FixedBufferAllocator.init(&resolved_cwd_buf); var allocator = std.heap.FixedBufferAllocator.init(&resolved_cwd_buf);
break :path try fs.path.resolve(allocator.allocator(), &[_][]const u8{new_cwd}); break :path try fs.path.resolve(allocator.allocator(), &[_][]const u8{new_cwd});
@ -230,7 +230,7 @@ test "symlink with relative paths" {
try posix.symlink("file.txt", "symlinked"); try posix.symlink("file.txt", "symlinked");
} }
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const given = try posix.readlink("symlinked", buffer[0..]); const given = try posix.readlink("symlinked", buffer[0..]);
try expect(mem.eql(u8, "file.txt", given)); try expect(mem.eql(u8, "file.txt", given));
@ -247,7 +247,7 @@ test "readlink on Windows" {
} }
fn testReadlink(target_path: []const u8, symlink_path: []const u8) !void { fn testReadlink(target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const given = try posix.readlink(symlink_path, buffer[0..]); const given = try posix.readlink(symlink_path, buffer[0..]);
try expect(mem.eql(u8, target_path, given)); try expect(mem.eql(u8, target_path, given));
} }
@ -385,7 +385,7 @@ test "readlinkat" {
} }
// read the link // read the link
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const read_link = try posix.readlinkat(tmp.dir.fd, "link", buffer[0..]); const read_link = try posix.readlinkat(tmp.dir.fd, "link", buffer[0..]);
try expect(mem.eql(u8, "file.txt", read_link)); try expect(mem.eql(u8, "file.txt", read_link));
} }
@ -466,7 +466,7 @@ test "getrandom" {
test "getcwd" { test "getcwd" {
// at least call it so it gets compiled // at least call it so it gets compiled
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
_ = posix.getcwd(&buf) catch undefined; _ = posix.getcwd(&buf) catch undefined;
} }

View File

@ -32,9 +32,9 @@ pub const GetCwdAllocError = Allocator.Error || posix.GetCwdError;
/// On Windows, the result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/). /// On Windows, the result is encoded as [WTF-8](https://simonsapin.github.io/wtf-8/).
/// On other platforms, the result is an opaque sequence of bytes with no particular encoding. /// On other platforms, the result is an opaque sequence of bytes with no particular encoding.
pub fn getCwdAlloc(allocator: Allocator) ![]u8 { pub fn getCwdAlloc(allocator: Allocator) ![]u8 {
// The use of MAX_PATH_BYTES here is just a heuristic: most paths will fit // The use of max_path_bytes here is just a heuristic: most paths will fit
// in stack_buf, avoiding an extra allocation in the common case. // in stack_buf, avoiding an extra allocation in the common case.
var stack_buf: [fs.MAX_PATH_BYTES]u8 = undefined; var stack_buf: [fs.max_path_bytes]u8 = undefined;
var heap_buf: ?[]u8 = null; var heap_buf: ?[]u8 = null;
defer if (heap_buf) |buf| allocator.free(buf); defer if (heap_buf) |buf| allocator.free(buf);
@ -1618,7 +1618,7 @@ pub const can_execv = switch (native_os) {
else => true, else => true,
}; };
/// Tells whether spawning child processes is supported (e.g. via ChildProcess) /// Tells whether spawning child processes is supported (e.g. via Child)
pub const can_spawn = switch (native_os) { pub const can_spawn = switch (native_os) {
.wasi, .watchos, .tvos, .visionos => false, .wasi, .watchos, .tvos, .visionos => false,
else => true, else => true,

View File

@ -43,8 +43,6 @@ pub const StringHashMap = hash_map.StringHashMap;
pub const StringHashMapUnmanaged = hash_map.StringHashMapUnmanaged; pub const StringHashMapUnmanaged = hash_map.StringHashMapUnmanaged;
pub const StringArrayHashMap = array_hash_map.StringArrayHashMap; pub const StringArrayHashMap = array_hash_map.StringArrayHashMap;
pub const StringArrayHashMapUnmanaged = array_hash_map.StringArrayHashMapUnmanaged; pub const StringArrayHashMapUnmanaged = array_hash_map.StringArrayHashMapUnmanaged;
/// deprecated: use `DoublyLinkedList`.
pub const TailQueue = DoublyLinkedList;
pub const Target = @import("Target.zig"); pub const Target = @import("Target.zig");
pub const Thread = @import("Thread.zig"); pub const Thread = @import("Thread.zig");
pub const Treap = @import("treap.zig").Treap; pub const Treap = @import("treap.zig").Treap;
@ -88,8 +86,6 @@ pub const packed_int_array = @import("packed_int_array.zig");
pub const pdb = @import("pdb.zig"); pub const pdb = @import("pdb.zig");
pub const posix = @import("posix.zig"); pub const posix = @import("posix.zig");
pub const process = @import("process.zig"); pub const process = @import("process.zig");
/// Deprecated: use `Random` instead.
pub const rand = Random;
pub const sort = @import("sort.zig"); pub const sort = @import("sort.zig");
pub const simd = @import("simd.zig"); pub const simd = @import("simd.zig");
pub const ascii = @import("ascii.zig"); pub const ascii = @import("ascii.zig");

View File

@ -283,9 +283,9 @@ fn nullStr(str: []const u8) []const u8 {
/// Options for iterator. /// Options for iterator.
/// Buffers should be provided by the caller. /// Buffers should be provided by the caller.
pub const IteratorOptions = struct { pub const IteratorOptions = struct {
/// Use a buffer with length `std.fs.MAX_PATH_BYTES` to match file system capabilities. /// Use a buffer with length `std.fs.max_path_bytes` to match file system capabilities.
file_name_buffer: []u8, file_name_buffer: []u8,
/// Use a buffer with length `std.fs.MAX_PATH_BYTES` to match file system capabilities. /// Use a buffer with length `std.fs.max_path_bytes` to match file system capabilities.
link_name_buffer: []u8, link_name_buffer: []u8,
/// Collects error messages during unpacking /// Collects error messages during unpacking
diagnostics: ?*Diagnostics = null, diagnostics: ?*Diagnostics = null,
@ -613,8 +613,8 @@ fn PaxIterator(comptime ReaderType: type) type {
/// Saves tar file content to the file systems. /// Saves tar file content to the file systems.
pub fn pipeToFileSystem(dir: std.fs.Dir, reader: anytype, options: PipeOptions) !void { pub fn pipeToFileSystem(dir: std.fs.Dir, reader: anytype, options: PipeOptions) !void {
var file_name_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var file_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
var link_name_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var link_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
var iter = iterator(reader, .{ var iter = iterator(reader, .{
.file_name_buffer = &file_name_buffer, .file_name_buffer = &file_name_buffer,
.link_name_buffer = &link_name_buffer, .link_name_buffer = &link_name_buffer,
@ -946,8 +946,8 @@ test iterator {
var fbs = std.io.fixedBufferStream(data); var fbs = std.io.fixedBufferStream(data);
// User provided buffers to the iterator // User provided buffers to the iterator
var file_name_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var file_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
var link_name_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var link_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
// Create iterator // Create iterator
var iter = iterator(fbs.reader(), .{ var iter = iterator(fbs.reader(), .{
.file_name_buffer = &file_name_buffer, .file_name_buffer = &file_name_buffer,

View File

@ -342,8 +342,8 @@ const Md5Writer = struct {
}; };
test "run test cases" { test "run test cases" {
var file_name_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var file_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
var link_name_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var link_name_buffer: [std.fs.max_path_bytes]u8 = undefined;
for (cases) |case| { for (cases) |case| {
var fsb = std.io.fixedBufferStream(case.data); var fsb = std.io.fixedBufferStream(case.data);

View File

@ -983,8 +983,7 @@ pub fn utf16LeToUtf8ArrayList(result: *std.ArrayList(u8), utf16le: []const u16)
return utf16LeToUtf8ArrayListImpl(result, utf16le, .cannot_encode_surrogate_half); return utf16LeToUtf8ArrayListImpl(result, utf16le, .cannot_encode_surrogate_half);
} }
/// Deprecated; renamed to utf16LeToUtf8Alloc pub const utf16leToUtf8Alloc = @compileError("deprecated; renamed to utf16LeToUtf8Alloc");
pub const utf16leToUtf8Alloc = utf16LeToUtf8Alloc;
/// Caller must free returned memory. /// Caller must free returned memory.
pub fn utf16LeToUtf8Alloc(allocator: mem.Allocator, utf16le: []const u16) Utf16LeToUtf8AllocError![]u8 { pub fn utf16LeToUtf8Alloc(allocator: mem.Allocator, utf16le: []const u16) Utf16LeToUtf8AllocError![]u8 {
@ -996,8 +995,7 @@ pub fn utf16LeToUtf8Alloc(allocator: mem.Allocator, utf16le: []const u16) Utf16L
return result.toOwnedSlice(); return result.toOwnedSlice();
} }
/// Deprecated; renamed to utf16LeToUtf8AllocZ pub const utf16leToUtf8AllocZ = @compileError("deprecated; renamed to utf16LeToUtf8AllocZ");
pub const utf16leToUtf8AllocZ = utf16LeToUtf8AllocZ;
/// Caller must free returned memory. /// Caller must free returned memory.
pub fn utf16LeToUtf8AllocZ(allocator: mem.Allocator, utf16le: []const u16) Utf16LeToUtf8AllocError![:0]u8 { pub fn utf16LeToUtf8AllocZ(allocator: mem.Allocator, utf16le: []const u16) Utf16LeToUtf8AllocError![:0]u8 {
@ -1067,8 +1065,7 @@ fn utf16LeToUtf8Impl(utf8: []u8, utf16le: []const u16, comptime surrogates: Surr
return dest_index; return dest_index;
} }
/// Deprecated; renamed to utf16LeToUtf8 pub const utf16leToUtf8 = @compileError("deprecated; renamed to utf16LeToUtf8");
pub const utf16leToUtf8 = utf16LeToUtf8;
pub fn utf16LeToUtf8(utf8: []u8, utf16le: []const u16) Utf16LeToUtf8Error!usize { pub fn utf16LeToUtf8(utf8: []u8, utf16le: []const u16) Utf16LeToUtf8Error!usize {
return utf16LeToUtf8Impl(utf8, utf16le, .cannot_encode_surrogate_half); return utf16LeToUtf8Impl(utf8, utf16le, .cannot_encode_surrogate_half);
@ -1189,8 +1186,7 @@ pub fn utf8ToUtf16LeAlloc(allocator: mem.Allocator, utf8: []const u8) error{ Inv
return result.toOwnedSlice(); return result.toOwnedSlice();
} }
/// Deprecated; renamed to utf8ToUtf16LeAllocZ pub const utf8ToUtf16LeWithNull = @compileError("deprecated; renamed to utf8ToUtf16LeAllocZ");
pub const utf8ToUtf16LeWithNull = utf8ToUtf16LeAllocZ;
pub fn utf8ToUtf16LeAllocZ(allocator: mem.Allocator, utf8: []const u8) error{ InvalidUtf8, OutOfMemory }![:0]u16 { pub fn utf8ToUtf16LeAllocZ(allocator: mem.Allocator, utf8: []const u8) error{ InvalidUtf8, OutOfMemory }![:0]u16 {
// optimistically guess that it will not require surrogate pairs // optimistically guess that it will not require surrogate pairs
@ -1335,7 +1331,7 @@ test utf8ToUtf16LeAllocZ {
try testing.expectError(error.InvalidUtf8, result); try testing.expectError(error.InvalidUtf8, result);
} }
{ {
const utf16 = try utf8ToUtf16LeWithNull(testing.allocator, "This string has been designed to test the vectorized implementat" ++ const utf16 = try utf8ToUtf16LeAllocZ(testing.allocator, "This string has been designed to test the vectorized implementat" ++
"ion by beginning with one hundred twenty-seven ASCII characters¡"); "ion by beginning with one hundred twenty-seven ASCII characters¡");
defer testing.allocator.free(utf16); defer testing.allocator.free(utf16);
try testing.expectEqualSlices(u8, &.{ try testing.expectEqualSlices(u8, &.{
@ -1479,8 +1475,7 @@ fn formatUtf16Le(
try writer.writeAll(buf[0..u8len]); try writer.writeAll(buf[0..u8len]);
} }
/// Deprecated; renamed to fmtUtf16Le pub const fmtUtf16le = @compileError("deprecated; renamed to fmtUtf16Le");
pub const fmtUtf16le = fmtUtf16Le;
/// Return a Formatter for a (potentially ill-formed) UTF-16 LE string, /// Return a Formatter for a (potentially ill-formed) UTF-16 LE string,
/// which will be converted to UTF-8 during formatting. /// which will be converted to UTF-8 during formatting.

View File

@ -15,8 +15,7 @@ pub const Ast = @import("zig/Ast.zig");
pub const AstGen = @import("zig/AstGen.zig"); pub const AstGen = @import("zig/AstGen.zig");
pub const Zir = @import("zig/Zir.zig"); pub const Zir = @import("zig/Zir.zig");
pub const system = @import("zig/system.zig"); pub const system = @import("zig/system.zig");
/// Deprecated: use `std.Target.Query`. pub const CrossTarget = @compileError("deprecated; use std.Target.Query");
pub const CrossTarget = std.Target.Query;
pub const BuiltinFn = @import("zig/BuiltinFn.zig"); pub const BuiltinFn = @import("zig/BuiltinFn.zig");
pub const AstRlAnnotate = @import("zig/AstRlAnnotate.zig"); pub const AstRlAnnotate = @import("zig/AstRlAnnotate.zig");
pub const LibCInstallation = @import("zig/LibCInstallation.zig"); pub const LibCInstallation = @import("zig/LibCInstallation.zig");

View File

@ -444,7 +444,7 @@ pub const Installation = struct {
error.OutOfMemory => return error.OutOfMemory, error.OutOfMemory => return error.OutOfMemory,
}; };
if (path_maybe_with_trailing_slash.len > std.fs.MAX_PATH_BYTES or !std.fs.path.isAbsolute(path_maybe_with_trailing_slash)) { if (path_maybe_with_trailing_slash.len > std.fs.max_path_bytes or !std.fs.path.isAbsolute(path_maybe_with_trailing_slash)) {
allocator.free(path_maybe_with_trailing_slash); allocator.free(path_maybe_with_trailing_slash);
return error.PathTooLong; return error.PathTooLong;
} }
@ -459,7 +459,7 @@ pub const Installation = struct {
errdefer allocator.free(path); errdefer allocator.free(path);
const version = version: { const version = version: {
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
const sdk_lib_dir_path = std.fmt.bufPrint(buf[0..], "{s}\\Lib\\", .{path}) catch |err| switch (err) { const sdk_lib_dir_path = std.fmt.bufPrint(buf[0..], "{s}\\Lib\\", .{path}) catch |err| switch (err) {
error.NoSpaceLeft => return error.PathTooLong, error.NoSpaceLeft => return error.PathTooLong,
}; };
@ -516,7 +516,7 @@ pub const Installation = struct {
error.OutOfMemory => return error.OutOfMemory, error.OutOfMemory => return error.OutOfMemory,
}; };
if (path_maybe_with_trailing_slash.len > std.fs.MAX_PATH_BYTES or !std.fs.path.isAbsolute(path_maybe_with_trailing_slash)) { if (path_maybe_with_trailing_slash.len > std.fs.max_path_bytes or !std.fs.path.isAbsolute(path_maybe_with_trailing_slash)) {
allocator.free(path_maybe_with_trailing_slash); allocator.free(path_maybe_with_trailing_slash);
return error.PathTooLong; return error.PathTooLong;
} }
@ -562,7 +562,7 @@ pub const Installation = struct {
/// Check whether this version is enumerated in registry. /// Check whether this version is enumerated in registry.
fn isValidVersion(installation: Installation) bool { fn isValidVersion(installation: Installation) bool {
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
const reg_query_as_wtf8 = std.fmt.bufPrint(buf[0..], "{s}\\{s}\\Installed Options", .{ const reg_query_as_wtf8 = std.fmt.bufPrint(buf[0..], "{s}\\{s}\\Installed Options", .{
windows_kits_reg_key, windows_kits_reg_key,
installation.version, installation.version,
@ -878,7 +878,7 @@ const MsvcLibDir = struct {
error.OutOfMemory => return error.OutOfMemory, error.OutOfMemory => return error.OutOfMemory,
else => continue, else => continue,
}; };
if (source_directories_value.len > (std.fs.MAX_PATH_BYTES * 30)) { // note(bratishkaerik): guessing from the fact that on my computer it has 15 pathes and at least some of them are not of max length if (source_directories_value.len > (std.fs.max_path_bytes * 30)) { // note(bratishkaerik): guessing from the fact that on my computer it has 15 pathes and at least some of them are not of max length
allocator.free(source_directories_value); allocator.free(source_directories_value);
continue; continue;
} }
@ -892,7 +892,7 @@ const MsvcLibDir = struct {
const msvc_dir: []const u8 = msvc_dir: { const msvc_dir: []const u8 = msvc_dir: {
const msvc_include_dir_maybe_with_trailing_slash = try allocator.dupe(u8, source_directories_splitted.first()); const msvc_include_dir_maybe_with_trailing_slash = try allocator.dupe(u8, source_directories_splitted.first());
if (msvc_include_dir_maybe_with_trailing_slash.len > std.fs.MAX_PATH_BYTES or !std.fs.path.isAbsolute(msvc_include_dir_maybe_with_trailing_slash)) { if (msvc_include_dir_maybe_with_trailing_slash.len > std.fs.max_path_bytes or !std.fs.path.isAbsolute(msvc_include_dir_maybe_with_trailing_slash)) {
allocator.free(msvc_include_dir_maybe_with_trailing_slash); allocator.free(msvc_include_dir_maybe_with_trailing_slash);
return error.PathNotFound; return error.PathNotFound;
} }
@ -960,7 +960,7 @@ const MsvcLibDir = struct {
else => break :try_vs7_key, else => break :try_vs7_key,
}; };
if (path_maybe_with_trailing_slash.len > std.fs.MAX_PATH_BYTES or !std.fs.path.isAbsolute(path_maybe_with_trailing_slash)) { if (path_maybe_with_trailing_slash.len > std.fs.max_path_bytes or !std.fs.path.isAbsolute(path_maybe_with_trailing_slash)) {
allocator.free(path_maybe_with_trailing_slash); allocator.free(path_maybe_with_trailing_slash);
break :try_vs7_key; break :try_vs7_key;
} }

View File

@ -583,7 +583,7 @@ pub fn extract(dest: std.fs.Dir, seekable_stream: anytype, options: ExtractOptio
const SeekableStream = @TypeOf(seekable_stream); const SeekableStream = @TypeOf(seekable_stream);
var iter = try Iterator(SeekableStream).init(seekable_stream); var iter = try Iterator(SeekableStream).init(seekable_stream);
var filename_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var filename_buf: [std.fs.max_path_bytes]u8 = undefined;
while (try iter.next()) |entry| { while (try iter.next()) |entry| {
const crc32 = try entry.extract(seekable_stream, options, &filename_buf, dest); const crc32 = try entry.extract(seekable_stream, options, &filename_buf, dest);
if (crc32 != entry.crc32) if (crc32 != entry.crc32)

View File

@ -17,7 +17,7 @@ pub fn expectFiles(
}, },
) !void { ) !void {
for (test_files) |test_file| { for (test_files) |test_file| {
var normalized_sub_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var normalized_sub_path_buf: [std.fs.max_path_bytes]u8 = undefined;
const name = blk: { const name = blk: {
if (opt.strip_prefix) |strip_prefix| { if (opt.strip_prefix) |strip_prefix| {

View File

@ -266,7 +266,7 @@ pub fn populateFile(comp: *Compilation, mod: *Module, file: *File) !void {
} }
fn writeFile(file: *File, mod: *Module) !void { fn writeFile(file: *File, mod: *Module) !void {
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
var af = try mod.root.atomicFile(mod.root_src_path, .{ .make_path = true }, &buf); var af = try mod.root.atomicFile(mod.root_src_path, .{ .make_path = true }, &buf);
defer af.deinit(); defer af.deinit();
try af.file.writeAll(file.source); try af.file.writeAll(file.source);

View File

@ -1364,7 +1364,7 @@ fn recursiveDirectoryCopy(f: *Fetch, dir: fs.Dir, tmp_dir: fs.Dir) anyerror!void
}; };
}, },
.sym_link => { .sym_link => {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
const link_name = try dir.readLink(entry.path, &buf); const link_name = try dir.readLink(entry.path, &buf);
// TODO: if this would create a symlink to outside // TODO: if this would create a symlink to outside
// the destination directory, fail with an error instead. // the destination directory, fail with an error instead.
@ -1748,7 +1748,7 @@ pub fn depDigest(
switch (dep.location) { switch (dep.location) {
.url => return null, .url => return null,
.path => |rel_path| { .path => |rel_path| {
var buf: [fs.MAX_PATH_BYTES]u8 = undefined; var buf: [fs.max_path_bytes]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf); var fba = std.heap.FixedBufferAllocator.init(&buf);
const new_root = pkg_root.resolvePosix(fba.allocator(), rel_path) catch const new_root = pkg_root.resolvePosix(fba.allocator(), rel_path) catch
return null; return null;

View File

@ -1975,7 +1975,7 @@ pub const Object = struct {
defer gpa.free(dir_path); defer gpa.free(dir_path);
if (std.fs.path.isAbsolute(dir_path)) if (std.fs.path.isAbsolute(dir_path))
break :dir_path try o.builder.metadataString(dir_path); break :dir_path try o.builder.metadataString(dir_path);
var abs_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var abs_buffer: [std.fs.max_path_bytes]u8 = undefined;
const abs_path = std.fs.realpath(dir_path, &abs_buffer) catch const abs_path = std.fs.realpath(dir_path, &abs_buffer) catch
break :dir_path try o.builder.metadataString(dir_path); break :dir_path try o.builder.metadataString(dir_path);
break :dir_path try o.builder.metadataString(abs_path); break :dir_path try o.builder.metadataString(abs_path);

View File

@ -2006,7 +2006,7 @@ pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64)
// Write the form for the compile unit, which must match the abbrev table above. // Write the form for the compile unit, which must match the abbrev table above.
const name_strp = try self.strtab.insert(self.allocator, zcu.root_mod.root_src_path); const name_strp = try self.strtab.insert(self.allocator, zcu.root_mod.root_src_path);
var compile_unit_dir_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var compile_unit_dir_buffer: [std.fs.max_path_bytes]u8 = undefined;
const compile_unit_dir = resolveCompilationDir(zcu, &compile_unit_dir_buffer); const compile_unit_dir = resolveCompilationDir(zcu, &compile_unit_dir_buffer);
const comp_dir_strp = try self.strtab.insert(self.allocator, compile_unit_dir); const comp_dir_strp = try self.strtab.insert(self.allocator, compile_unit_dir);
const producer_strp = try self.strtab.insert(self.allocator, link.producer_string); const producer_strp = try self.strtab.insert(self.allocator, link.producer_string);
@ -2058,7 +2058,7 @@ pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64)
} }
} }
fn resolveCompilationDir(module: *Module, buffer: *[std.fs.MAX_PATH_BYTES]u8) []const u8 { fn resolveCompilationDir(module: *Module, buffer: *[std.fs.max_path_bytes]u8) []const u8 {
// We fully resolve all paths at this point to avoid lack of source line info in stack // We fully resolve all paths at this point to avoid lack of source line info in stack
// traces or lack of debugging information which, if relative paths were used, would // traces or lack of debugging information which, if relative paths were used, would
// be very location dependent. // be very location dependent.
@ -2804,7 +2804,7 @@ fn genIncludeDirsAndFileNames(self: *Dwarf, arena: Allocator) !struct {
const dir_path = std.fs.path.dirname(full_path) orelse "."; const dir_path = std.fs.path.dirname(full_path) orelse ".";
const sub_file_path = std.fs.path.basename(full_path); const sub_file_path = std.fs.path.basename(full_path);
// https://github.com/ziglang/zig/issues/19353 // https://github.com/ziglang/zig/issues/19353
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [std.fs.max_path_bytes]u8 = undefined;
const resolved = if (!std.fs.path.isAbsolute(dir_path)) const resolved = if (!std.fs.path.isAbsolute(dir_path))
std.posix.realpath(dir_path, &buffer) catch dir_path std.posix.realpath(dir_path, &buffer) catch dir_path
else else

View File

@ -1831,7 +1831,7 @@ fn parseLdScript(self: *Elf, lib: SystemLib) ParseError!void {
break :success; break :success;
} }
} else { } else {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
if (fs.realpath(scr_obj.path, &buffer)) |path| { if (fs.realpath(scr_obj.path, &buffer)) |path| {
test_path.clearRetainingCapacity(); test_path.clearRetainingCapacity();
try test_path.writer().writeAll(path); try test_path.writer().writeAll(path);
@ -3706,7 +3706,7 @@ fn sortInitFini(self: *Elf) !void {
} }
const default: i32 = if (is_ctor_dtor) -1 else std.math.maxInt(i32); const default: i32 = if (is_ctor_dtor) -1 else std.math.maxInt(i32);
const name = atom_ptr.name(self); const name = atom_ptr.name(self);
var it = mem.splitBackwards(u8, name, "."); var it = mem.splitBackwardsScalar(u8, name, '.');
const priority = std.fmt.parseUnsigned(u16, it.first(), 10) catch default; const priority = std.fmt.parseUnsigned(u16, it.first(), 10) catch default;
break :blk priority; break :blk priority;
}; };

View File

@ -1230,7 +1230,7 @@ fn parseDependentDylibs(self: *MachO) !void {
const prefix = eatPrefix(rpath, "@loader_path/") orelse rpath; const prefix = eatPrefix(rpath, "@loader_path/") orelse rpath;
const rel_path = try fs.path.join(arena, &.{ prefix, path }); const rel_path = try fs.path.join(arena, &.{ prefix, path });
try checked_paths.append(rel_path); try checked_paths.append(rel_path);
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
const full_path = fs.realpath(rel_path, &buffer) catch continue; const full_path = fs.realpath(rel_path, &buffer) catch continue;
break :full_path try arena.dupe(u8, full_path); break :full_path try arena.dupe(u8, full_path);
} }
@ -1243,7 +1243,7 @@ fn parseDependentDylibs(self: *MachO) !void {
} }
try checked_paths.append(try arena.dupe(u8, id.name)); try checked_paths.append(try arena.dupe(u8, id.name));
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [fs.max_path_bytes]u8 = undefined;
if (fs.realpath(id.name, &buffer)) |full_path| { if (fs.realpath(id.name, &buffer)) |full_path| {
break :full_path try arena.dupe(u8, full_path); break :full_path try arena.dupe(u8, full_path);
} else |_| { } else |_| {

View File

@ -831,7 +831,7 @@ pub const Id = struct {
var out: u32 = 0; var out: u32 = 0;
var values: [3][]const u8 = undefined; var values: [3][]const u8 = undefined;
var split = mem.split(u8, string, "."); var split = mem.splitScalar(u8, string, '.');
var count: u4 = 0; var count: u4 = 0;
while (split.next()) |value| { while (split.next()) |value| {
if (count > 2) { if (count > 2) {

View File

@ -365,7 +365,7 @@ fn putFn(self: *Plan9, decl_index: InternPool.DeclIndex, out: FnDeclOutput) !voi
try a.writer().writeInt(u16, 1, .big); try a.writer().writeInt(u16, 1, .big);
// getting the full file path // getting the full file path
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
const full_path = try std.fs.path.join(arena, &.{ const full_path = try std.fs.path.join(arena, &.{
file.mod.root.root_dir.path orelse try std.posix.getcwd(&buf), file.mod.root.root_dir.path orelse try std.posix.getcwd(&buf),
file.mod.root.sub_path, file.mod.root.sub_path,

View File

@ -192,7 +192,7 @@ pub fn parseObject(archive: Archive, wasm_file: *const Wasm, file_offset: u32) !
const object_name = try archive.parseName(header); const object_name = try archive.parseName(header);
const name = name: { const name = name: {
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [std.fs.max_path_bytes]u8 = undefined;
const path = try std.posix.realpath(archive.name, &buffer); const path = try std.posix.realpath(archive.name, &buffer);
break :name try std.fmt.allocPrint(gpa, "{s}({s})", .{ path, object_name }); break :name try std.fmt.allocPrint(gpa, "{s}({s})", .{ path, object_name });
}; };

View File

@ -10,7 +10,7 @@ pub fn main() !void {
var self_exe = try std.fs.openSelfExe(.{}); var self_exe = try std.fs.openSelfExe(.{});
defer self_exe.close(); defer self_exe.close();
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buf: [std.fs.max_path_bytes]u8 = undefined;
const self_exe_path = try std.os.getFdPath(self_exe.handle, &buf); const self_exe_path = try std.os.getFdPath(self_exe.handle, &buf);
try std.testing.expectEqualStrings(self_exe_path, self_path); try std.testing.expectEqualStrings(self_exe_path, self_path);

View File

@ -32,7 +32,7 @@ pub fn main() !void {
} }
break :seed try std.fmt.parseUnsigned(u64, args[3], 10); break :seed try std.fmt.parseUnsigned(u64, args[3], 10);
}; };
var random = std.rand.DefaultPrng.init(seed); var random = std.Random.DefaultPrng.init(seed);
const rand = random.random(); const rand = random.random();
// If the seed was not given via the CLI, then output the // If the seed was not given via the CLI, then output the
@ -72,7 +72,7 @@ pub fn main() !void {
} }
} }
fn randomCommandLineW(allocator: Allocator, rand: std.rand.Random) ![:0]const u16 { fn randomCommandLineW(allocator: Allocator, rand: std.Random) ![:0]const u16 {
const Choice = enum { const Choice = enum {
backslash, backslash,
quote, quote,

View File

@ -27,7 +27,7 @@ pub fn main() anyerror!void {
}; };
break :seed try std.fmt.parseUnsigned(u64, seed_arg, 10); break :seed try std.fmt.parseUnsigned(u64, seed_arg, 10);
}; };
var random = std.rand.DefaultPrng.init(seed); var random = std.Random.DefaultPrng.init(seed);
const rand = random.random(); const rand = random.random();
// If the seed was not given via the CLI, then output the // If the seed was not given via the CLI, then output the
@ -109,7 +109,7 @@ fn testExecBat(allocator: std.mem.Allocator, bat: []const u8, args: []const []co
} }
} }
fn randomArg(allocator: Allocator, rand: std.rand.Random) ![]const u8 { fn randomArg(allocator: Allocator, rand: std.Random) ![]const u8 {
const Choice = enum { const Choice = enum {
backslash, backslash,
quote, quote,