2 -- Copyright (C) 2008-2015 Matthew Wild
3 -- Copyright (C) 2008-2015 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 -- Small ringbuffer library (i.e. an efficient FIFO queue with a size limit)
10 -- (because unbounded dynamically-growing queues are a bad thing...)
12 local have_utable
, utable
= pcall(require
, "util.table"); -- For pre-allocation of table
14 local function new(size
, allow_wrapping
)
15 -- Head is next insert, tail is next read
16 local head
, tail
= 1, 1;
17 local items
= 0; -- Number of stored items
18 local t
= have_utable
and utable
.create(size
, 0) or {}; -- Table to hold items
19 --luacheck: ignore 212/self
23 count
= function (self
) return items
; end;
24 push
= function (self
, item
)
26 if allow_wrapping
then
27 tail
= (tail
%size
)+1; -- Advance to next oldest item
30 return nil, "queue full";
43 item
, t
[tail
] = t
[tail
], 0;
48 peek
= function (self
)
54 items
= function (self
)
55 return function (_
, pos
)
59 local read_pos
= tail
+ pos
;
60 if read_pos
> self
.size
then
61 read_pos
= (read_pos
%size
);
63 return pos
+1, t
[read_pos
];
66 consume
= function (self
)
67 return self
.pop
, self
;