-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcstring.c
111 lines (90 loc) · 2.41 KB
/
cstring.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/* xml2json
*
* Copyright (c) 2018 Partha Susarla <mail@spartha.org>
* cstring - String handling library based of git's strbuf implementation.
*/
#include "cstring.h"
#include "util.h"
#include <ctype.h>
char cstring_base[1];
void cstring_grow(cstring *cstr, size_t len)
{
int newbuf = !cstr->alloc;
if (unsigned_add_overflows(len, 1) ||
(unsigned_add_overflows(cstr->len, len+1))) {
fprintf(stderr, "Not enough memory. Giving up!");
exit(EXIT_FAILURE);
}
if (newbuf)
cstr->buf = NULL;
ALLOC_GROW(cstr->buf, cstr->len + len + 1, cstr->alloc);
if (newbuf)
cstr->buf[0] = '\0';
}
void cstring_init(cstring *cstr, size_t len)
{
cstr->len = 0;
cstr->alloc = 0;
cstr->buf = cstring_base;
if (len)
cstring_grow(cstr, len);
}
void cstring_release(cstring *cstr)
{
if (cstr->alloc) {
free(cstr->buf);
cstring_init(cstr, 0);
}
}
char *cstring_detach(cstring *cstr, size_t *len)
{
char *res;
cstring_grow(cstr, 0);
res = cstr->buf;
if (len)
*len = cstr->len;
cstring_init(cstr, 0);
return res;
}
void cstring_attach(cstring *cstr, void *buf, size_t len, size_t alloc)
{
cstring_release(cstr);
cstr->buf = buf;
cstr->len = len;
cstr->alloc = alloc;
cstring_grow(cstr, 0);
cstr->buf[cstr->len] = '\0';
}
void cstring_add(cstring *cstr, const void *data, size_t len)
{
cstring_grow(cstr, len);
memcpy(cstr->buf + cstr->len, data, len);
cstring_setlen(cstr, cstr->len + len);
}
void cstring_dup(cstring *src, cstring *dest)
{
cstring_grow(dest ,src->len);
memcpy(dest->buf + dest->len, src->buf, src->len);
cstring_setlen(dest, dest->len + src->len);
}
void cstring_ltrim(cstring *cstr)
{
char *p = cstr->buf;
while (cstr->len > 0 && isspace(*p)) {
p++;
cstr->len--;
}
memmove(cstr->buf, p, cstr->len);
cstr->buf[cstr->len] = '\0';
}
void cstring_rtrim(cstring *cstr)
{
while (cstr->len > 0 && isspace(cstr->buf[cstr->len - 1]))
cstr->len--;
cstr->buf[cstr->len] = '\0';
}
void cstring_trim(cstring *cstr)
{
cstring_rtrim(cstr);
cstring_ltrim(cstr);
}