Skip to content

Commit f766696

Browse files
authored
perf(utils): faster split_path (#1902)
1 parent f3df514 commit f766696

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

lua/neo-tree/utils/init.lua

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1135,21 +1135,34 @@ M.split_path = function(path)
11351135
if prefix and vim.startswith(prefix, path) then
11361136
return nil, path
11371137
end
1138+
1139+
-- this is more than just a root path
11381140
if path:sub(-1) == M.path_separator then
11391141
-- trim it off
11401142
path = path:sub(1, -2)
11411143
end
11421144

1143-
local rest_of_path = prefix and path:sub(#prefix + 1) or path
1144-
local rest_parts = vim.split(rest_of_path, M.path_separator, { plain = true })
1145-
local name = table.remove(rest_parts)
1146-
local parentPath = (prefix or "") .. table.concat(rest_parts, M.path_separator)
1145+
local last_separator_index
1146+
local i = prefix and #prefix + 1 or 1
1147+
local j
1148+
repeat
1149+
j = path:find(M.path_separator, i, true)
1150+
if j then
1151+
last_separator_index = j
1152+
i = j + 1
1153+
end
1154+
until not j
11471155

1148-
if #parentPath == 0 then
1149-
return prefix, name
1156+
if not last_separator_index then
1157+
if not prefix then
1158+
return nil, path
1159+
end
1160+
return prefix, path:sub(#prefix + 1)
11501161
end
11511162

1152-
return parentPath, name
1163+
local parent_path = path:sub(1, last_separator_index - 1)
1164+
local tail = path:sub(last_separator_index + 1)
1165+
return parent_path, tail
11531166
end
11541167

11551168
---Joins arbitrary number of paths together.

tests/neo-tree/utils/path_spec.lua

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ describe("utils path functions", function()
104104

105105
-- Absolute paths
106106
assert.are.same({ "/a", "b" }, { utils.split_path("/a/b") })
107+
assert.are.same({ "/a/b/c/d", "e" }, { utils.split_path("/a/b/c/d/e") })
107108
assert.are.same({ "/", "a" }, { utils.split_path("/a") })
108109

109110
-- Edge cases

0 commit comments

Comments
 (0)