reduce use of rfind

This commit is contained in:
Kartik K. Agaram 2023-01-13 09:10:48 -08:00
parent e8ec87255f
commit 22bf3da7de
3 changed files with 28 additions and 14 deletions

View File

@ -60,7 +60,7 @@ function switch_color_based_on_prefix(frag)
end
frag = rtrim(frag)
for _,edge in pairs(Next_state[Current_state]) do
if edge.prefix and find(frag, edge.prefix, nil, --[[plain]] true) == 1 then
if edge.prefix and starts_with(frag, edge.prefix) then
Current_state = edge.target
break
end
@ -73,21 +73,9 @@ function switch_color_based_on_suffix(frag)
end
frag = rtrim(frag)
for _,edge in pairs(Next_state[Current_state]) do
if edge.suffix and rfind(frag, edge.suffix, nil, --[[plain]] true) == #frag - #edge.suffix + 1 then
if edge.suffix and ends_with(frag, edge.suffix) then
Current_state = edge.target
break
end
end
end
function trim(s)
return s:gsub('^%s+', ''):gsub('%s+$', '')
end
function ltrim(s)
return s:gsub('^%s+', '')
end
function rtrim(s)
return s:gsub('%s+$', '')
end

View File

@ -116,6 +116,8 @@ function find(s, pat, i, plain)
return s:find(pat, i, plain)
end
-- TODO: avoid the expensive reverse() operations
-- Particularly if we only care about literal matches, we don't need all of string.find
function rfind(s, pat, i, plain)
if s == nil then return end
local rs = s:reverse()

View File

@ -1001,3 +1001,27 @@ end
function rtrim(s)
return s:gsub('%s+$', '')
end
function starts_with(s, prefix)
if #s < #prefix then
return false
end
for i=1,#prefix do
if s:sub(i,i) ~= prefix:sub(i,i) then
return false
end
end
return true
end
function ends_with(s, suffix)
if #s < #suffix then
return false
end
for i=0,#suffix-1 do
if s:sub(#s-i,#s-i) ~= suffix:sub(#suffix-i,#suffix-i) then
return false
end
end
return true
end