proc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2013 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include "../util/darray.h"
  17. #include "proc.h"
  18. struct proc_info {
  19. char *name;
  20. void *data;
  21. void (*proc)(calldata_t, void*);
  22. };
  23. static inline void proc_info_free(struct proc_info *pi)
  24. {
  25. bfree(pi->name);
  26. }
  27. struct proc_handler {
  28. /* TODO: replace with hash table lookup? */
  29. DARRAY(struct proc_info) procs;
  30. };
  31. proc_handler_t proc_handler_create(void)
  32. {
  33. struct proc_handler *handler = bmalloc(sizeof(struct proc_handler));
  34. da_init(handler->procs);
  35. return handler;
  36. }
  37. void proc_handler_destroy(proc_handler_t handler)
  38. {
  39. if (handler) {
  40. for (size_t i = 0; i < handler->procs.num; i++)
  41. proc_info_free(handler->procs.array+i);
  42. da_free(handler->procs);
  43. bfree(handler);
  44. }
  45. }
  46. void proc_handler_add(proc_handler_t handler, const char *name,
  47. void (*proc)(void*, calldata_t), void *data)
  48. {
  49. struct proc_info pi = {bstrdup(name), data, proc};
  50. da_push_back(handler->procs, &pi);
  51. }
  52. bool proc_handler_call(proc_handler_t handler, const char *name,
  53. calldata_t params)
  54. {
  55. for (size_t i = 0; i < handler->procs.num; i++) {
  56. struct proc_info *info = handler->procs.array+i;
  57. if (strcmp(info->name, name) == 0) {
  58. info->proc(info->data, params);
  59. return true;
  60. }
  61. }
  62. return false;
  63. }