about summary refs log tree commit diff
path: root/fifo.lua
blob: f3a3d103a0a60073674ae273299fc838fc7bd47b (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
local condition = require("cqueues.condition")

local fifo = {}

function fifo.new()
	return setmetatable({ cond = condition.new() }, { __index = fifo })
end

function fifo.signal(f)
	f.cond:signal()
end

function fifo.get(f)
	while not f.head do
		f.cond:wait()
	end

	local data = f.head.data
	f.head = f.head.tail
	return data
end

function fifo.put(f, data)
	local tail = f.head
	while tail and tail.tail do tail = tail.tail end
	if tail then
		tail.tail = { data = data }
	else
		f.head = { data = data }
	end
	fifo.signal(f)
end

function fifo.iter(f)
	return function () return fifo.get(f) end
end

return fifo