VoxeLibre/mods/CORE/vl_scheduler/fifo.lua

56 lines
956 B
Lua
Raw Normal View History

local mod = vl_scheduler
2024-04-08 10:45:53 +02:00
function Class()
local cls = {}
cls.mt = { __index = cls }
function cls:new(...)
local inst = setmetatable({}, cls.mt)
local construct = inst.construct
if construct then inst:construct(...) end
return inst
end
return cls
end
-- Amoritized O(1) insert/delete functional First In, First Out (FIFO) queue
local fifo = Class()
mod.fifo = fifo
function fifo:insert(node)
if not node then return end
node.next = self.inbox
self.inbox = node
end
function fifo:insert_many(nodes)
while nodes do
local node = nodes
nodes = nodes.next
node.next = self.inbox
self.inbox = node.next
end
2024-04-08 10:45:53 +02:00
end
function fifo:get()
2024-04-08 10:45:53 +02:00
if not fifo.outbox then
-- reverse inbox
local iter = self.inbox
self.inbox = nil
2024-04-08 10:45:53 +02:00
while iter do
local i = iter
iter = iter.next
i.next = self.outbox
self.outbox = i
2024-04-08 10:45:53 +02:00
end
end
local res = self.outbox
2024-04-08 10:45:53 +02:00
if res then
self.outbox = res.next
2024-04-08 10:45:53 +02:00
res.next = nil
end
return res
end