about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2023-01-13 09:10:48 -0800
committerKartik K. Agaram <vc@akkartik.com>2023-01-13 09:10:48 -0800
commit22bf3da7de9074c6b99d8e43e3ab1772aed7b059 (patch)
tree1f6590d5b3aba69f5a63d8cf93dbd5207a8d8c37
parente8ec87255f94db9c6f1a0db10449f6304440a350 (diff)
downloadview.love-22bf3da7de9074c6b99d8e43e3ab1772aed7b059.tar.gz
reduce use of rfind
-rw-r--r--colorize.lua16
-rw-r--r--search.lua2
-rw-r--r--text.lua24
3 files changed, 28 insertions, 14 deletions
diff --git a/colorize.lua b/colorize.lua
index 6c2057c..e42630a 100644
--- a/colorize.lua
+++ b/colorize.lua
@@ -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
diff --git a/search.lua b/search.lua
index 37306f8..f7d4732 100644
--- a/search.lua
+++ b/search.lua
@@ -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()
diff --git a/text.lua b/text.lua
index 8232335..386553f 100644
--- a/text.lua
+++ b/text.lua
@@ -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