1 /* strbuff -- string buffers */
3 /* Copyright (c) 2007-2015. The SimGrid Team.
4 * All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
9 #include "xbt/strbuff.h"
12 #define minimal_increment 512
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(strbuff, xbt, "String buffers");
16 /** @brief Remove any content from the buffer */
17 inline void xbt_strbuff_clear(xbt_strbuff_t b)
23 /** @brief Constructor */
24 xbt_strbuff_t xbt_strbuff_new(void)
26 xbt_strbuff_t res = xbt_malloc(sizeof(s_xbt_strbuff_t));
27 res->data = xbt_malloc(512);
29 xbt_strbuff_clear(res);
33 /** @brief creates a new string buffer containing the provided string
35 * Beware, the ctn is copied, you want to free it afterward, anyhow
37 inline xbt_strbuff_t xbt_strbuff_new_from(const char *ctn)
39 xbt_strbuff_t res = xbt_malloc(sizeof(s_xbt_strbuff_t));
40 res->data = xbt_strdup(ctn);
41 res->size = strlen(ctn);
42 res->used = res->size;
46 /** @brief frees only the container without touching to the contained string */
47 inline void xbt_strbuff_free_container(xbt_strbuff_t b)
52 /** @brief frees the buffer and its content */
53 inline void xbt_strbuff_free(xbt_strbuff_t b)
61 /** @brief Adds some content at the end of the buffer */
62 void xbt_strbuff_append(xbt_strbuff_t b, const char *toadd)
67 xbt_assert(b, "Asked to append stuff to NULL buffer");
69 addlen = strlen(toadd);
70 needed_space = b->used + addlen + 1;
72 if (needed_space > b->size) {
73 b->size = MAX(minimal_increment + b->used, needed_space);
74 b->data = xbt_realloc(b->data, b->size);
76 strncpy(b->data + b->used, toadd, b->size-b->used);
80 /** @brief format some content and push it at the end of the buffer */
81 void xbt_strbuff_printf(xbt_strbuff_t b, const char *fmt, ...)
85 char *data = bvprintf(fmt, ap);
86 xbt_strbuff_append(b, data);