modlib/hashlist.lua

93 lines
1.7 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-12-23 20:09:21 +01:00
local index = 0
2021-07-14 11:51:47 +02:00
return function()
2021-12-23 20:09:21 +01:00
index = index + 1
2021-07-14 11:51:47 +02:00
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-12-23 20:09:21 +01:00
local index = self.length + 1
2021-07-14 11:51:47 +02:00
return function()
2021-12-23 20:09:21 +01:00
index = index - 1
2021-07-14 11:51:47 +02:00
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()
2021-12-27 20:09:26 +01:00
self.length = self.length - 1
2021-07-14 11:51:47 +02:00
self.head = self.head + 1
self[self.head] = nil
return value
2021-07-11 16:52:41 +02:00
end
return list