c0
C0DATA — structured data using ASCII C0 control codes (C)
Loading...
Searching...
No Matches
c0_strbuf.h
Go to the documentation of this file.
1/* c0_strbuf.h — a tiny growable byte buffer shared by the converter sources.
2 * static inline so it can be included into multiple translation units. */
3#ifndef C0_STRBUF_H
4#define C0_STRBUF_H
5
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9
10typedef struct {
11 uint8_t *d;
12 size_t n;
13 size_t cap;
14 int oom;
15} c0_strbuf;
16
17static inline int c0_sb_reserve(c0_strbuf *s, size_t extra) {
18 if (s->oom) return 0;
19 if (s->n + extra > s->cap) {
20 size_t ncap = s->cap ? s->cap : 64;
21 uint8_t *nd;
22 while (ncap < s->n + extra) ncap *= 2;
23 nd = (uint8_t *)realloc(s->d, ncap);
24 if (!nd) {
25 s->oom = 1;
26 return 0;
27 }
28 s->d = nd;
29 s->cap = ncap;
30 }
31 return 1;
32}
33
34static inline void c0_sb_byte(c0_strbuf *s, uint8_t b) {
35 if (c0_sb_reserve(s, 1)) s->d[s->n++] = b;
36}
37
38static inline void c0_sb_raw(c0_strbuf *s, const uint8_t *p, size_t n) {
39 if (n && c0_sb_reserve(s, n)) {
40 memcpy(s->d + s->n, p, n);
41 s->n += n;
42 }
43}
44
45static inline void c0_sb_cstr(c0_strbuf *s, const char *p) {
46 c0_sb_raw(s, (const uint8_t *)p, strlen(p));
47}
48
49#endif /* C0_STRBUF_H */
Definition c0_strbuf.h:10
int oom
Definition c0_strbuf.h:14
size_t n
Definition c0_strbuf.h:12
size_t cap
Definition c0_strbuf.h:13
uint8_t * d
Definition c0_strbuf.h:11