/usr/share/lua/5.1/cqueues/promise.lua is in lua-cqueues 20161214-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | local loader = function(loader, ...)
local cqueues = require"cqueues"
local condition = require"cqueues.condition"
local auxlib = require"cqueues.auxlib"
local assert3 = auxlib.assert3
local unpack = assert(table.unpack or unpack)
local pcall = pcall
local error = error
local getmetatable = getmetatable
local tostring = auxlib.tostring
local promise = {}
promise.__index = promise -- keep things simple
function promise.new(f, ...)
local self = setmetatable({
pollfd = condition.new(),
state = "pending",
}, promise)
if f then
cqueues.running():wrap(function(f, ...)
self:set(pcall(f, ...))
end, f, ...)
end
return self
end -- promise.new
function promise.type(self)
local mt = getmetatable(self)
return (mt == promise and "promise") or nil
end -- promise.type
function promise:set(ok, ...)
assert3(self.state == "pending", "attempt to set value of resolved promise")
if not ok then
self.state = "rejected"
self.reason = ...
else
self.state = "fulfilled"
self.n = select("#", ...)
if self.n == 1 then
self.tuple = ...
else
self.tuple = { ... }
end
end
self.pollfd:signal()
self.timeout = 0
end -- promise:set
function promise:wait(timeout)
if self.state == "pending" then
self.pollfd:wait(timeout)
end
return (self.state ~= "pending" and self) or nil
end -- promise:wait
function promise:get(timeout)
self:wait(timeout)
if self.state == "fulfilled" then
if self.n == 1 then
return self.tuple
else
return unpack(self.tuple)
end
elseif self.state == "rejected" then
return error(self.reason, 2)
end
end -- promise:get
function promise:status()
return self.state
end -- promise:status
-- NOTE: Only LuaJIT supports metamethod yielding.
function promise:__tostring()
return tostring(self:get())
end -- promise:__tostring
function promise:__call()
return self:get()
end -- promise:__call
promise.loader = loader
return promise
end
return loader(loader, ...)
|