kptype.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 <klish/khelper.h>
  8. #include <klish/kptype.h>
  9. struct kptype_s {
  10. char *name;
  11. char *help;
  12. };
  13. // Simple methods
  14. // Name
  15. KGET_STR(ptype, name);
  16. KSET_STR_ONCE(ptype, name);
  17. // Help
  18. KGET_STR(ptype, help);
  19. KSET_STR(ptype, help);
  20. static kptype_t *kptype_new_empty(void)
  21. {
  22. kptype_t *ptype = NULL;
  23. ptype = faux_zmalloc(sizeof(*ptype));
  24. assert(ptype);
  25. if (!ptype)
  26. return NULL;
  27. // Initialize
  28. ptype->name = NULL;
  29. ptype->help = NULL;
  30. return ptype;
  31. }
  32. kptype_t *kptype_new(const iptype_t *info, kptype_error_e *error)
  33. {
  34. kptype_t *ptype = NULL;
  35. ptype = kptype_new_empty();
  36. assert(ptype);
  37. if (!ptype) {
  38. if (error)
  39. *error = KPTYPE_ERROR_ALLOC;
  40. return NULL;
  41. }
  42. if (!info)
  43. return ptype;
  44. if (!kptype_parse(ptype, info, error)) {
  45. kptype_free(ptype);
  46. return NULL;
  47. }
  48. return ptype;
  49. }
  50. void kptype_free(kptype_t *ptype)
  51. {
  52. if (!ptype)
  53. return;
  54. faux_str_free(ptype->name);
  55. faux_str_free(ptype->help);
  56. faux_free(ptype);
  57. }
  58. const char *kptype_strerror(kptype_error_e error)
  59. {
  60. const char *str = NULL;
  61. switch (error) {
  62. case KPTYPE_ERROR_OK:
  63. str = "Ok";
  64. break;
  65. case KPTYPE_ERROR_INTERNAL:
  66. str = "Internal error";
  67. break;
  68. case KPTYPE_ERROR_ALLOC:
  69. str = "Memory allocation error";
  70. break;
  71. case KPTYPE_ERROR_ATTR_NAME:
  72. str = "Illegal 'name' attribute";
  73. break;
  74. case KPTYPE_ERROR_ATTR_HELP:
  75. str = "Illegal 'help' attribute";
  76. break;
  77. default:
  78. str = "Unknown error";
  79. break;
  80. }
  81. return str;
  82. }
  83. bool_t kptype_parse(kptype_t *ptype, const iptype_t *info, kptype_error_e *error)
  84. {
  85. bool_t retval = BOOL_TRUE;
  86. // Name [mandatory]
  87. if (faux_str_is_empty(info->name)) {
  88. if (error)
  89. *error = KPTYPE_ERROR_ATTR_NAME;
  90. retval = BOOL_FALSE;
  91. } else {
  92. if (!kptype_set_name(ptype, info->name)) {
  93. if (error)
  94. *error = KPTYPE_ERROR_ATTR_NAME;
  95. retval = BOOL_FALSE;
  96. }
  97. }
  98. // Help
  99. if (!faux_str_is_empty(info->name)) {
  100. if (!kptype_set_help(ptype, info->help)) {
  101. if (error)
  102. *error = KPTYPE_ERROR_ATTR_HELP;
  103. retval = BOOL_FALSE;
  104. }
  105. }
  106. return retval;
  107. }