Skip to content

Commit

Permalink
feat: add utils.lua
Browse files Browse the repository at this point in the history
  • Loading branch information
vm-001 committed Dec 18, 2023
1 parent 7be46c7 commit 147cfb0
Showing 1 changed file with 40 additions and 32 deletions.
72 changes: 40 additions & 32 deletions src/resty/utils.lua
Original file line number Diff line number Diff line change
@@ -1,45 +1,53 @@
local base = require("resty.core.base")
local clear_table = base.clear_tab
--[[
-- 其实可以做个兼容,这个项目不一定要依赖 luajit/openresty
-- string find 其实可以替换成其他的实现
local ok, clear_tab = pcall(require, "table.clear")
local str_byte = string.byte
local str_find = string.find
local math_min = math.min


local clear_table
do
local ok
ok, clear_table = pcall(require, "table.clear")
if not ok then
clear_tab = function (tab)
local pairs = pairs
clear_table = function (tab)
for k, _ in pairs(tab) do
tab[k] = nil
end
end
end
]]
end

local ffi = require("ffi")
local C = ffi.C
local ffi_cast = ffi.cast
local ffi_cdef = ffi.cdef
local str_byte = string.byte
local math_min = math.min

ffi_cdef[[
int memcmp(const void *s1, const void *s2, size_t n);
]]
local starts_with
do
local luajit = type(_G.jit) == "table"
if luajit then
local ffi = require "ffi"
local C = ffi.C
ffi.cdef[[
int memcmp(const void *s1, const void *s2, size_t n);
]]
starts_with = function(str, prefix, strn, prefixn)
strn = strn or #str
prefixn = prefixn or #prefix

local function starts_with(str, prefix, strn, prefixn)
strn = strn or #str
prefixn = prefixn or #prefix
if prefixn == 0 then
return true
end

if prefixn == 0 then
return true
end
if strn < prefixn then
return false
end

if strn < prefixn then
return false
local rc = C.memcmp(str, prefix, prefixn)
return rc == 0
end
else
local str_sub = string.sub
starts_with = function(str, prefix, strn, prefixn)
return str_sub(str, 1, #prefix) == prefix
end
end

-- TODO lua-resty-radixtree 里面还用到了 cast
local rc = C.memcmp(str, prefix, prefixn)
return rc == 0
--return string.sub(s, 1, #prefix) == prefix
end


Expand All @@ -58,8 +66,8 @@ end


local function has_wildcard(path)
local idx_wildcard = string.find(path, "*", 1, true)
local idx_parameter = string.find(path, ":", 1, true)
local idx_wildcard = str_find(path, "*", 1, true)
local idx_parameter = str_find(path, ":", 1, true)
return idx_wildcard or idx_parameter
end

Expand Down

0 comments on commit 147cfb0

Please sign in to comment.