7 #define MAX(a, b) ((a) < (b) ? (b) : (a))
10 static void sbuf_extend(struct sbuf
*sbuf
, int amount
)
13 sbuf
->sz
= (MAX(1, amount
) + SBUF_SZ
- 1) & ~(SBUF_SZ
- 1);
14 sbuf
->s
= malloc(sbuf
->sz
);
16 memcpy(sbuf
->s
, s
, sbuf
->n
);
20 void sbuf_init(struct sbuf
*sbuf
)
22 memset(sbuf
, 0, sizeof(*sbuf
));
23 sbuf_extend(sbuf
, SBUF_SZ
);
26 void sbuf_add(struct sbuf
*sbuf
, int c
)
28 if (sbuf
->n
+ 2 >= sbuf
->sz
)
29 sbuf_extend(sbuf
, sbuf
->sz
* 2);
30 sbuf
->s
[sbuf
->n
++] = c
;
33 void sbuf_append(struct sbuf
*sbuf
, char *s
)
36 if (sbuf
->n
+ len
+ 1 >= sbuf
->sz
)
37 sbuf_extend(sbuf
, sbuf
->n
+ len
+ 1);
38 memcpy(sbuf
->s
+ sbuf
->n
, s
, len
);
42 void sbuf_printf(struct sbuf
*sbuf
, char *s
, ...)
49 sbuf_append(sbuf
, buf
);
52 void sbuf_putnl(struct sbuf
*sbuf
)
54 if (sbuf
->n
&& sbuf
->s
[sbuf
->n
- 1] != '\n')
58 int sbuf_empty(struct sbuf
*sbuf
)
63 char *sbuf_buf(struct sbuf
*sbuf
)
65 sbuf
->s
[sbuf
->n
] = '\0';
69 int sbuf_len(struct sbuf
*sbuf
)
74 /* shorten the sbuf */
75 void sbuf_cut(struct sbuf
*sbuf
, int n
)
81 void sbuf_done(struct sbuf
*sbuf
)