Skip to content

Commit 156e914

Browse files
committed
expanduser: simpler, faster
1 parent 0cad3e8 commit 156e914

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

+stdlib/expanduser.m

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,24 @@
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+
e = p;
23+
24+
if isempty(i0), return, end
25+
26+
home = stdlib.homedir();
27+
28+
if i1 - i0 == 0
29+
e = home;
2230
else
23-
home = stdlib.homedir();
24-
if isempty(home)
25-
% noop
26-
elseif L < 2
27-
e = home;
31+
if isstring(p)
32+
e = strjoin([home, extractAfter(p, i1)], filesep());
2833
else
29-
e = fullfile(home, e(3:end));
34+
e = strjoin({home, e(i1:end)}, filesep());
3035
end
3136
end
3237

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)