Parsee/src/Command/Router.c

61 lines
1.2 KiB
C

#include <Command.h>
#include <Cytoplasm/Memory.h>
struct CommandRouter {
HashMap *routes;
};
CommandRouter *
CommandCreateRouter(void)
{
CommandRouter *router = Malloc(sizeof(*router));
router->routes = HashMapCreate();
return router;
}
void
CommandAddCommand(CommandRouter *rter, char *c, CommandRoute rte)
{
CommandRoute *indirect;
if (!rter || !c || !rte)
{
return;
}
/* Little dirty trick to force C99 into submission, and since
* some architectures may separate data/code. Still don't like it... */
indirect = Malloc(sizeof(rte));
*indirect = rte;
HashMapSet(rter->routes, c, (void *) indirect);
}
void
RouteCommand(CommandRouter *rter, Command *cmd, void *d)
{
CommandRoute *route;
if (!rter || !cmd)
{
return;
}
route = HashMapGet(rter->routes, cmd->command);
if (route && *route)
{
(*route)(cmd, d);
}
}
void
CommandFreeRouter(CommandRouter *rter)
{
char *key;
CommandRoute *val;
if (!rter)
{
return;
}
while (HashMapIterate(rter->routes, &key, (void **) &val))
{
Free(val);
}
HashMapFree(rter->routes);
Free(rter);
}