util.queue: Small fast FIFO/ringbuffer/queue library
[prosody.git] / util / queue.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2015 Matthew Wild
3 -- Copyright (C) 2008-2015 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 -- Small ringbuffer library (i.e. an efficient FIFO queue with a size limit)
10 -- (because unbounded dynamically-growing queues are a bad thing...)
11
12 local have_utable, utable = pcall(require, "util.table"); -- For pre-allocation of table
13
14 local function new(size)
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
20         return {
21                 size = size;
22                 count = function (self) return items; end;
23                 push = function (self, item)
24                         if items >= size then
25                                 return nil, "queue full";
26                         end
27                         t[head] = item;
28                         items = items + 1;
29                         head = (head%size)+1;
30                         return true;
31                 end;
32                 pop = function (self)
33                         if items == 0 then
34                                 return nil;
35                         end
36                         local item;
37                         item, t[tail] = t[tail], 0;
38                         tail = (tail%size)+1;
39                         items = items - 1;
40                         return item;
41                 end;
42                 peek = function (self)
43                         if items == 0 then
44                                 return nil;
45                         end
46                         return t[tail];
47                 end;
48         };
49 end
50
51 return {
52         new = new;
53 };
54