proc.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 "decl.h"
  18. #include "proc.h"
  19. struct proc_info {
  20. struct decl_info func;
  21. void *data;
  22. proc_handler_proc_t callback;
  23. };
  24. static inline void proc_info_free(struct proc_info *pi)
  25. {
  26. decl_info_free(&pi->func);
  27. }
  28. struct proc_handler {
  29. /* TODO: replace with hash table lookup? */
  30. DARRAY(struct proc_info) procs;
  31. };
  32. proc_handler_t *proc_handler_create(void)
  33. {
  34. struct proc_handler *handler = bmalloc(sizeof(struct proc_handler));
  35. da_init(handler->procs);
  36. return handler;
  37. }
  38. void proc_handler_destroy(proc_handler_t *handler)
  39. {
  40. if (handler) {
  41. for (size_t i = 0; i < handler->procs.num; i++)
  42. proc_info_free(handler->procs.array+i);
  43. da_free(handler->procs);
  44. bfree(handler);
  45. }
  46. }
  47. void proc_handler_add(proc_handler_t *handler, const char *decl_string,
  48. proc_handler_proc_t proc, void *data)
  49. {
  50. if (!handler) return;
  51. struct proc_info pi;
  52. memset(&pi, 0, sizeof(struct proc_info));
  53. if (!parse_decl_string(&pi.func, decl_string)) {
  54. blog(LOG_ERROR, "Function declaration invalid: %s",
  55. decl_string);
  56. return;
  57. }
  58. pi.callback = proc;
  59. pi.data = data;
  60. da_push_back(handler->procs, &pi);
  61. }
  62. bool proc_handler_call(proc_handler_t *handler, const char *name,
  63. calldata_t *params)
  64. {
  65. if (!handler) return false;
  66. for (size_t i = 0; i < handler->procs.num; i++) {
  67. struct proc_info *info = handler->procs.array+i;
  68. if (strcmp(info->func.name, name) == 0) {
  69. info->callback(info->data, params);
  70. return true;
  71. }
  72. }
  73. return false;
  74. }