aboutsummaryrefslogtreecommitdiffstats
path: root/lua/inet/set.lua
blob: 27c938840afb10412d08cfd211baab4a572a6a94 (plain) (blame)
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
local M = {}

local function table_compact(t, n)
	-- remove nil entries, and reorder
	local i = 0
	for j=1,n do
		if t[j] then
			if i > 0 then
				t[i] = t[j]
				i = i + 1
			end
		elseif i == 0 then
			i = j
		end
	end
	if i > 0 then
		for j=i,n do
			t[j] = nil
		end
	end
end

function M.aggregate(t)
	local flag = true
	local n = #t
	for i=1,n do
		t[i] = t[i]:network()
	end
	while flag do -- loop until no aggregatable addresses are found
		flag = false
		for i=1,n do
			local ia = t[i]
			if ia then
				local ib = ia:flip() -- counterpart
				for j=1,n do
					if j ~= i then
						if ia == t[j] then
							-- duplicate found
							t[j] = nil
							flag = true
						elseif t[j] == ib then
							-- counterpart found, aggregating
							t[i] = (ia ^ -1):network()
							t[j] = nil
							flag = true
						end
					end
				end
			end
		end
	end
	table_compact(t, n)
end

return M