2 /*] Copyright (c) 2009-2010, Charles McGarvey [**************************
3 **] All rights reserved.
7 * Distributable under the terms and conditions of the 2-clause BSD license;
8 * see the file COPYING for a complete text of the license.
10 **************************************************************************/
14 #include "Dispatch.hh"
24 Impl(Dispatch
* dispatch
) :
28 Dispatch::Handle
getNewHandle()
31 Dispatch::Handle
handle(mDispatch
->mImpl
, mId
);
35 typedef std::pair
<unsigned,Dispatch::Function
> Callback
;
36 typedef std::multimap
<std::string
,Callback
> CallbackLookup
;
37 typedef CallbackLookup::iterator CallbackIt
;
39 typedef std::multimap
<unsigned,std::string
> HandleLookup
;
40 typedef HandleLookup::iterator HandleIt
;
43 inline Handle
addTarget(const std::string
& event
,
44 const Function
& callback
, Handle handle
)
46 mCallbacks
.insert(std::make_pair(event
,
47 std::make_pair(handle
.getId(), callback
)));
48 mHandles
.insert(std::make_pair(handle
.getId(), event
));
53 inline void removeTarget(unsigned id
)
55 std::pair
<HandleIt
,HandleIt
> matching(mHandles
.equal_range(id
));
57 for (HandleIt it
= matching
.first
; it
!= matching
.second
; ++it
)
59 CallbackIt first
= mCallbacks
.find((*it
).second
);
60 CallbackIt last
= mCallbacks
.end();
62 for (CallbackIt jt
= first
; jt
!= last
; ++jt
)
64 if ((*jt
).second
.first
== id
)
75 void dispatch(const std::string
& event
, const Message
* message
)
77 std::pair
<CallbackIt
,CallbackIt
>
78 callbacks(mCallbacks
.equal_range(event
));
80 for (CallbackIt it
= callbacks
.first
; it
!= callbacks
.second
; ++it
)
82 Function callback
= (*it
).second
.second
;
92 CallbackLookup mCallbacks
;
93 HandleLookup mHandles
;
97 void Dispatch::Handle::clear()
99 boost::shared_ptr
<Impl
> dispatch
;
100 if (mId
&& (dispatch
= mDispatch
.lock()))
102 dispatch
->removeTarget(mId
);
108 Dispatch::Dispatch() :
109 mImpl(new Dispatch::Impl(this)) {}
112 Dispatch::Handle
Dispatch::addTarget(const std::string
& event
,
113 const Function
& callback
)
115 return addTarget(event
, callback
, mImpl
->getNewHandle());
118 Dispatch::Handle
Dispatch::addTarget(const std::string
& event
,
119 const Function
& callback
,
123 return mImpl
->addTarget(event
, callback
, handle
);
127 void Dispatch::removeTarget(unsigned id
)
130 return mImpl
->removeTarget(id
);
134 void Dispatch::dispatch(const std::string
& event
, const Message
* message
)
137 mImpl
->dispatch(event
, message
);
141 Dispatch
& Dispatch::global()
143 static Dispatch dispatch
;