zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 3e7c02edc183a1b869c004d89debcefbd74bcdeb (tree)
parent a697de3eac7fb4bb09e7f2aaee18c916a4eacc07
Author: LemonBoy <thatlemon@gmail.com>
Date:   Tue,  4 Feb 2020 12:32:05 +0100

std: Fix edge case in isAbsolute fn family

* Empty strings are not considered absolute paths.
* Refactor some common code.

Closes #4382

Diffstat:
Mlib/std/fs/path.zig | 60++++++++++++++++++++----------------------------------------
1 file changed, 20 insertions(+), 40 deletions(-)

diff --git a/lib/std/fs/path.zig b/lib/std/fs/path.zig @@ -146,72 +146,51 @@ pub fn isAbsolute(path: []const u8) bool { } } -pub fn isAbsoluteW(path_w: [*:0]const u16) bool { - if (path_w[0] == '/') - return true; - - if (path_w[0] == '\\') { - return true; - } - if (path_w[0] == 0 or path_w[1] == 0 or path_w[2] == 0) { +fn isAbsoluteWindowsImpl(comptime T: type, path: []const T) bool { + if (path.len < 1) return false; - } - if (path_w[1] == ':') { - if (path_w[2] == '/') - return true; - if (path_w[2] == '\\') - return true; - } - return false; -} -pub fn isAbsoluteWindows(path: []const u8) bool { if (path[0] == '/') return true; - if (path[0] == '\\') { + if (path[0] == '\\') return true; - } - if (path.len < 3) { + + if (path.len < 3) return false; - } + if (path[1] == ':') { if (path[2] == '/') return true; if (path[2] == '\\') return true; } + return false; } -pub fn isAbsoluteWindowsC(path_c: [*:0]const u8) bool { - if (path_c[0] == '/') - return true; +pub fn isAbsoluteWindows(path: []const u8) bool { + return isAbsoluteWindowsImpl(u8, path); +} - if (path_c[0] == '\\') { - return true; - } - if (path_c[0] == 0 or path_c[1] == 0 or path_c[2] == 0) { - return false; - } - if (path_c[1] == ':') { - if (path_c[2] == '/') - return true; - if (path_c[2] == '\\') - return true; - } - return false; +pub fn isAbsoluteW(path_w: [*:0]const u16) bool { + return isAbsoluteWindowsImpl(u16, mem.toSliceConst(u16, path_w)); +} + +pub fn isAbsoluteWindowsC(path_c: [*:0]const u8) bool { + return isAbsoluteWindowsImpl(u8, mem.toSliceConst(u8, path_c)); } pub fn isAbsolutePosix(path: []const u8) bool { - return path[0] == sep_posix; + return path.len > 0 and path[0] == sep_posix; } pub fn isAbsolutePosixC(path_c: [*:0]const u8) bool { - return path_c[0] == sep_posix; + return isAbsolutePosix(mem.toSliceConst(u8, path_c)); } test "isAbsoluteWindows" { + testIsAbsoluteWindows("", false); testIsAbsoluteWindows("/", true); testIsAbsoluteWindows("//", true); testIsAbsoluteWindows("//server", true); @@ -234,6 +213,7 @@ test "isAbsoluteWindows" { } test "isAbsolutePosix" { + testIsAbsolutePosix("", false); testIsAbsolutePosix("/home/foo", true); testIsAbsolutePosix("/home/foo/..", true); testIsAbsolutePosix("bar/", false);