aboutsummaryrefslogtreecommitdiff
path: root/src/chunk.h
blob: b29c1b9210ac39761153aa65dba980314792a76a (plain)
  1. #ifndef CMARK_CHUNK_H
  2. #define CMARK_CHUNK_H
  3. #include <string.h>
  4. #include <ctype.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include "buffer.h"
  8. typedef struct {
  9. unsigned char *data;
  10. int len;
  11. int alloc; // also implies a NULL-terminated string
  12. } chunk;
  13. static inline void chunk_free(chunk *c)
  14. {
  15. if (c->alloc)
  16. free(c->data);
  17. c->data = NULL;
  18. c->alloc = 0;
  19. c->len = 0;
  20. }
  21. static inline void chunk_ltrim(chunk *c)
  22. {
  23. assert(!c->alloc);
  24. while (c->len && isspace(c->data[0])) {
  25. c->data++;
  26. c->len--;
  27. }
  28. }
  29. static inline void chunk_rtrim(chunk *c)
  30. {
  31. while (c->len > 0) {
  32. if (!isspace(c->data[c->len - 1]))
  33. break;
  34. c->len--;
  35. }
  36. }
  37. static inline void chunk_trim(chunk *c)
  38. {
  39. chunk_ltrim(c);
  40. chunk_rtrim(c);
  41. }
  42. static inline int chunk_strchr(chunk *ch, int c, int offset)
  43. {
  44. const unsigned char *p = (unsigned char *)memchr(ch->data + offset, c, ch->len - offset);
  45. return p ? (int)(p - ch->data) : ch->len;
  46. }
  47. static inline const char *chunk_to_cstr(chunk *c)
  48. {
  49. unsigned char *str;
  50. if (c->alloc) {
  51. return (char *)c->data;
  52. }
  53. str = (unsigned char *)malloc(c->len + 1);
  54. if(str != NULL) {
  55. memcpy(str, c->data, c->len);
  56. str[c->len] = 0;
  57. }
  58. c->data = str;
  59. c->alloc = 1;
  60. return (char *)str;
  61. }
  62. static inline void chunk_set_cstr(chunk *c, const char *str)
  63. {
  64. if (c->alloc) {
  65. free(c->data);
  66. }
  67. c->len = strlen(str);
  68. c->data = (unsigned char *)malloc(c->len + 1);
  69. c->alloc = 1;
  70. memcpy(c->data, str, c->len + 1);
  71. }
  72. static inline chunk chunk_literal(const char *data)
  73. {
  74. chunk c = {(unsigned char *)data, data ? strlen(data) : 0, 0};
  75. return c;
  76. }
  77. static inline chunk chunk_dup(const chunk *ch, int pos, int len)
  78. {
  79. chunk c = {ch->data + pos, len, 0};
  80. return c;
  81. }
  82. static inline chunk chunk_buf_detach(strbuf *buf)
  83. {
  84. chunk c;
  85. c.len = buf->size;
  86. c.data = strbuf_detach(buf);
  87. c.alloc = 1;
  88. return c;
  89. }
  90. #endif