Commit 64feae3ac3

Lee Cannon <leecannon@leecannon.xyz>
2020-11-08 19:06:45
Move utf8->utf16 up one level into os.zig
1 parent dbbe709
Changed files (2)
lib/std/os/windows.zig
@@ -562,28 +562,25 @@ pub const SetCurrentDirectoryError = error{
     NotDir,
     AccessDenied,
     NoDevice,
+    BadPathName,
     Unexpected,
 };
 
-pub fn SetCurrentDirectory(path_name: []const u8) SetCurrentDirectoryError!void {
-    var path_space: PathSpace = undefined;
-    path_space.len = try std.unicode.utf8ToUtf16Le(path_space.data[0..], path_name);
-    if (path_space.len > path_space.data.len) return error.NameTooLong;
-    
-    const path_len_bytes = math.cast(u16, path_space.len * 2) catch |err| switch (err) {
+pub fn SetCurrentDirectory(path_name: []const u16) SetCurrentDirectoryError!void {
+    const path_len_bytes = math.cast(u16, path_name.len * 2) catch |err| switch (err) {
         error.Overflow => return error.NameTooLong,
     };
     
     var nt_name = UNICODE_STRING{
         .Length = path_len_bytes,
         .MaximumLength = path_len_bytes,
-        .Buffer = @intToPtr([*]u16, @ptrToInt(&path_space.data)),
+        .Buffer = @intToPtr([*]u16, @ptrToInt(path_name.ptr)),
     };
     
     const rc = ntdll.RtlSetCurrentDirectory_U(&nt_name);
     switch (rc) {
         .SUCCESS => {},
-        .OBJECT_NAME_INVALID => unreachable,
+        .OBJECT_NAME_INVALID => return error.BadPathName,
         .OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
         .OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
         .NO_MEDIA_IN_DEVICE => return error.NoDevice,
lib/std/os.zig
@@ -2297,6 +2297,7 @@ pub const ChangeCurDirError = error{
     FileNotFound,
     SystemResources,
     NotDir,
+    BadPathName,
     
     /// On Windows, file paths must be valid Unicode.
     InvalidUtf8,
@@ -2308,7 +2309,11 @@ pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {
     if (builtin.os.tag == .wasi) {
         @compileError("chdir is not supported in WASI");
     } else if (builtin.os.tag == .windows) {
-        windows.SetCurrentDirectory(dir_path) catch |err| switch (err) {
+        var utf16_dir_path: [windows.PATH_MAX_WIDE]u16 = undefined;
+        const len = try std.unicode.utf8ToUtf16Le(utf16_dir_path[0..], dir_path);
+        if (len > utf16_dir_path.len) return error.NameTooLong;
+        
+        windows.SetCurrentDirectory(utf16_dir_path[0..len]) catch |err| switch (err) {
             error.NoDevice => return error.FileSystem,
             else => |e| return e,
         };