From 54251356a23468136f6226134b0f8524a6ae3523 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20Sloth=20T=C3=B8nnesen?= Date: Wed, 17 Jul 2019 22:08:26 +0000 Subject: initial new set support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Asbjørn Sloth Tønnesen --- lua/inet/set.lua | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) (limited to 'lua/inet/set.lua') diff --git a/lua/inet/set.lua b/lua/inet/set.lua index 5999f65..a353f30 100644 --- a/lua/inet/set.lua +++ b/lua/inet/set.lua @@ -1,3 +1,11 @@ +local core = require 'inet.core' + +local is_inet = core.is_inet + +local insert = table.insert +local remove = table.remove +local sort = table.sort + local M = {} local function table_compact(t, n) @@ -95,6 +103,7 @@ function M.iterator(set) return iter end +-- iterate over the set repeatedly function M.loopiterator(set) local orig_iter = M.iterator(set) local function iter() @@ -108,4 +117,84 @@ function M.loopiterator(set) return iter end +local inet_set = {} +inet_set.__index = inet_set + +local function check_net(self, net) + if not is_inet(net) then return nil, 'invalid net' end + local set_fam = self.family + local net_fam = net:family() + if set_fam then + if set_fam ~= net_fam then + return nil, 'invalid family' + end + else + self.family = net_fam + end + return true +end + +function inet_set:add(net)--, aggregate) + if not check_net(self, net) then return check_net(self, net) end + insert(self.nets, net) + M.aggregate(self.nets) + return true +end + +function inet_set:remove(net) + if not check_net(self, net) then return check_net(self, net) end + local nets = self.nets + local ret = false + for i=1,#nets do + local n = nets[i] + if n == net then + ret = true + remove(nets, i) + elseif n:contains(net) then + ret = true + remove(nets, i) + for j=#n+1,#net do + local sn = (net / j):network() + if sn:contains(net) then + sn = sn:flip() + end + self:add(sn) + end + end + end + return ret +end + +function inet_set:contains(net) + if not check_net(self, net) then return check_net(self, net) end + local nets = self.nets + for i=1,#nets do + local n = nets[i] + if n == net or n:contains(net) then + return true + end + end + return false +end + +function inet_set:list() + local nets = self.nets + sort(nets) + return nets +end + +function inet_set:flush() + self.nets = {} + self.family = nil + return true +end + +local function new_set() + return setmetatable({ + nets = {}, + }, inet_set) +end + +M.new = new_set + return M -- cgit v1.2.1