Skip to content

Commit 514c948

Browse files
committed
expanduser: improve efficiency
1 parent 24631f8 commit 514c948

File tree

2 files changed

+29
-7
lines changed

2 files changed

+29
-7
lines changed

+stdlib/expanduser.m

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,45 @@
1313
use_java (1,1) logical = false
1414
end
1515

16-
e = p;
16+
e = stdlib.drop_slash(p);
1717

18-
19-
if ~startsWith(e, "~") || (strlength(e) > 1 && ~startsWith(e, "~/"))
18+
L = stdlib.len(e);
19+
if ~L
2020
return
2121
end
2222

23+
if ischar(e)
24+
if e(1) ~= '~' || (L > 1 && e(1) == '~' && e(2) ~= '/')
25+
return
26+
end
27+
else
28+
if ~startsWith(e, "~") || (L > 1 && ~startsWith(e, "~/"))
29+
return
30+
end
31+
end
32+
2333
home = stdlib.homedir(use_java);
2434

2535
if ~isempty(home)
2636
d = home;
27-
if strlength(e) < 2
37+
if L < 2
2838
e = d;
2939
return
3040
end
3141

32-
e = d + "/" + strip(extractAfter(e, 1), "left", "/");
42+
if ischar(e)
43+
e = strcat(d, '/', e(3:end));
44+
else
45+
e = d + "/" + extractAfter(e, 2);
46+
end
3347
end
3448

35-
end %function
49+
end
50+
51+
52+
%!assert(expanduser('',0), '')
53+
%!assert(expanduser("~",0), homedir(0))
54+
%!assert(expanduser("~/",0), homedir(0))
55+
%!assert(expanduser("~user",0), "~user")
56+
%!assert(expanduser("~user/",0), "~user")
57+
%!assert(expanduser("~///c",0), strcat(homedir(0), "/c"))

test/TestFileImpure.m

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
cwd = fileparts(mfilename("fullpath"));
2929
top = fullfile(cwd, "..");
3030
addpath(top)
31-
p_expand = {{"", ""}, {"~abc", "~abc"}, {"~", stdlib.homedir()}, {"~/foo", stdlib.homedir() + "/foo"}};
31+
p_expand = {{"", ""}, {"~abc", "~abc"}, {"~", stdlib.homedir()}, {"~/foo", stdlib.homedir() + "/foo"}, {'~/////c', stdlib.homedir() + "/c"}};
3232
end
3333
end
3434

0 commit comments

Comments
 (0)