optimise tag match function

This commit is contained in:
Sarah Hoffmann
2022-11-08 10:21:44 +01:00
parent 84e5e601e1
commit 3683cf7ddc

View File

@@ -219,49 +219,58 @@ function tag_match(data)
return nil return nil
end end
local tests = {} local fullmatches = {}
local key_prefixes = {}
local key_suffixes = {}
if data.keys ~= nil then if data.keys ~= nil then
for _, key in pairs(data.keys) do for _, key in pairs(data.keys) do
if key:sub(1, 1) == '*' then if key:sub(1, 1) == '*' then
if #key > 1 then if #key > 1 then
local suffix = key:sub(2) if key_suffixes[#key - 1] == nil then
tests[#tests + 1] = function (k, v) key_suffixes[#key - 1] = {}
return k:sub(-#suffix) == suffix
end end
key_suffixes[#key - 1][key:sub(2)] = true
end end
elseif key:sub(#key, #key) == '*' then elseif key:sub(#key, #key) == '*' then
local prefix = key:sub(1, #key - 1) if key_prefixes[#key - 1] == nil then
tests[#tests + 1] = function (k, v) key_prefixes[#key - 1] = {}
return k:sub(1, #prefix) == prefix
end end
key_prefixes[#key - 1][key:sub(1, #key - 1)] = true
else else
tests[#tests + 1] = function (k, v) fullmatches[key] = true
return k == key
end
end end
end end
end end
if data.tags ~= nil then if data.tags ~= nil then
local tags = {}
for k, vlist in pairs(data.tags) do for k, vlist in pairs(data.tags) do
tags[k] = {} if fullmatches[k] == nil then
for _, v in pairs(vlist) do fullmatches[k] = {}
tags[k][v] = true for _, v in pairs(vlist) do
fullmatches[k][v] = true
end
end end
end end
tests[#tests + 1] = function (k, v)
return tags[k] ~= nil and tags[k][v] ~= nil
end
end end
return function (k, v) return function (k, v)
for _, func in pairs(tests) do if fullmatches[k] ~= nil and (fullmatches[k] == true or fullmatches[k][v] ~= nil) then
if func(k, v) then return true
end
for slen, slist in pairs(key_suffixes) do
if #k >= slen and slist[k:sub(-slen)] ~= nil then
return true return true
end end
end end
for slen, slist in pairs(key_prefixes) do
if #k >= slen and slist[k:sub(1, slen)] ~= nil then
return true
end
end
return false return false
end end
end end