db/upnp: use std::function for the libupnp callback

Replaces the bloated std::map.
This commit is contained in:
Max Kellermann 2014-01-13 22:05:45 +01:00
parent 85324f80fe
commit ca43e634b5
3 changed files with 16 additions and 31 deletions

View File

@ -158,7 +158,7 @@ discoExplorer(void *)
// mutex just for clarifying the message printing, the workqueue is // mutex just for clarifying the message printing, the workqueue is
// mt-safe of course. // mt-safe of course.
static int static int
cluCallBack(Upnp_EventType et, void *evp, void *) cluCallBack(Upnp_EventType et, void *evp)
{ {
static Mutex cblock; static Mutex cblock;
const ScopeLock protect(cblock); const ScopeLock protect(cblock);
@ -231,11 +231,9 @@ UPnPDeviceDirectory::UPnPDeviceDirectory()
if (lib == nullptr) if (lib == nullptr)
return; return;
lib->registerHandler(UPNP_DISCOVERY_SEARCH_RESULT, cluCallBack, this); lib->SetHandler([](Upnp_EventType type, void *event){
lib->registerHandler(UPNP_DISCOVERY_ADVERTISEMENT_ALIVE, cluCallBack(type, event);
cluCallBack, this); });
lib->registerHandler(UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE,
cluCallBack, this);
search(); search();
} }

View File

@ -65,15 +65,6 @@ LibUPnP::LibUPnP()
ixmlRelaxParser(1); ixmlRelaxParser(1);
} }
void
LibUPnP::registerHandler(Upnp_EventType et, Upnp_FunPtr handler, void *cookie)
{
if (handler == nullptr)
m_handlers.erase(et);
else
m_handlers.emplace(et, Handler(handler, cookie));
}
int int
LibUPnP::o_callback(Upnp_EventType et, void* evp, void* cookie) LibUPnP::o_callback(Upnp_EventType et, void* evp, void* cookie)
{ {
@ -83,10 +74,9 @@ LibUPnP::o_callback(Upnp_EventType et, void* evp, void* cookie)
ulib = theLib; ulib = theLib;
} }
auto it = ulib->m_handlers.find(et); if (ulib->handler)
if (it != ulib->m_handlers.end()) { ulib->handler(et, evp);
(it->second.handler)(et, evp, it->second.cookie);
}
return UPNP_E_SUCCESS; return UPNP_E_SUCCESS;
} }

View File

@ -22,24 +22,18 @@
#include "util/Error.hxx" #include "util/Error.hxx"
#include <map>
#include <upnp/upnp.h> #include <upnp/upnp.h>
#include <functional>
/** Our link to libupnp. Initialize and keep the handle around */ /** Our link to libupnp. Initialize and keep the handle around */
class LibUPnP { class LibUPnP {
// A Handler object records the data from registerHandler. typedef std::function<void(Upnp_EventType type, void *event)> Handler;
class Handler {
public:
Handler(Upnp_FunPtr h, void *c)
: handler(h), cookie(c) {}
Upnp_FunPtr handler;
void *cookie;
};
Error init_error; Error init_error;
UpnpClient_Handle m_clh; UpnpClient_Handle m_clh;
std::map<Upnp_EventType, Handler> m_handlers;
Handler handler;
LibUPnP(); LibUPnP();
@ -65,7 +59,10 @@ public:
return init_error; return init_error;
} }
void registerHandler(Upnp_EventType et, Upnp_FunPtr handler, void *cookie); template<typename T>
void SetHandler(T &&_handler) {
handler = std::forward<T>(_handler);
}
UpnpClient_Handle getclh() UpnpClient_Handle getclh()
{ {