Skip to content

Commit 460d46c

Browse files
committed
Add chunk.h
1 parent a7314de commit 460d46c

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

src/chunk.h

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

0 commit comments

Comments
 (0)