-
Notifications
You must be signed in to change notification settings - Fork 2
/
ringbuf.lua
51 lines (45 loc) · 859 Bytes
/
ringbuf.lua
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
local ringbuf = safeinit(...)
ringbuf.cap = 0
ringbuf.first = 1
ringbuf.last = 0
function ringbuf:new(capacity)
return setmetatable({cap=capacity, first=1, last=0}, {__index=self})
end
function ringbuf:push(el)
if self.last == 0 then
self.last = 1
elseif self.last == self.cap then
self.last = 1
self.first = 2
else
self.last = self.last + 1
if self.last == self.first then
if self.first == self.cap then
self.first = 1
else
self.first = self.last + 1
end
end
end
self[self.last] = el
end
function ringbuf:iter()
local i = self.first
local done = false
return function()
if done then return nil end
local el = self[i]
if i == self.last then
done = true
elseif i == self.cap then
i = 1
else
i = i + 1
end
return el
end
end
function ringbuf:full()
return #self == self.cap
end
return ringbuf