summaryrefslogtreecommitdiffstatshomepage
path: root/3rdparty/genie/src/base/set.lua
blob: 04936560d408459fc8d5de920229ed329c9fa640 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Set_mt = {}

function Set(t)
	local set = {}
	for k, l in ipairs(t) do 
		set[l] = true 
	end
	setmetatable(set, Set_mt)
	return set
end

function Set_mt.union(a, b)
	local res = Set{}
	for k in pairs(a) do res[k] = true end
	for k in pairs(b) do res[k] = true end
	return res
end

function Set_mt.intersection(a, b)
	local res = Set{}
	for k in pairs(a) do
		res[k] = b[k]
	end
	return res
end

local function get_cache(a)
	if not rawget(a, "__cache") then
		rawset(a, "__cache", Set_mt.totable(a))
	end
	return rawget(a, "__cache")
end

function Set_mt.len(a)
	return #get_cache(a)
end

function Set_mt.implode(a, sep)
	return table.concat(get_cache(a), sep)
end

function Set_mt.totable(a)
	local res = {}
	for k in pairs(a) do
		table.insert(res, k)
	end
	return res
end

function Set_mt.difference(a, b)
	if getmetatable(b) ~= Set_mt then
		if type(b) ~= "table" then
			error(type(b).." is not a Set or table")
		end
		b=Set(b)
	end

	local res = Set{}
	for k in pairs(a) do
		res[k] = not b[k] or nil
	end
	rawset(res, "__cache", nil)
	return res
end

function Set_mt.__index(a, i)
	if type(i) == "number" then
		return get_cache(a)[i]
	end
	return Set_mt[i] or rawget(a, i)
end

Set_mt.__add = Set_mt.union
Set_mt.__mul = Set_mt.intersection
Set_mt.__sub = Set_mt.difference
Set_mt.__len = Set_mt.len
Set_mt.__concat = Set_mt.implode