diff options
author | Vicent Marti <tanoku@gmail.com> | 2014-09-03 03:40:53 +0200 |
---|---|---|
committer | Vicent Marti <tanoku@gmail.com> | 2014-09-09 03:39:15 +0200 |
commit | 460d46c62b0675f2fab6f103bb9f0d185a73eebb (patch) | |
tree | 42d7689a7bb8b32cd6f97ed48ffd3b9e9f899906 /src/chunk.h | |
parent | a7314deae649646f1f7ce5ede972641b5b62538c (diff) |
Add chunk.h
Diffstat (limited to 'src/chunk.h')
-rw-r--r-- | src/chunk.h | 92 |
1 files changed, 92 insertions, 0 deletions
diff --git a/src/chunk.h b/src/chunk.h new file mode 100644 index 0000000..f3841ed --- /dev/null +++ b/src/chunk.h @@ -0,0 +1,92 @@ +#ifndef _CHUNK_H_ +#define _CHUNK_H_ + +#include <string.h> +#include <ctype.h> +#include <stdlib.h> +#include <assert.h> +#include "buffer.h" + +typedef struct { + const unsigned char *data; + int len; + int alloc; +} chunk; + +static inline void chunk_free(chunk *c) +{ + if (c->alloc) + free((char *)c->data); + + c->data = NULL; + c->alloc = 0; + c->len = 0; +} + +static inline void chunk_ltrim(chunk *c) +{ + assert(!c->alloc); + + while (c->len && isspace(c->data[0])) { + c->data++; + c->len--; + } +} + +static inline void chunk_rtrim(chunk *c) +{ + while (c->len > 0) { + if (!isspace(c->data[c->len - 1])) + break; + + c->len--; + } +} + +static inline void chunk_trim(chunk *c) +{ + chunk_ltrim(c); + chunk_rtrim(c); +} + +static inline int chunk_strchr(chunk *ch, int c, int offset) +{ + const unsigned char *p = memchr(ch->data + offset, c, ch->len - offset); + return p ? (int)(p - ch->data) : ch->len; +} + +static inline unsigned char *chunk_to_cstr(chunk *c) +{ + unsigned char *str; + + str = malloc(c->len + 1); + memcpy(str, c->data, c->len); + str[c->len] = 0; + + return str; +} + +static inline chunk chunk_literal(const char *data) +{ + chunk c = {(const unsigned char *)data, data ? strlen(data) : 0, 0}; + return c; +} + +static inline chunk chunk_dup(const chunk *ch, int pos, int len) +{ + chunk c = {ch->data + pos, len, 0}; + return c; +} + +static inline chunk chunk_buf_detach(gh_buf *buf) +{ + chunk c; + + c.len = buf->size; + c.data = gh_buf_detach(buf); + c.alloc = 1; + + return c; +} + +#endif |