Skip to content

Commit

Permalink
perf(tools/string): a way faster strip function
Browse files Browse the repository at this point in the history
### Summary

In #13168 I made this already faster,
but this time I managed to make it a way faster.

Signed-off-by: Aapo Talvensaari <[email protected]>
  • Loading branch information
bungle committed Feb 10, 2025
1 parent 04f8094 commit 44f4eb2
Showing 1 changed file with 14 additions and 22 deletions.
36 changes: 14 additions & 22 deletions kong/tools/string.lua
Original file line number Diff line number Diff line change
Expand Up @@ -45,34 +45,26 @@ _M.strip = function(value)
return ""
end

local len = #value
local s = 1 -- position of the leftmost non-whitespace char
for i = 1, len do
local b = byte(value, i)
if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then
s = s + 1
else
break
end
end

if s > len then
::spos::
local b = byte(value, s)
if not b then -- reached the end of the all whitespace string
return ""
end
if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then
s = s + 1
goto spos
end

local e = len -- position of the rightmost non-whitespace char
if s < e then
for i = e, 1, -1 do
local b = byte(value, i)
if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then
e = e - 1
else
break
end
end
local e = -1 -- position of the rightmost non-whitespace char
::epos::
b = byte(value, e)
if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then
e = e - 1
goto epos
end

if s ~= 1 or e ~= len then
if s ~= 1 or e ~= -1 then
value = sub(value, s, e)
end

Expand Down

0 comments on commit 44f4eb2

Please sign in to comment.