aboutsummaryrefslogtreecommitdiff
path: root/src/chunk.h
blob: 9dd56b6dc65f96aab069aee2fa332fdc4dcb382f (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. const unsigned char *data;
  10. int len;
  11. int alloc;
  12. } cmark_chunk;
  13. static inline void cmark_chunk_free(cmark_chunk *c)
  14. {
  15. if (c->alloc)
  16. free((char *)c->data);
  17. c->data = NULL;
  18. c->alloc = 0;
  19. c->len = 0;
  20. }
  21. static inline void cmark_chunk_ltrim(cmark_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 cmark_chunk_rtrim(cmark_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 cmark_chunk_trim(cmark_chunk *c)
  38. {
  39. cmark_chunk_ltrim(c);
  40. cmark_chunk_rtrim(c);
  41. }
  42. static inline int cmark_chunk_strchr(cmark_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 unsigned char *cmark_chunk_to_cstr(cmark_chunk *c)
  48. {
  49. unsigned char *str;
  50. str = (unsigned char *)calloc(c->len + 1, sizeof(*str));
  51. if(str != NULL) {
  52. memcpy(str, c->data, c->len);
  53. str[c->len] = 0;
  54. }
  55. return str;
  56. }
  57. static inline cmark_chunk cmark_chunk_literal(const char *data)
  58. {
  59. cmark_chunk c = {(const unsigned char *)data, data ? strlen(data) : 0, 0};
  60. return c;
  61. }
  62. static inline cmark_chunk cmark_chunk_dup(const cmark_chunk *ch, int pos, int len)
  63. {
  64. cmark_chunk c = {ch->data + pos, len, 0};
  65. return c;
  66. }
  67. static inline cmark_chunk cmark_chunk_buf_detach(cmark_strbuf *buf)
  68. {
  69. cmark_chunk c;
  70. c.len = buf->size;
  71. c.data = cmark_strbuf_detach(buf);
  72. c.alloc = 1;
  73. return c;
  74. }
  75. #ifndef CMARK_NO_SHORT_NAMES
  76. #define chunk cmark_chunk
  77. #define chunk_free cmark_chunk_free
  78. #define chunk_ltrim cmark_chunk_ltrim
  79. #define chunk_rtrim cmark_chunk_rtrim
  80. #define chunk_trim cmark_chunk_trim
  81. #define chunk_strchr cmark_chunk_strchr
  82. #define chunk_to_cstr cmark_chunk_to_cstr
  83. #define chunk_literal cmark_chunk_literal
  84. #define chunk_dup cmark_chunk_dup
  85. #define chunk_buf_detach cmark_chunk_buf_detach
  86. #endif
  87. #endif