Skip to content

Commit 8346bae

Browse files
committed
expanduser: simpler, faster
1 parent 65bf28e commit 8346bae

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

+stdlib/expanduser.m

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,25 @@
1414
p {mustBeTextScalar}
1515
end
1616

17-
e = char(p);
1817

19-
L = length(e);
20-
if L == 0 || e(1) ~= '~' || (L > 1 && ~startsWith(e(1:2), {'~/', ['~', filesep()]}))
21-
% noop
18+
pat = ['~[/\', filesep(), ']+|^~$'];
19+
20+
[i0, i1] = regexp(p, pat, 'once');
21+
22+
if isempty(i0)
23+
% no leading ~ or it's ~user, which we don't handle
24+
e = p;
25+
return
26+
end
27+
28+
home = stdlib.homedir();
29+
30+
if i1 - i0 == 0 || strlength(p) == i1
31+
e = home;
32+
elseif isstring(p)
33+
e = strjoin([home, extractAfter(p, i1)], filesep());
2234
else
23-
home = stdlib.homedir();
24-
if isempty(home)
25-
% noop
26-
elseif L < 2
27-
e = home;
28-
else
29-
e = fullfile(home, e(3:end));
30-
end
35+
e = strjoin({home, p(i1:end)}, filesep());
3136
end
3237

3338
if isstring(p)

test/TestExpanduser.m

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
{'~', stdlib.homedir()},...
88
{"~", string(stdlib.homedir())}, ...
99
{'~/', stdlib.homedir()},...
10-
{"~/", string(stdlib.homedir())}, ...
10+
{"~" + filesep(), string(stdlib.homedir())}, ...
1111
{"~/c", fullfile(stdlib.homedir(), "c")}, ...
12-
{"~//c", fullfile(stdlib.homedir(), "c")}};
12+
{"~//c", fullfile(stdlib.homedir(), "c")}, ...
13+
{"~" + filesep() + "c", fullfile(stdlib.homedir(), "c")}};
1314
end
1415

1516
methods(Test, TestTags="impure")

0 commit comments

Comments
 (0)