1
0
mirror of https://github.com/SpaceVim/SpaceVim.git synced 2025-02-03 14:50:04 +08:00
SpaceVim/bundle/nvim-cmp/lua/cmp/utils/cache.lua

61 lines
1.1 KiB
Lua
Raw Normal View History

---@class cmp.Cache
---@field public entries any
local cache = {}
cache.new = function()
local self = setmetatable({}, { __index = cache })
self.entries = {}
return self
end
---Get cache value
2023-06-08 21:15:37 +08:00
---@param key string|string[]
---@return any|nil
cache.get = function(self, key)
key = self:key(key)
if self.entries[key] ~= nil then
return self.entries[key]
end
return nil
end
---Set cache value explicitly
2023-06-08 21:15:37 +08:00
---@param key string|string[]
---@vararg any
cache.set = function(self, key, value)
key = self:key(key)
self.entries[key] = value
end
---Ensure value by callback
2023-06-08 21:15:37 +08:00
---@generic T
---@param key string|string[]
---@param callback fun(): T
---@return T
cache.ensure = function(self, key, callback)
local value = self:get(key)
if value == nil then
local v = callback()
self:set(key, v)
return v
end
return value
end
---Clear all cache entries
cache.clear = function(self)
self.entries = {}
end
---Create key
2023-06-08 21:15:37 +08:00
---@param key string|string[]
---@return string
cache.key = function(_, key)
if type(key) == 'table' then
return table.concat(key, ':')
end
return key
end
return cache