-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqueue.lua
57 lines (57 loc) · 1.02 KB
/
queue.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
52
53
54
55
56
57
return function()
local read,write,cap=1,1,64
local q={}
local function size()
local sz=write-read
if sz>=0 then return sz,cap end
return cap+sz,cap
end
local function pop()
local val
if read==write then return end
val,q[read]=q[read],nil
read=read+1
if read>cap then read=1 end
return val
end
local function top()
if read==write then return end
local val=q[read]
return val
end
local function push(val)
q[write]=val
write=write+1
if write>cap then write=1 end
if write==read then
local oq=q
local oread,owrite,ocap=read,write,cap
read,write,cap=1,1,ocap*2
q={}
for i=oread,ocap do
push(oq[i])
end
for i=1,owrite-1 do
push(oq[i])
end
end
end
local function pairs()
local i=0
local sz=size()
return function()
if i==sz then return end
local idx=i+read
if idx>cap then idx=idx-cap end
i=i+1
return i,q[idx]
end
end
return setmetatable({
pop=pop,
push=push,
size=size,
top=top,
--table=function() return q end,
},{__pairs=pairs})
end