Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
e87d383c708c44980fb8b169d509c14e6165e592
[simgrid.git] / src / xbt / xbt_strbuff.c
1 /* strbuff -- string buffers                                                */
2
3 /* Copyright (c) 2007-2015. The SimGrid Team.
4  * All rights reserved.                                                     */
5
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. */
8
9 #include "xbt/strbuff.h"
10 #include <stdarg.h>
11
12 #define minimal_increment 512
13
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(strbuff, xbt, "String buffers");
15
16 /** @brief Remove any content from the buffer */
17 inline void xbt_strbuff_clear(xbt_strbuff_t b)
18 {
19   b->used = 0;
20   b->data[0] = '\0';
21 }
22
23 /** @brief Constructor */
24 xbt_strbuff_t xbt_strbuff_new(void)
25 {
26   xbt_strbuff_t res = xbt_malloc(sizeof(s_xbt_strbuff_t));
27   res->data = xbt_malloc(512);
28   res->size = 512;
29   xbt_strbuff_clear(res);
30   return res;
31 }
32
33 /** @brief creates a new string buffer containing the provided string
34  *
35  * Beware, the ctn is copied, you want to free it afterward, anyhow
36  */
37 inline xbt_strbuff_t xbt_strbuff_new_from(const char *ctn)
38 {
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;
43   return res;
44 }
45
46 /** @brief frees only the container without touching to the contained string */
47 inline void xbt_strbuff_free_container(xbt_strbuff_t b)
48 {
49   free(b);
50 }
51
52 /** @brief frees the buffer and its content */
53 inline void xbt_strbuff_free(xbt_strbuff_t b)
54 {
55   if (b) {
56     free(b->data);
57     free(b);
58   }
59 }
60
61 /** @brief Adds some content at the end of the buffer */
62 void xbt_strbuff_append(xbt_strbuff_t b, const char *toadd)
63 {
64   int addlen;
65   int needed_space;
66
67   xbt_assert(b, "Asked to append stuff to NULL buffer");
68
69   addlen = strlen(toadd);
70   needed_space = b->used + addlen + 1;
71
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);
75   }
76   strncpy(b->data + b->used, toadd, b->size-b->used);
77   b->used += addlen;
78 }
79
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, ...)
82 {
83   va_list ap;
84   va_start(ap, fmt);
85   char *data = bvprintf(fmt, ap);
86   xbt_strbuff_append(b, data);
87   xbt_free(data);
88   va_end(ap);
89 }