summaryrefslogtreecommitdiffstats
path: root/lem/streams/queue.lua
blob: 7672798873ce3efb733de937b4de41344e34dc86 (plain) (blame)
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
--
-- This file is part of lem-streams.
-- Copyright 2011 Emil Renner Berthing
--
-- lem-streams is free software: you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- lem-streams is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with lem-streams.  If not, see <http://www.gnu.org/licenses/>.
--

local utils = require 'lem.utils'

local setmetatable = setmetatable
local thisthread, suspend, resume
	= utils.thisthread, utils.suspend, utils.resume

local QOStream = {}
QOStream.__index = QOStream

function QOStream:closed(...)
	return self.stream:closed(...)
end

function QOStream:interrupt(...)
	return self.stream:interrupt(...)
end

function QOStream:close(...)
	return self.stream:close(...)
end

function QOStream:write(...)
	local nxt = self.next
	if nxt == 0 then
		nxt = 1
		self.next = 1
	else
		local me = nxt

		self[me] = thisthread()
		nxt = #self+1
		self.next = nxt
		suspend()
		self[me] = nil
	end

	local ok, err = self.stream:write(...)

	nxt = self[nxt]
	if nxt then
		resume(nxt)
	else
		self.next = 0
	end

	if not ok then return nil, err end
	return ok
end

local function wrap(stream, ...)
	if not stream then return stream, ... end
	return setmetatable({ stream = stream, next = 0 }, QOStream)
end

return {
	QOStream = QOStream,
	wrap = wrap,
}

-- vim: set ts=2 sw=2 noet: