-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrbuf.c
More file actions
82 lines (68 loc) · 1.55 KB
/
strbuf.c
File metadata and controls
82 lines (68 loc) · 1.55 KB
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
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "strbuf.h"
/*
* Minimal strbuf implementation for standalone graph.c
*/
/* Sentinel buffer for empty strbufs - allows buf to never be NULL */
char strbuf_slopbuf[1];
void strbuf_init(struct strbuf *sb, size_t hint)
{
sb->alloc = 0;
sb->len = 0;
sb->buf = strbuf_slopbuf;
if (hint)
strbuf_grow(sb, hint);
}
void strbuf_release(struct strbuf *sb)
{
if (sb->buf != strbuf_slopbuf)
free(sb->buf);
strbuf_init(sb, 0);
}
void strbuf_grow(struct strbuf *sb, size_t extra)
{
size_t need = sb->len + extra + 1; /* +1 for NUL */
if (need <= sb->alloc)
return;
/* Grow by at least 64 bytes or double, whichever is more */
size_t new_alloc = sb->alloc ? sb->alloc * 2 : 64;
if (new_alloc < need)
new_alloc = need;
if (sb->buf == strbuf_slopbuf) {
sb->buf = malloc(new_alloc);
sb->buf[0] = '\0';
} else {
sb->buf = realloc(sb->buf, new_alloc);
}
if (!sb->buf) {
fprintf(stderr, "strbuf: out of memory\n");
exit(1);
}
sb->alloc = new_alloc;
}
void strbuf_addch(struct strbuf *sb, int c)
{
strbuf_grow(sb, 1);
sb->buf[sb->len++] = c;
sb->buf[sb->len] = '\0';
}
void strbuf_addchars(struct strbuf *sb, int c, size_t n)
{
strbuf_grow(sb, n);
memset(sb->buf + sb->len, c, n);
sb->len += n;
sb->buf[sb->len] = '\0';
}
void strbuf_add(struct strbuf *sb, const void *data, size_t len)
{
strbuf_grow(sb, len);
memcpy(sb->buf + sb->len, data, len);
sb->len += len;
sb->buf[sb->len] = '\0';
}
void strbuf_addstr(struct strbuf *sb, const char *s)
{
strbuf_add(sb, s, strlen(s));
}