ksym.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include <faux/str.h>
  6. #include <faux/list.h>
  7. #include <faux/conv.h>
  8. #include <faux/error.h>
  9. #include <klish/khelper.h>
  10. #include <klish/ksym.h>
  11. struct ksym_s {
  12. char *name;
  13. const void *fn;
  14. };
  15. // Simple methods
  16. // Name
  17. KGET_STR(sym, name);
  18. KSET_STR_ONCE(sym, name);
  19. // Fn (function)
  20. KGET(sym, const void *, fn);
  21. KSET(sym, const void *, fn);
  22. static ksym_t *ksym_new_empty(void)
  23. {
  24. ksym_t *sym = NULL;
  25. sym = faux_zmalloc(sizeof(*sym));
  26. assert(sym);
  27. if (!sym)
  28. return NULL;
  29. // Initialize
  30. sym->name = NULL;
  31. sym->fn = NULL;
  32. return sym;
  33. }
  34. ksym_t *ksym_new(ksym_error_e *error)
  35. {
  36. ksym_t *sym = NULL;
  37. sym = ksym_new_empty();
  38. assert(sym);
  39. if (!sym) {
  40. if (error)
  41. *error = KSYM_ERROR_ALLOC;
  42. return NULL;
  43. }
  44. return sym;
  45. }
  46. void ksym_free(ksym_t *sym)
  47. {
  48. if (!sym)
  49. return;
  50. faux_str_free(sym->name);
  51. faux_free(sym);
  52. }
  53. const char *ksym_strerror(ksym_error_e error)
  54. {
  55. const char *str = NULL;
  56. switch (error) {
  57. case KSYM_ERROR_OK:
  58. str = "Ok";
  59. break;
  60. case KSYM_ERROR_INTERNAL:
  61. str = "Internal error";
  62. break;
  63. case KSYM_ERROR_ALLOC:
  64. str = "Memory allocation error";
  65. break;
  66. default:
  67. str = "Unknown error";
  68. break;
  69. }
  70. return str;
  71. }