5 * Modifications (2010-10-19):
6 * - add license header.
7 * - remove unneeded functions.
14 * Strbuf's can be use in many ways: as a byte array, or to store arbitrary
15 * long, overflow safe strings.
17 * Strbufs has some invariants that are very important to keep in mind:
19 * 1. the ->buf member is always malloc-ed, hence strbuf's can be used to
20 * build complex strings/buffers whose final size isn't easily known.
22 * It is NOT legal to copy the ->buf pointer away.
24 * 2. the ->buf member is a byte array that has at least ->len + 1 bytes
25 * allocated. The extra byte is used to store a '\0', allowing the ->buf
26 * member to be a valid C-string. Every strbuf function ensures this
27 * invariant is preserved.
29 * Note that it is OK to "play" with the buffer directly if you work it
32 * strbuf_grow(sb, SOME_SIZE);
33 * ... Here, the memory array starting at sb->buf, and of length
34 * ... strbuf_avail(sb) is all yours, and you are sure that
35 * ... strbuf_avail(sb) is at least SOME_SIZE.
36 * strbuf_setlen(sb, sb->len + SOME_OTHER_SIZE);
38 * Doing so is safe, though if it has to be done in many places, adding the
39 * missing API to the strbuf module is the way to go.
41 * XXX: do _not_ assume that the area that is yours is of size ->alloc - 1
42 * even if it's true in the current implementation. Alloc is somehow a
43 * "private" member that should not be messed with.
48 extern char strbuf_slopbuf
[];
55 #define STRBUF_INIT { 0, 0, strbuf_slopbuf }
57 /*----- strbuf life cycle -----*/
58 extern void strbuf_init(struct strbuf
*, size_t);
59 extern void strbuf_release(struct strbuf
*);
61 /*----- strbuf size related -----*/
62 extern void strbuf_grow(struct strbuf
*, size_t);
64 static inline void strbuf_setlen(struct strbuf
*sb
, size_t len
) {
67 assert(len
< sb
->alloc
);
71 #define strbuf_reset(sb) strbuf_setlen(sb, 0)
73 /*----- add data in your buffer -----*/
74 static inline void strbuf_addch(struct strbuf
*sb
, int c
) {
76 sb
->buf
[sb
->len
++] = c
;
77 sb
->buf
[sb
->len
] = '\0';
80 extern void strbuf_add(struct strbuf
*, const void *, size_t);
82 extern size_t strbuf_fread(struct strbuf
*, size_t, FILE *);