Comparison

util/queue.lua @ 6731:d4a6c9ee4bc5

util.queue: Allow optional wrap-around when pushing, overwriting oldest unread item
author Matthew Wild <mwild1@gmail.com>
date Wed, 03 Jun 2015 15:51:07 +0100
parent 6678:343ca80ceb36
child 6911:56c9bc4ba247
comparison
equal deleted inserted replaced
6730:7889515bac86 6731:d4a6c9ee4bc5
9 -- Small ringbuffer library (i.e. an efficient FIFO queue with a size limit) 9 -- Small ringbuffer library (i.e. an efficient FIFO queue with a size limit)
10 -- (because unbounded dynamically-growing queues are a bad thing...) 10 -- (because unbounded dynamically-growing queues are a bad thing...)
11 11
12 local have_utable, utable = pcall(require, "util.table"); -- For pre-allocation of table 12 local have_utable, utable = pcall(require, "util.table"); -- For pre-allocation of table
13 13
14 local function new(size) 14 local function new(size, allow_wrapping)
15 -- Head is next insert, tail is next read 15 -- Head is next insert, tail is next read
16 local head, tail = 1, 1; 16 local head, tail = 1, 1;
17 local items = 0; -- Number of stored items 17 local items = 0; -- Number of stored items
18 local t = have_utable and utable.create(size, 0) or {}; -- Table to hold items 18 local t = have_utable and utable.create(size, 0) or {}; -- Table to hold items
19 19
20 return { 20 return {
21 size = size; 21 size = size;
22 count = function (self) return items; end; 22 count = function (self) return items; end;
23 push = function (self, item) 23 push = function (self, item)
24 if items >= size then 24 if items >= size then
25 return nil, "queue full"; 25 if allow_wrapping then
26 tail = (tail%size)+1; -- Advance to next oldest item
27 items = items - 1;
28 else
29 return nil, "queue full";
30 end
26 end 31 end
27 t[head] = item; 32 t[head] = item;
28 items = items + 1; 33 items = items + 1;
29 head = (head%size)+1; 34 head = (head%size)+1;
30 return true; 35 return true;