diff options
Diffstat (limited to 'src/chunk.h')
-rw-r--r-- | src/chunk.h | 39 |
1 files changed, 28 insertions, 11 deletions
diff --git a/src/chunk.h b/src/chunk.h index 9dd56b6..7a1dbc3 100644 --- a/src/chunk.h +++ b/src/chunk.h @@ -8,15 +8,15 @@ #include "buffer.h" typedef struct { - const unsigned char *data; + unsigned char *data; int len; - int alloc; + int alloc; // also implies a NULL-terminated string } cmark_chunk; static inline void cmark_chunk_free(cmark_chunk *c) { if (c->alloc) - free((char *)c->data); + free(c->data); c->data = NULL; c->alloc = 0; @@ -55,21 +55,38 @@ static inline int cmark_chunk_strchr(cmark_chunk *ch, int c, int offset) return p ? (int)(p - ch->data) : ch->len; } -static inline unsigned char *cmark_chunk_to_cstr(cmark_chunk *c) +static inline const char *cmark_chunk_to_cstr(cmark_chunk *c) { unsigned char *str; - str = (unsigned char *)calloc(c->len + 1, sizeof(*str)); - if(str != NULL) { - memcpy(str, c->data, c->len); - str[c->len] = 0; - } - return str; + if (c->alloc) { + return (char *)c->data; + } + str = (unsigned char *)malloc(c->len + 1); + if(str != NULL) { + memcpy(str, c->data, c->len); + str[c->len] = 0; + } + c->data = str; + c->alloc = 1; + + return (char *)str; +} + +static inline void cmark_chunk_set_cstr(cmark_chunk *c, const char *str) +{ + if (c->alloc) { + free(c->data); + } + c->len = strlen(str); + c->data = (unsigned char *)malloc(c->len + 1); + c->alloc = 1; + memcpy(c->data, str, c->len + 1); } static inline cmark_chunk cmark_chunk_literal(const char *data) { - cmark_chunk c = {(const unsigned char *)data, data ? strlen(data) : 0, 0}; + cmark_chunk c = {(unsigned char *)data, data ? strlen(data) : 0, 0}; return c; } |