proc.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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)
  51. return;
  52. struct proc_info pi;
  53. memset(&pi, 0, sizeof(struct proc_info));
  54. if (!parse_decl_string(&pi.func, decl_string)) {
  55. blog(LOG_ERROR, "Function declaration invalid: %s",
  56. decl_string);
  57. return;
  58. }
  59. pi.callback = proc;
  60. pi.data = data;
  61. da_push_back(handler->procs, &pi);
  62. }
  63. bool proc_handler_call(proc_handler_t *handler, const char *name,
  64. calldata_t *params)
  65. {
  66. if (!handler)
  67. return false;
  68. for (size_t i = 0; i < handler->procs.num; i++) {
  69. struct proc_info *info = handler->procs.array + i;
  70. if (strcmp(info->func.name, name) == 0) {
  71. info->callback(info->data, params);
  72. return true;
  73. }
  74. }
  75. return false;
  76. }