2018-01-26 01:31:09 +02:00
|
|
|
local Queue = {}
|
|
|
|
|
|
|
|
function Queue.new()
|
2019-07-03 13:35:34 +02:00
|
|
|
local queue = {_head = 1, _tail = 1}
|
2018-01-26 01:31:09 +02:00
|
|
|
return queue
|
|
|
|
end
|
|
|
|
|
|
|
|
function Queue.size(queue)
|
2019-07-03 13:35:34 +02:00
|
|
|
return queue._head - queue._tail
|
2018-01-26 01:31:09 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
function Queue.push(queue, element)
|
|
|
|
local index = queue._head
|
|
|
|
queue[index] = element
|
2019-07-03 13:35:34 +02:00
|
|
|
queue._head = index + 1
|
|
|
|
end
|
|
|
|
|
|
|
|
--- Pushes the element such that it would be the next element pop'ed.
|
|
|
|
function Queue.push_to_end(queue, element)
|
|
|
|
local index = queue._tail - 1
|
|
|
|
queue[index] = element
|
|
|
|
queue._tail = index
|
2018-01-26 01:31:09 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
function Queue.peek(queue)
|
|
|
|
return queue[queue._tail]
|
|
|
|
end
|
|
|
|
|
2019-07-03 13:35:34 +02:00
|
|
|
function Queue.peek_start(queue)
|
|
|
|
return queue[queue._head - 1]
|
|
|
|
end
|
|
|
|
|
|
|
|
function Queue.peek_index(queue, index)
|
|
|
|
return queue[queue._tail + index - 1]
|
|
|
|
end
|
|
|
|
|
2018-01-26 01:31:09 +02:00
|
|
|
function Queue.pop(queue)
|
|
|
|
local index = queue._tail
|
|
|
|
|
|
|
|
local element = queue[index]
|
|
|
|
queue[index] = nil
|
|
|
|
|
2019-01-11 20:25:54 +02:00
|
|
|
if element then
|
2019-07-03 13:35:34 +02:00
|
|
|
queue._tail = index + 1
|
2019-01-11 20:25:54 +02:00
|
|
|
end
|
2019-07-03 13:35:34 +02:00
|
|
|
|
2018-01-26 01:31:09 +02:00
|
|
|
return element
|
|
|
|
end
|
|
|
|
|
2019-07-03 13:35:34 +02:00
|
|
|
function Queue.to_array(queue)
|
|
|
|
local n = 1
|
|
|
|
local res = {}
|
|
|
|
|
|
|
|
for i = queue._tail, queue._head - 1 do
|
|
|
|
res[n] = queue[i]
|
|
|
|
n = n + 1
|
|
|
|
end
|
|
|
|
|
|
|
|
return res
|
|
|
|
end
|
|
|
|
|
|
|
|
function Queue.pairs(queue)
|
|
|
|
local index = queue._tail
|
|
|
|
return function()
|
|
|
|
local element = queue[index]
|
|
|
|
|
|
|
|
if element then
|
|
|
|
local old = index
|
|
|
|
index = index + 1
|
|
|
|
return old, element
|
|
|
|
else
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-11-20 12:46:42 +02:00
|
|
|
return Queue
|