summaryrefslogtreecommitdiff
path: root/stowables-dotlocal/share/nvim/site/pack/manual/start/nvim-cmp-v0.0.1/lua/cmp/utils/cache.lua
blob: 26456ad4ba34b281115a5002a2aadfe65b844e52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
---@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
---@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
---@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
---@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
---@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