luat_ztt.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "uv.h"
  2. #include "luat_base.h"
  3. #include "luat_ztt.h"
  4. #include "luat_malloc.h"
  5. #include "printf.h"
  6. #define LUAT_LOG_TAG "ztt"
  7. #include "luat_log.h"
  8. luat_ztt_t* ztt_create(const char* type) {
  9. return ztt_add(NULL, "type", type, strlen(type));
  10. }
  11. luat_ztt_t* ztt_addf(luat_ztt_t* ztt_head, const char* key, const char* _fmt, ...) {
  12. char* buff = luat_heap_malloc(4096);
  13. if (buff == NULL)
  14. return NULL;
  15. memset(buff, 0, 4096);
  16. va_list args;
  17. va_start(args, _fmt);
  18. int len = vsnprintf_(buff, 4096 - 1, _fmt, args);
  19. va_end(args);
  20. if (len <= 0) {
  21. luat_heap_free(buff);
  22. return NULL;
  23. }
  24. luat_ztt_t* ret = ztt_add(ztt_head, key, buff, len);
  25. luat_heap_free(buff);
  26. return ret;
  27. }
  28. luat_ztt_t* ztt_add(luat_ztt_t* ztt_head, const char* key, const char* value, size_t value_len) {
  29. luat_ztt_t* ztt = luat_heap_malloc(sizeof(luat_ztt_t));
  30. if (ztt == NULL) {
  31. return ztt_head;
  32. }
  33. memset(ztt, 0, sizeof(luat_ztt_t));
  34. ztt->key = luat_heap_malloc(strlen(key) + 1);
  35. ztt->value = luat_heap_malloc(value_len);
  36. if (ztt->value == NULL || ztt->key == NULL) {
  37. if (ztt->value)
  38. luat_heap_free(ztt->value);
  39. if (ztt->key)
  40. luat_heap_free(ztt->key);
  41. luat_heap_free(ztt);
  42. return ztt_head;
  43. }
  44. memcpy(ztt->key, key, strlen(key) + 1);
  45. memcpy(ztt->value, value, value_len);
  46. ztt->value_len = value_len;
  47. if (ztt_head == NULL) {
  48. return ztt;
  49. }
  50. luat_ztt_t* head = ztt_head;
  51. while (1) {
  52. if (head->next) {
  53. head = head->next;
  54. continue;
  55. }
  56. head->next = ztt;
  57. break;
  58. }
  59. return ztt_head;
  60. }
  61. int ztt_commit(luat_ztt_t* ztt) {
  62. if (ztt == NULL)
  63. return -1;
  64. luat_ztt_t* head = ztt;
  65. size_t len = 0;
  66. char* buff = luat_heap_malloc(4);
  67. if (buff == NULL) {
  68. // TODO clear ztt;
  69. return -2;
  70. }
  71. while (head != NULL) {
  72. buff = luat_heap_realloc(buff, len + head->value_len + 2);
  73. if (buff == NULL) {
  74. // TODO clear ztt;
  75. return -3;
  76. }
  77. memcpy(buff + len, head->value, head->value_len);
  78. len += head->value_len;
  79. buff[len] = ',';
  80. len ++;
  81. luat_ztt_t* tmp = head;
  82. head = head->next;
  83. luat_heap_free(tmp->key);
  84. luat_heap_free(tmp->value);
  85. luat_heap_free(tmp);
  86. }
  87. buff[len] = '0';
  88. // TODO 发送UDP/接收UDP
  89. return 0;
  90. }