modlib/hashlist.lua

90 lines
1.6 KiB
Lua
Raw Normal View History

2021-07-11 16:52:41 +02:00
-- Localize globals
local setmetatable = setmetatable
-- Table based list, can handle at most 2^52 pushes
local list = {}
-- TODO use __len for Lua version > 5.1
local metatable = {__index = list}
list.metatable = metatable
-- Takes a list
function list:new()
2021-07-14 11:51:47 +02:00
self.head = 0
self.length = #self
return setmetatable(self, metatable)
2021-07-11 16:52:41 +02:00
end
function list:in_bounds(index)
2021-07-14 11:51:47 +02:00
return index >= 1 and index <= self.length
2021-07-11 16:52:41 +02:00
end
function list:get(index)
2021-07-14 11:51:47 +02:00
return self[self.head + index]
2021-07-11 16:52:41 +02:00
end
function list:set(index, value)
2021-07-14 11:51:47 +02:00
assert(value ~= nil)
self[self.head + index] = value
2021-07-11 16:52:41 +02:00
end
function list:len()
2021-07-14 11:51:47 +02:00
return self.length
2021-07-11 16:52:41 +02:00
end
function list:ipairs()
2021-07-14 11:51:47 +02:00
local index = 1
return function()
if index > self.length then
return
end
return index, self[self.head + index]
end
2021-07-11 16:52:41 +02:00
end
function list:rpairs()
2021-07-14 11:51:47 +02:00
local index = self.length
return function()
if index < 1 then
return
end
return index, self[self.head + index]
end
2021-07-11 16:52:41 +02:00
end
function list:push_tail(value)
2021-07-14 11:51:47 +02:00
assert(value ~= nil)
self.length = self.length + 1
self[self.head + self.length] = value
2021-07-11 16:52:41 +02:00
end
function list:get_tail()
2021-07-14 11:51:47 +02:00
return self[self.head + self.length]
2021-07-11 16:52:41 +02:00
end
function list:pop_tail()
2021-07-14 11:51:47 +02:00
if self.length == 0 then return end
local value = self:get_tail()
self[self.head + self.length] = nil
self.length = self.length - 1
return value
2021-07-11 16:52:41 +02:00
end
function list:push_head(value)
2021-07-14 11:51:47 +02:00
self[self.head] = value
self.head = self.head - 1
self.length = self.length + 1
2021-07-11 16:52:41 +02:00
end
function list:get_head()
2021-07-14 11:51:47 +02:00
return self[self.head + 1]
2021-07-11 16:52:41 +02:00
end
function list:pop_head()
2021-07-14 11:51:47 +02:00
if self.length == 0 then return end
local value = self:get_head()
self.head = self.head + 1
self[self.head] = nil
return value
2021-07-11 16:52:41 +02:00
end
return list