proc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. proc_handler_proc_t proc;
  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. proc_handler_proc_t proc, void *data)
  48. {
  49. if (!handler) return;
  50. struct proc_info pi = {bstrdup(name), data, proc};
  51. da_push_back(handler->procs, &pi);
  52. }
  53. bool proc_handler_call(proc_handler_t handler, const char *name,
  54. calldata_t params)
  55. {
  56. if (!handler) return false;
  57. for (size_t i = 0; i < handler->procs.num; i++) {
  58. struct proc_info *info = handler->procs.array+i;
  59. if (strcmp(info->name, name) == 0) {
  60. info->proc(info->data, params);
  61. return true;
  62. }
  63. }
  64. return false;
  65. }