acts.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <stdlib.h>
  2. #include "acts.h"
  3. char act_failure[] = "Nit failed act";
  4. static void
  5. action_free(void *action, void *extra)
  6. {
  7. (void) extra;
  8. free(action);
  9. }
  10. Disposer action_dspr = {
  11. .dispose = action_free
  12. };
  13. Nit_error
  14. acts_init(Acts *acts)
  15. {
  16. return map_init(acts, &action_dspr, 0);
  17. }
  18. Nit_error
  19. acts_add(Acts *acts, uint32_t key_len, const void *key,
  20. Act_do do_it, Act_undo undo, Act_dif dif)
  21. {
  22. Nit_error error;
  23. Action *action = malloc(sizeof(*action));
  24. if (!action)
  25. return NIT_ERROR_MEMORY;
  26. action->do_it = do_it;
  27. action->undo = undo;
  28. action->dif = dif;
  29. if ((error = map_add(acts, key_len, key, action)))
  30. free(action);
  31. return error;
  32. }
  33. Nit_error
  34. acts_act(Acts *acts, Act *act, void *extra)
  35. {
  36. Action *action;
  37. if (!map_get(acts, act->key_len, act->key, (void **) &action))
  38. return NIT_ERROR_NOT_FOUND;
  39. switch (act->type) {
  40. case ACT_DO:
  41. case ACT_REDO:
  42. if (!action->do_it)
  43. return NIT_ERROR_NOT_DOABLE;
  44. if ((act->cng = action->do_it(act->real, act->dat,
  45. act->args, extra)) == act_failure)
  46. return NIT_ERROR_FAILED;
  47. break;
  48. case ACT_UNDO:
  49. if (!action->undo)
  50. return NIT_ERROR_NOT_UNDOABLE;
  51. if ((action->undo(act->cng, act->dat, act->args, extra)))
  52. return NIT_ERROR_FAILED;
  53. break;
  54. case ACT_DIF:
  55. case ACT_REDIF:
  56. if (!action->dif)
  57. return NIT_ERROR_NOT_DIFF;
  58. if ((act->cng = action->dif(act->cng, act->dat,
  59. act->args, extra)) == act_failure)
  60. return NIT_ERROR_FAILED;
  61. break;
  62. }
  63. return NIT_ERROR_FINE;
  64. }