From e442a0ecc23d315f99f62684c6240e7c1cb6e9ce Mon Sep 17 00:00:00 2001 From: Ryan Liptak Date: Sat, 20 Dec 2025 20:18:07 -0800 Subject: [PATCH] Dir.readFile/readFileAlloc: take advantage of `.allow_directory = false` on Windows Since we know the read will fail for directories, we can take advantage of Windows being able to fail with IsDir during open to avoid needing to wait until the read to find out about the directory-ness of the file. --- lib/std/Io/Dir.zig | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/std/Io/Dir.zig b/lib/std/Io/Dir.zig index a84a20167dd82c29dde487f75d738ca992743b25..e7b18066160adf95cbace687eb00843eb9175718 100644 --- a/lib/std/Io/Dir.zig +++ b/lib/std/Io/Dir.zig @@ -633,7 +633,11 @@ pub const ReadFileError = File.OpenError || File.Reader.Error; /// * On WASI, `file_path` should be encoded as valid UTF-8. /// * On other platforms, `file_path` is an opaque sequence of bytes with no particular encoding. pub fn readFile(dir: Dir, io: Io, file_path: []const u8, buffer: []u8) ReadFileError![]u8 { - var file = try dir.openFile(io, file_path, .{}); + var file = try dir.openFile(io, file_path, .{ + // We can take advantage of this on Windows since it doesn't involve any extra syscalls, + // so we can get error.IsDir during open rather than during the read. + .allow_directory = if (native_os == .windows) false else true, + }); defer file.close(io); var reader = file.reader(io, &.{}); @@ -1217,7 +1221,11 @@ pub fn readFileAllocOptions( comptime alignment: std.mem.Alignment, comptime sentinel: ?u8, ) ReadFileAllocError!(if (sentinel) |s| [:s]align(alignment.toByteUnits()) u8 else []align(alignment.toByteUnits()) u8) { - var file = try dir.openFile(io, sub_path, .{}); + var file = try dir.openFile(io, sub_path, .{ + // We can take advantage of this on Windows since it doesn't involve any extra syscalls, + // so we can get error.IsDir during open rather than during the read. + .allow_directory = if (native_os == .windows) false else true, + }); defer file.close(io); var file_reader = file.reader(io, &.{}); return file_reader.interface.allocRemainingAlignedSentinel(gpa, limit, alignment, sentinel) catch |err| switch (err) { -- 2.54.0