robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
2.1 KiB87 linesraw
1--- Module for private utility functions
2
3--- @alias vim.func.MemoObj { _hash: (fun(...): any), _weak: boolean?, _cache: table<any, any> }
4
5--- @param argc integer?
6--- @return fun(...): any
7local function concat_hash(argc)
8  return function(...)
9    return table.concat({ ... }, '%%', 1, argc)
10  end
11end
12
13--- @param idx integer
14--- @return fun(...): any
15local function idx_hash(idx)
16  return function(...)
17    return select(idx, ...)
18  end
19end
20
21--- @param hash integer|string|fun(...): any
22--- @return fun(...): any
23local function resolve_hash(hash)
24  if type(hash) == 'number' then
25    hash = idx_hash(hash)
26  elseif type(hash) == 'string' then
27    if hash == 'concat' then
28      hash = concat_hash()
29    else
30      local c = hash:match('^concat%-(%d+)')
31      if c then
32        hash = concat_hash(vim._assert_integer(c))
33      else
34        error('invalid value for hash: ' .. hash)
35      end
36    end
37  end
38  --- @cast hash -integer
39  return hash
40end
41
42--- @param weak boolean?
43--- @return table
44local create_cache = function(weak)
45  return setmetatable({}, {
46    __mode = weak ~= false and 'kv',
47  })
48end
49
50--- @generic F: function
51--- @param hash integer|string|fun(...): any
52--- @param fn F
53--- @param weak? boolean
54--- @return F
55return function(hash, fn, weak)
56  vim.validate('hash', hash, { 'number', 'string', 'function' })
57  vim.validate('fn', fn, 'function')
58  vim.validate('weak', weak, 'boolean', true)
59
60  --- @type vim.func.MemoObj
61  local obj = {
62    _cache = create_cache(weak),
63    _hash = resolve_hash(hash),
64    _weak = weak,
65    --- @param self vim.func.MemoObj
66    clear = function(self, ...)
67      if select('#', ...) == 0 then
68        self._cache = create_cache(self._weak)
69        return
70      end
71      local key = self._hash(...)
72      self._cache[key] = nil
73    end,
74  }
75
76  return setmetatable(obj, {
77    --- @param self vim.func.MemoObj
78    __call = function(self, ...)
79      local key = self._hash(...)
80      local cache = self._cache
81      if cache[key] == nil then
82        cache[key] = vim.F.pack_len(fn(...))
83      end
84      return vim.F.unpack_len(cache[key])
85    end,
86  })
87end