From a190582b26a82f96da7488eff37e9676cdb937bc Mon Sep 17 00:00:00 2001 From: Ryan Liptak Date: Mon, 7 Aug 2023 23:49:53 -0700 Subject: [PATCH] fs.Dir.realpathW: Reduce the number of OpenFile calls for directories `.filter = .any` can be used here to remove an unnecessary extra OpenFile call when getting the path of a directory --- lib/std/fs.zig | 12 +----------- lib/std/fs/test.zig | 19 ++++++++++++++----- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/lib/std/fs.zig b/lib/std/fs.zig index e5c2d67d67..6485fdb9c7 100644 --- a/lib/std/fs.zig +++ b/lib/std/fs.zig @@ -1568,18 +1568,8 @@ pub const Dir = struct { .share_access = share_access, .creation = creation, .io_mode = .blocking, + .filter = .any, }) catch |err| switch (err) { - error.IsDir => break :blk w.OpenFile(pathname, .{ - .dir = self.fd, - .access_mask = access_mask, - .share_access = share_access, - .creation = creation, - .io_mode = .blocking, - .filter = .dir_only, - }) catch |er| switch (er) { - error.WouldBlock => unreachable, - else => |e2| return e2, - }, error.WouldBlock => unreachable, else => |e| return e, }; diff --git a/lib/std/fs/test.zig b/lib/std/fs/test.zig index ac4163fe91..e17438d2dc 100644 --- a/lib/std/fs/test.zig +++ b/lib/std/fs/test.zig @@ -341,6 +341,8 @@ test "Dir.realpath smoke test" { // with a sharing violation. file.close(); + try tmp_dir.dir.makeDir("test_dir"); + var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); @@ -353,18 +355,25 @@ test "Dir.realpath smoke test" { // First, test non-alloc version { var buf1: [fs.MAX_PATH_BYTES]u8 = undefined; - const file_path = try tmp_dir.dir.realpath("test_file", buf1[0..]); - const expected_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_file" }); - try testing.expect(mem.eql(u8, file_path, expected_path)); + const file_path = try tmp_dir.dir.realpath("test_file", buf1[0..]); + const expected_file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_file" }); + try testing.expectEqualStrings(expected_file_path, file_path); + + const dir_path = try tmp_dir.dir.realpath("test_dir", buf1[0..]); + const expected_dir_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_dir" }); + try testing.expectEqualStrings(expected_dir_path, dir_path); } // Next, test alloc version { const file_path = try tmp_dir.dir.realpathAlloc(allocator, "test_file"); - const expected_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_file" }); + const expected_file_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_file" }); + try testing.expectEqualStrings(expected_file_path, file_path); - try testing.expect(mem.eql(u8, file_path, expected_path)); + const dir_path = try tmp_dir.dir.realpathAlloc(allocator, "test_dir"); + const expected_dir_path = try fs.path.join(allocator, &[_][]const u8{ base_path, "test_dir" }); + try testing.expectEqualStrings(expected_dir_path, dir_path); } }