X-Git-Url: https://git.enpas.org/?a=blobdiff_plain;f=util%2Fset.lua;h=e4cc2dffbd428b6be84c2ec749ba0cd2156b67b3;hb=6a6712b24e5f780549692190e0819e2d2622faa8;hp=f550a721c1cb297cf037ff70a1f92f4c0796b6a4;hpb=556c77818f385198e236758f5650cafcd4870dba;p=prosody.git diff --git a/util/set.lua b/util/set.lua index f550a721..e4cc2dff 100644 --- a/util/set.lua +++ b/util/set.lua @@ -1,10 +1,68 @@ -local ipairs, pairs = - ipairs, pairs; +-- Prosody IM +-- Copyright (C) 2008-2010 Matthew Wild +-- Copyright (C) 2008-2010 Waqas Hussain +-- +-- This project is MIT/X11 licensed. Please see the +-- COPYING file in the source package for more information. +-- + +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 +99,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 +149,8 @@ function intersection(set1, set2) return set; end +function xor(set1, set2) + return union(set1, set2) - intersection(set1, set2); +end + return _M;