Comparison

util/queue.lua @ 6745:6728ad041761

Merge 0.10->trunk
author Kim Alvefur <zash@zash.se>
date Thu, 25 Jun 2015 18:57:43 +0200
parent 6731:d4a6c9ee4bc5
child 6911:56c9bc4ba247
comparison
equal deleted inserted replaced
6729:daa5c83b2879 6745:6728ad041761
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;