Skip to content

Commit

Permalink
non-java normalize, more than 10x faster
Browse files Browse the repository at this point in the history
  • Loading branch information
scivision committed Oct 2, 2024
1 parent a17439a commit 23432a3
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 5 deletions.
2 changes: 1 addition & 1 deletion +stdlib/canonical.m
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
else
% for non-existing path, return normalized relative path
% like C++ filesystem weakly_canonical()
c = stdlib.normalize(c);
c = stdlib.normalize(c, use_java);
return
end
end
Expand Down
46 changes: 44 additions & 2 deletions +stdlib/normalize.m
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function n = normalize(p)
function n = normalize(p, use_java)
%% normalize(p)
% normalize(p) remove redundant elements of path p
% path need not exist, normalized path is returned
Expand All @@ -10,9 +10,51 @@
% https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/Path.html#normalize()
arguments
p (1,1) string
use_java (1,1) logical = false
end

n = stdlib.posix(java.io.File(p).toPath().normalize());
if use_java
n = stdlib.posix(java.io.File(p).toPath().normalize());
else

n = stdlib.posix(p);

% use split to remove /../ and /./ and duplicated /
parts = split(n, "/");
i0 = 1;
if startsWith(n, "/")
n = "/";
elseif ispc && strlength(n) >= 2 && isletter(extractBetween(n, 1, 1)) && extractBetween(n, 2, 2) == ":"
n = parts(1);
i0 = 2;
else
n = "";
end

for i = i0:length(parts)
if parts(i) == ".."
if n == ""
n = parts(i);
elseif endsWith(n, "..")
n = n + "/" + parts(i);
else
j = strfind(n, "/");
if isempty(j)
n = "";
else
n = extractBefore(n, j(end));
end
end
elseif all(parts(i) ~= [".", ""])
if n == ""
n = parts(i);
else
n = n + "/" + parts(i);
end
end
end

end

if(strlength(n) == 0), n = "."; end

Expand Down
4 changes: 2 additions & 2 deletions +stdlib/relative_to.m
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
end

% must remove trailing slashes
base = stdlib.normalize(base);
other = stdlib.normalize(other);
base = stdlib.normalize(base, true);
other = stdlib.normalize(other, true);

if base == other
r = ".";
Expand Down

0 comments on commit 23432a3

Please sign in to comment.