libevent.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifndef __HIREDIS_LIBEVENT_H__
  2. #define __HIREDIS_LIBEVENT_H__
  3. #include <event.h>
  4. #include "../hiredis.h"
  5. #include "../async.h"
  6. typedef struct redisLibeventEvents {
  7. redisAsyncContext *context;
  8. struct event rev, wev;
  9. } redisLibeventEvents;
  10. static void redisLibeventReadEvent(int fd, short event, void *arg) {
  11. ((void)fd); ((void)event);
  12. redisLibeventEvents *e = (redisLibeventEvents*)arg;
  13. redisAsyncHandleRead(e->context);
  14. }
  15. static void redisLibeventWriteEvent(int fd, short event, void *arg) {
  16. ((void)fd); ((void)event);
  17. redisLibeventEvents *e = (redisLibeventEvents*)arg;
  18. redisAsyncHandleWrite(e->context);
  19. }
  20. static void redisLibeventAddRead(void *privdata) {
  21. redisLibeventEvents *e = (redisLibeventEvents*)privdata;
  22. event_add(&e->rev,NULL);
  23. }
  24. static void redisLibeventDelRead(void *privdata) {
  25. redisLibeventEvents *e = (redisLibeventEvents*)privdata;
  26. event_del(&e->rev);
  27. }
  28. static void redisLibeventAddWrite(void *privdata) {
  29. redisLibeventEvents *e = (redisLibeventEvents*)privdata;
  30. event_add(&e->wev,NULL);
  31. }
  32. static void redisLibeventDelWrite(void *privdata) {
  33. redisLibeventEvents *e = (redisLibeventEvents*)privdata;
  34. event_del(&e->wev);
  35. }
  36. static void redisLibeventCleanup(void *privdata) {
  37. redisLibeventEvents *e = (redisLibeventEvents*)privdata;
  38. event_del(&e->rev);
  39. event_del(&e->wev);
  40. free(e);
  41. }
  42. static int redisLibeventAttach(redisAsyncContext *ac, struct event_base *base) {
  43. redisContext *c = &(ac->c);
  44. redisLibeventEvents *e;
  45. /* Nothing should be attached when something is already attached */
  46. if (ac->ev.data != NULL)
  47. return REDIS_ERR;
  48. /* Create container for context and r/w events */
  49. e = (redisLibeventEvents*)malloc(sizeof(*e));
  50. e->context = ac;
  51. /* Register functions to start/stop listening for events */
  52. ac->ev.addRead = redisLibeventAddRead;
  53. ac->ev.delRead = redisLibeventDelRead;
  54. ac->ev.addWrite = redisLibeventAddWrite;
  55. ac->ev.delWrite = redisLibeventDelWrite;
  56. ac->ev.cleanup = redisLibeventCleanup;
  57. ac->ev.data = e;
  58. /* Initialize and install read/write events */
  59. event_set(&e->rev,c->fd,EV_READ,redisLibeventReadEvent,e);
  60. event_set(&e->wev,c->fd,EV_WRITE,redisLibeventWriteEvent,e);
  61. event_base_set(base,&e->rev);
  62. event_base_set(base,&e->wev);
  63. return REDIS_OK;
  64. }
  65. #endif