词条 | Module:Sandbox/Artoria2e5/CacheUtils |
释义 | -- Cached function decorators.-- lru-- lfu-- rr local defaultsize = 128 -- An ordered dict implementation.local orderedDict = {} function orderedDict.create(argDict, argOrder) if (#dict) ~= (#order) then return nil end
-- grrr, this won't work if I want (amortized) O(1) removal -- TODO: Use a double-linked map of the form table local dict = {} local nils = {} for k, v in pairs(argDict) do dict[k] = v if v == nil then nils[k] = true end end local order = {} -- tableArray
local function len(this) return #dict end
local function newindex(this, k, v) dict[k] = v if v == nil then nils[k] = true end table.insert(order, k) end
local function leak() return dict, order, nils end
local ret = {} setmetatable(ret, { ["__len"] = len, ["__newindex"] = __newindex, ["__index"] = dict, ["__mwint__leak"] = leak, }) return ret end -- These need to go into the metatable. They interfere with indexing.function orderedDict:has(od, k) local dict, order, nils = getmetatable(od).__mwint__leak() return (dict[k] ~= nil) or (nils[k]) end function orderedDict:pop(od, k) local dict, order, nils = getmetatable(od).__mwint__leak() if orderedDict:has(od, k) then v = dict[k] table.remove(dict, k) if v == nil then table.remove(nils, k) end
else return nil, false end end local function lru_cache(func, size) size = size or defaultsize memo = OrderedDict.create()
end return { ["lru"] = lru_cache, ["_"] = { ["orderedDict"] = orderedDict } } |
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。