tmus

TUI Music Player
git clone https://git.sinitax.com/sinitax/tmus
Log | Files | Refs | Submodules | LICENSE | sfeed.txt

strbuf.c (923B)


      1#include "strbuf.h"
      2
      3#include "util.h"
      4
      5#include <stdio.h>
      6#include <stdarg.h>
      7#include <string.h>
      8
      9void
     10strbuf_init(struct strbuf *strbuf)
     11{
     12	strbuf->buf = NULL;
     13	strbuf->cap = 0;
     14}
     15
     16void
     17strbuf_deinit(struct strbuf *strbuf)
     18{
     19	free(strbuf->buf);
     20}
     21
     22void
     23strbuf_clear(struct strbuf *strbuf)
     24{
     25	if (!strbuf->buf)
     26		strbuf_append(strbuf, "");
     27
     28	strbuf->buf[0] = '\0';
     29}
     30
     31void
     32strbuf_append(struct strbuf *strbuf, const char *fmt, ...)
     33{
     34	va_list ap, cpy;
     35	ssize_t slen;
     36	int blen;
     37
     38	va_copy(cpy, ap);
     39
     40	blen = strbuf->buf ? strlen(strbuf->buf) : 0;
     41
     42	va_start(cpy, fmt);
     43	slen = vsnprintf(NULL, 0, fmt, cpy);
     44	if (slen < 0) ERROR(SYSTEM, "snprintf");
     45	va_end(cpy);
     46
     47	if (blen + slen + 1 > strbuf->cap) {
     48		strbuf->cap = blen + slen + 1;
     49		strbuf->buf = realloc(strbuf->buf, strbuf->cap);
     50		if (!strbuf->buf) ERROR(SYSTEM, "realloc");
     51	}
     52
     53	va_start(ap, fmt);
     54	vsnprintf(strbuf->buf + blen, slen + 1, fmt, ap);
     55	va_end(ap);
     56}