robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
3.8 KiB130 linesraw
1local F = vim.F
2local new_event = require('vim.async._event')
3
4local pcall = pcall
5do
6  local ok, coxpcall = pcall(require, 'coxpcall')
7  if ok and type(coxpcall) == 'table' and type(coxpcall.pcall) == 'function' then
8    pcall = coxpcall.pcall
9  end
10end
11local validate = vim.validate
12
13--- A semaphore manages an internal permit counter. [Semaphore:acquire()]
14--- consumes one permit and [Semaphore:release()] returns one permit. If no
15--- permits are available, `acquire()` suspends the current task until another
16--- task releases one.
17---
18--- The preferred way to use a Semaphore is with the `with()` method, which
19--- automatically acquires and releases the semaphore around a function call.
20--- This is useful for limiting sections that start external work and then
21--- await it, such as file reads, requests, or subprocesses.
22---
23--- ```lua
24--- local async = vim.async
25---
26--- async.run(function()
27---   local limit = async.semaphore(4)
28---   local tasks = {}
29---
30---   for _, path in ipairs(paths) do
31---     table.insert(tasks, async.run(function()
32---       return limit:with(function()
33---         return read_file(path)
34---       end)
35---     end))
36---   end
37---
38---   local next_task = async.iter(tasks)
39---   while true do
40---     local task = next_task()
41---     if task == nil then
42---       break
43---     end
44---     async.await(task)
45---   end
46--- end)
47--- ```
48--- @class vim.async.Semaphore
49--- @field private _permits integer
50--- @field private _max_permits integer
51--- @field package _event vim.async.Event
52local Semaphore = {}
53Semaphore.__index = Semaphore
54
55--- Executes a function while holding one semaphore permit.
56---
57--- This acquires the semaphore before running the function and releases it
58--- after the function completes, even if it errors or the current task is
59--- closed.
60--- @async
61--- @generic R
62--- @param fn async fun(): R... # Function to execute within the semaphore's context.
63--- @return R... # Result(s) of the executed function.
64function Semaphore:with(fn)
65  self:acquire()
66  -- This pcall is only a try/finally guard for release(); all errors are
67  -- immediately rethrown so it is not an async recovery boundary.
68  local r = F.pack_len(pcall(fn))
69  self:release()
70  local stat = r[1]
71  if not stat then
72    local err = r[2]
73    error(err, 0)
74  end
75  return unpack(r, 2, r.n)
76end
77
78--- Acquire a semaphore permit.
79---
80--- If the internal counter is greater than zero, decrement it by `1` and
81--- return immediately. If it is `0`, wait until [Semaphore:release()] is
82--- called.
83--- @async
84function Semaphore:acquire()
85  self._event:wait()
86  self._permits = self._permits - 1
87  assert(self._permits >= 0, 'Semaphore value is negative')
88  if self._permits == 0 then
89    self._event:clear()
90  end
91end
92
93--- Release a semaphore permit.
94---
95--- Increments the internal counter by `1` and can wake a task waiting in
96--- [Semaphore:acquire()].
97---
98--- Calling this more times than permits were acquired raises an error.
99function Semaphore:release()
100  if self._permits >= self._max_permits then
101    error('Semaphore value is greater than max permits', 2)
102  end
103  self._permits = self._permits + 1
104  self._event:set(1)
105end
106
107--- Create an async semaphore that allows up to a given number of acquisitions.
108---
109--- Prefer [Semaphore:with()] for most uses so permits are released reliably.
110--- Use [Semaphore:acquire()] and [Semaphore:release()] directly only when the
111--- acquire and release points cannot be expressed as one function call.
112--- @param permits? integer (default: 1)
113--- @return vim.async.Semaphore
114local function new_semaphore(permits)
115  validate('permits', permits, 'number', true)
116  permits = permits or 1
117  if permits < 1 or permits % 1 ~= 0 then
118    error('permits: expected positive integer', 2)
119  end
120
121  local obj = setmetatable({
122    _max_permits = permits,
123    _permits = permits,
124    _event = new_event(),
125  }, Semaphore)
126  obj._event:set()
127  return obj
128end
129
130return new_semaphore