Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(tools/string): a way faster strip function #14253

Merged
merged 1 commit into from
Feb 14, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading