2 * collectd - src/utils_strbuf.c
3 * Copyright (C) 2018 Florian Forster
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26 * Florian Forster <octo at collectd.org>
29 #include "utils_strbuf.h"
34 strbuf_t *strbuf_create(size_t sz) /* {{{ */
38 buf = malloc(sizeof(*buf));
41 memset(buf, 0, sizeof(*buf));
43 buf->buffer = malloc(sz);
44 if (buf->buffer == NULL) {
48 memset(buf->buffer, 0, sz);
54 } /* }}} int strbuf_t *strbuf_create */
56 void strbuf_destroy(strbuf_t *buf) /* {{{ */
63 } /* }}} void strbuf_destroy */
65 void strbuf_reset(strbuf_t *buf) /* {{{ */
67 buf->free += buf->used;
70 } /* }}} void strbuf_reset */
72 int strbuf_add(strbuf_t *buf, char const *str) /* {{{ */
74 char *base = buf->buffer + buf->used;
75 size_t len = strlen(str);
80 /* len+1 so copied memory includes the trailing nil. */
81 memcpy(base, str, len + 1);
85 assert(buf->buffer[buf->used] == 0);
88 } /* }}} int strbuf_add */
90 __attribute__((format(printf, 2, 3))) int
91 strbuf_addf(strbuf_t *buf, char const *format, ...) /* {{{ */
94 char *base = buf->buffer + buf->used;
99 status = vsnprintf(base, buf->free, format, ap);
105 len = (size_t)status;
106 if (len >= buf->free) /* truncated */
108 base[0] = 0; /* make sure buffer appears unmodified. */
115 assert(buf->buffer[buf->used] == 0);
118 } /* }}} int strbuf_addf */
120 /* vim: set sw=2 sts=2 et fdm=marker : */