Software /
code /
prosody
Comparison
util/events.lua @ 3501:90c18e0355af
util.events: Event handler indices are now built lazily (faster server startup for large number of hosts).
author | Waqas Hussain <waqas20@gmail.com> |
---|---|
date | Sun, 19 Sep 2010 17:51:00 +0500 |
parent | 3500:a49ed9166820 |
child | 3776:bc4f67a0658d |
comparison
equal
deleted
inserted
replaced
3500:a49ed9166820 | 3501:90c18e0355af |
---|---|
8 | 8 |
9 | 9 |
10 local pairs = pairs; | 10 local pairs = pairs; |
11 local t_insert = table.insert; | 11 local t_insert = table.insert; |
12 local t_sort = table.sort; | 12 local t_sort = table.sort; |
13 local setmetatable = setmetatable; | |
14 local next = next; | |
13 | 15 |
14 module "events" | 16 module "events" |
15 | 17 |
16 function new() | 18 function new() |
17 local handlers = {}; | 19 local handlers = {}; |
18 local event_map = {}; | 20 local event_map = {}; |
19 local function _rebuild_index(event) -- TODO optimize index rebuilding | 21 local function _rebuild_index(handlers, event) |
20 local _handlers = event_map[event]; | 22 local _handlers = event_map[event]; |
23 if not _handlers or next(_handlers) == nil then return; end | |
21 local index = {}; | 24 local index = {}; |
22 for handler in pairs(_handlers) do | 25 for handler in pairs(_handlers) do |
23 t_insert(index, handler); | 26 t_insert(index, handler); |
24 end | 27 end |
25 t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end); | 28 t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end); |
26 handlers[event] = index; | 29 handlers[event] = index; |
30 return index; | |
27 end; | 31 end; |
32 setmetatable(handlers, { __index = _rebuild_index }); | |
28 local function add_handler(event, handler, priority) | 33 local function add_handler(event, handler, priority) |
29 local map = event_map[event]; | 34 local map = event_map[event]; |
30 if map then | 35 if map then |
31 map[handler] = priority or 0; | 36 map[handler] = priority or 0; |
32 else | 37 else |
33 map = {[handler] = priority or 0}; | 38 map = {[handler] = priority or 0}; |
34 event_map[event] = map; | 39 event_map[event] = map; |
35 end | 40 end |
36 _rebuild_index(event); | 41 handlers[event] = nil; |
37 end; | 42 end; |
38 local function remove_handler(event, handler) | 43 local function remove_handler(event, handler) |
39 local map = event_map[event]; | 44 local map = event_map[event]; |
40 if map then | 45 if map then |
41 map[handler] = nil; | 46 map[handler] = nil; |
42 _rebuild_index(event); | 47 handlers[event] = nil; |
43 end | 48 end |
44 end; | 49 end; |
45 local function add_handlers(handlers) | 50 local function add_handlers(handlers) |
46 for event, handler in pairs(handlers) do | 51 for event, handler in pairs(handlers) do |
47 add_handler(event, handler); | 52 add_handler(event, handler); |