aboutsummaryrefslogtreecommitdiffstats
path: root/util
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2009-04-22 20:14:11 +0100
committerMatthew Wild <mwild1@gmail.com>2009-04-22 20:14:11 +0100
commit77195f9fb9f2092fc2ac3fc379185a9210de2a57 (patch)
treee57cf40c3f3d1cac021d60e36ddcf5d1a95f8133 /util
parent84bdf9494c891172c03f81186e0e8ff1a39364d7 (diff)
parentfc2a4159849cf5fcb2c53d4fb0c0f1a7b101d69a (diff)
downloadprosody-77195f9fb9f2092fc2ac3fc379185a9210de2a57.tar.gz
prosody-77195f9fb9f2092fc2ac3fc379185a9210de2a57.zip
Merge with 0.4.1
Diffstat (limited to 'util')
-rw-r--r--util/array.lua15
-rw-r--r--util/set.lua66
2 files changed, 76 insertions, 5 deletions
diff --git a/util/array.lua b/util/array.lua
index 9e99a3ec..072b24a7 100644
--- a/util/array.lua
+++ b/util/array.lua
@@ -52,4 +52,17 @@ function array:reverse()
end
end
-_G.array = array
+function array.collect(f, s, var)
+ local t, var = {};
+ while true do
+ var = f(s, var);
+ if var == nil then break; end
+ table.insert(t, var);
+ end
+ return setmetatable(t, array_mt);
+end
+
+_G.array = array;
+module("array");
+
+return array;
diff --git a/util/set.lua b/util/set.lua
index f550a721..84bfe8c4 100644
--- a/util/set.lua
+++ b/util/set.lua
@@ -1,10 +1,60 @@
-local ipairs, pairs =
- ipairs, pairs;
+local ipairs, pairs, setmetatable, next, tostring =
+ ipairs, pairs, setmetatable, next, tostring;
+local t_concat = table.concat;
module "set"
+local set_mt = {};
+function set_mt.__call(set, _, k)
+ return next(set._items, k);
+end
+function set_mt.__add(set1, set2)
+ return _M.union(set1, set2);
+end
+function set_mt.__sub(set1, set2)
+ return _M.difference(set1, set2);
+end
+function set_mt.__div(set, func)
+ local new_set, new_items = _M.new();
+ local items, new_items = set._items, new_set._items;
+ for item in pairs(items) do
+ if func(item) then
+ new_items[item] = true;
+ end
+ end
+ return new_set;
+end
+function set_mt.__eq(set1, set2)
+ local set1, set2 = set1._items, set2._items;
+ for item in pairs(set1) do
+ if not set2[item] then
+ return false;
+ end
+ end
+
+ for item in pairs(set2) do
+ if not set1[item] then
+ return false;
+ end
+ end
+
+ return true;
+end
+function set_mt.__tostring(set)
+ local s, items = { }, set._items;
+ for item in pairs(items) do
+ s[#s+1] = tostring(item);
+ end
+ return t_concat(s, ", ");
+end
+
+local items_mt = {};
+function items_mt.__call(items, _, k)
+ return next(items, k);
+end
+
function new(list)
- local items = {};
+ local items = setmetatable({}, items_mt);
local set = { _items = items };
function set:add(item)
@@ -41,11 +91,15 @@ function new(list)
end
end
+ function set:empty()
+ return not next(items);
+ end
+
if list then
set:add_list(list);
end
- return set;
+ return setmetatable(set, set_mt);
end
function union(set1, set2)
@@ -87,4 +141,8 @@ function intersection(set1, set2)
return set;
end
+function xor(set1, set2)
+ return union(set1, set2) - intersection(set1, set2);
+end
+
return _M;