Skip to content

Commit ceec2e9

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

File tree

2 files changed

+18
-14
lines changed

2 files changed

+18
-14
lines changed

+stdlib/expanduser.m

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,23 @@
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;
30+
elseif isstring(p)
31+
e = strjoin([home, extractAfter(p, i1)], filesep());
2232
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
33+
e = strjoin({home, e(i1:end)}, filesep());
3134
end
3235

3336
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)