Software /
code /
prosody
Comparison
util/events.lua @ 1180:8c5d945c1f35
util.events: Much more efficient index building
author | Waqas Hussain <waqas20@gmail.com> |
---|---|
date | Sun, 17 May 2009 02:06:35 +0500 |
parent | 1175:edef0c10e076 |
child | 1181:dffbb7d1da4b |
comparison
equal
deleted
inserted
replaced
1179:503d68e7e18a | 1180:8c5d945c1f35 |
---|---|
9 | 9 |
10 function new() | 10 function new() |
11 local dispatchers = {}; | 11 local dispatchers = {}; |
12 local handlers = {}; | 12 local handlers = {}; |
13 local event_map = {}; | 13 local event_map = {}; |
14 local function _rebuild_index() -- TODO optimize index rebuilding | 14 local function _rebuild_index(event) -- TODO optimize index rebuilding |
15 for event, _handlers in pairs(event_map) do | 15 local _handlers = event_map[event]; |
16 local index = handlers[event]; | 16 local index = handlers[event]; |
17 if index then | 17 if index then |
18 for i=#index,1,-1 do index[i] = nil; end | 18 for i=#index,1,-1 do index[i] = nil; end |
19 else index = {}; handlers[event] = index; end | 19 else index = {}; handlers[event] = index; end |
20 for handler in pairs(_handlers) do | 20 for handler in pairs(_handlers) do |
21 t_insert(index, handler); | 21 t_insert(index, handler); |
22 end | |
23 t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end); | |
24 end | 22 end |
23 t_sort(index, function(a, b) return _handlers[a] > _handlers[b]; end); | |
25 end; | 24 end; |
26 local function add_handler(event, handler, priority) | 25 local function add_handler(event, handler, priority) |
27 local map = event_map[event]; | 26 local map = event_map[event]; |
28 if map then | 27 if map then |
29 map[handler] = priority or 0; | 28 map[handler] = priority or 0; |
30 else | 29 else |
31 map = {[handler] = priority or 0}; | 30 map = {[handler] = priority or 0}; |
32 event_map[event] = map; | 31 event_map[event] = map; |
33 end | 32 end |
34 _rebuild_index(); | 33 _rebuild_index(event); |
35 end; | 34 end; |
36 local function remove_handler(event, handler) | 35 local function remove_handler(event, handler) |
37 local map = event_map[event]; | 36 local map = event_map[event]; |
38 if map then | 37 if map then |
39 map[handler] = nil; | 38 map[handler] = nil; |
40 _rebuild_index(); | 39 _rebuild_index(event); |
41 end | 40 end |
42 end; | 41 end; |
43 local function add_plugin(plugin) | 42 local function add_plugin(plugin) |
44 for event, handler in pairs(plugin) do | 43 for event, handler in pairs(plugin) do |
45 add_handler(event, handler); | 44 add_handler(event, handler); |