-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrbuf.h
More file actions
66 lines (50 loc) · 1.65 KB
/
strbuf.h
File metadata and controls
66 lines (50 loc) · 1.65 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
#ifndef STRBUF_H
#define STRBUF_H
#include <stddef.h>
/*
* Minimal strbuf implementation for standalone graph.c
* Only implements functions actually used by graph.c
*/
struct strbuf {
size_t alloc;
size_t len;
char *buf;
};
extern char strbuf_slopbuf[];
#define STRBUF_INIT { 0, 0, strbuf_slopbuf }
/* Initialize a strbuf. Optionally pre-allocate 'hint' bytes. */
void strbuf_init(struct strbuf *sb, size_t hint);
/* Release the buffer memory. Safe to call multiple times. */
void strbuf_release(struct strbuf *sb);
/* Ensure at least 'extra' more bytes can be added without realloc */
void strbuf_grow(struct strbuf *sb, size_t extra);
/* Set length, ensuring NUL termination. Use for truncating or after manual writes. */
static inline void strbuf_setlen(struct strbuf *sb, size_t len)
{
if (len > (sb->alloc ? sb->alloc - 1 : 0)) {
/* Caller is responsible for not exceeding allocated space */
return;
}
sb->len = len;
if (sb->buf != strbuf_slopbuf)
sb->buf[len] = '\0';
}
/* Reset to empty string (keeps allocated memory) */
static inline void strbuf_reset(struct strbuf *sb)
{
strbuf_setlen(sb, 0);
}
/* Add a single character */
void strbuf_addch(struct strbuf *sb, int c);
/* Add 'n' copies of character 'c' */
void strbuf_addchars(struct strbuf *sb, int c, size_t n);
/* Add a NUL-terminated string */
void strbuf_addstr(struct strbuf *sb, const char *s);
/* Add 'len' bytes from buffer */
void strbuf_add(struct strbuf *sb, const void *data, size_t len);
/* Return number of bytes that can be added without realloc */
static inline size_t strbuf_avail(const struct strbuf *sb)
{
return sb->alloc ? sb->alloc - sb->len - 1 : 0;
}
#endif /* STRBUF_H */