Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
a966f309bb60bd139c88e953aaa3d788af720ccb
[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_empty(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_empty(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->used = res->size = strlen(ctn);
42   return res;
43 }
44
45 /** @brief frees only the container without touching to the contained string */
46 inline void xbt_strbuff_free_container(xbt_strbuff_t b)
47 {
48   free(b);
49 }
50
51 /** @brief frees the buffer and its content */
52 inline void xbt_strbuff_free(xbt_strbuff_t b)
53 {
54   if (b) {
55     free(b->data);
56     free(b);
57   }
58 }
59
60 /** @brief Adds some content at the end of the buffer */
61 void xbt_strbuff_append(xbt_strbuff_t b, const char *toadd)
62 {
63   int addlen;
64   int needed_space;
65
66   xbt_assert(b, "Asked to append stuff to NULL buffer");
67
68   addlen = strlen(toadd);
69   needed_space = b->used + addlen + 1;
70
71   if (needed_space > b->size) {
72     b->size = MAX(minimal_increment + b->used, needed_space);
73     b->data = xbt_realloc(b->data, b->size);
74   }
75   strncpy(b->data + b->used, toadd, b->size-b->used);
76   b->used += addlen;
77 }
78
79 /** @brief format some content and push it at the end of the buffer */
80 void xbt_strbuff_printf(xbt_strbuff_t b, const char *fmt, ...)
81 {
82   va_list ap;
83   va_start(ap, fmt);
84   char *data = bvprintf(fmt, ap);
85   xbt_strbuff_append(b, data);
86   xbt_free(data);
87   va_end(ap);
88 }
89
90 /** @brief Replaces a set of variables by their values
91  *
92  * @param b buffer to modify
93  * @param patterns variables to substitute in the buffer
94  *
95  * Both '$toto' and '${toto}' are valid (and the two writing are equivalent).
96  *
97  * If the variable name contains spaces, use the brace version (ie, ${toto tutu})
98  *
99  * You can provide a default value to use if the variable is not set in the dict by using  '${var:=default}' or
100  * '${var:-default}'. These two forms are equivalent, even if they shouldn't to respect the shell standard (:= form
101  * should set the value in the dict, but does not) (BUG).
102  */
103 void xbt_strbuff_varsubst(xbt_strbuff_t b, xbt_dict_t patterns)
104 {
105   char *end;                    /* pointers around the parsed chunk */
106   int in_simple_quote = 0, in_double_quote = 0;
107   int done = 0;
108
109   if (b->data[0] == '\0')
110     return;
111   end = b->data;
112
113   while (!done) {
114     switch (*end) {
115     case '\\':
116       /* Protected char; pass the protection */
117       end++;
118       xbt_assert(*end != '\0', "String ends with \\");
119       break;
120     case '\'':
121       if (!in_double_quote) {
122         /* simple quote not protected by double ones, note it */
123         in_simple_quote = !in_simple_quote;
124       }
125       break;
126     case '"':
127       if (!in_simple_quote) {
128         /* double quote protected by simple ones, note it */
129         in_double_quote = !in_double_quote;
130       }
131       break;
132     case '$':
133       if (!in_simple_quote) {
134         /* Go for the substitution. First search the variable name */
135         char *beg_var, *end_var;        /* variable name boundary */
136         char *beg_subst, *end_subst = NULL;     /* where value should be written to */
137         char *value, *default_value = NULL;
138         int val_len;
139         beg_subst = end;
140
141         if (*(++end) == '{') {
142           /* the variable name is enclosed in braces. */
143           beg_var = end + 1;
144           /* Search name's end */
145           end_var = beg_var;
146           while (*end_var != '\0' && *end_var != '}') {
147             /* TODO: we do not respect the standard for ":=", we should set this value in the dict */
148             if (*end_var == ':'
149                 && ((*(end_var + 1) == '=') || (*(end_var + 1) == '-'))) {
150               /* damn, we have a default value */
151               char *p = end_var + 1;
152               while (*p != '\0' && *p != '}')
153                 p++;
154               xbt_assert (*p != '\0', "Variable default value not terminated ('}' missing)");
155
156               default_value = xbt_malloc(p - end_var - 1);
157               memcpy(default_value, end_var + 2, p - end_var - 2);
158               default_value[p - end_var - 2] = '\0';
159
160               end_subst = p + 1;        /* eat '}' */
161               break;
162             }
163             end_var++;
164           }
165           xbt_assert(*end_var != '\0', "Variable name not terminated ('}' missing)");
166
167           if (!end_subst)       /* already set if there's a default value */
168             end_subst = end_var + 1;    /* also kill the } in the name */
169
170           xbt_assert(end_var != beg_var, "Variable name empty (${} is not valid)");
171         } else {
172           /* name given directly */
173           beg_var = end;
174           end_var = beg_var;
175           while (*end_var != '\0' && *end_var != ' ' && *end_var != '\t' && *end_var != '\n')
176             end_var++;
177           end_subst = end_var;
178           xbt_assert (end_var != beg_var, "Variable name empty ($ is not valid)");
179         }
180
181         /* ok, we now have the variable name. Search the dictionary for the substituted value */
182         value = xbt_dict_get_or_null_ext(patterns, beg_var, end_var - beg_var);
183
184         if (value)
185           value = xbt_strdup(value);
186         else if (default_value)
187           value = xbt_strdup(default_value);
188         else
189           value = xbt_strdup("");
190
191         /* En route for the actual substitution */
192         val_len = strlen(value);
193         if (val_len <= end_subst - beg_subst) {
194           /* enough room to do the substitute in place */
195           memmove(beg_subst, value, val_len);   /* substitute */
196           /* move the end of the string closer */
197           memmove(beg_subst + val_len, end_subst, b->used - (end_subst - b->data) + 1);
198 //          XBT_DEBUG("String is now: '%s'",b->data);
199           end = beg_subst + val_len;    /* update the currently explored char in the overall loop */
200 //          XBT_DEBUG("end of substituted section is now '%s'",end);
201           b->used -= end_subst - beg_subst - val_len;   /* update string buffer used size */
202 //          XBT_DEBUG("Used:%d end:%d ending char:%d",b->used,end-b->data,*end);
203         } else {
204           /* we have to extend the data area */
205           int tooshort = val_len - (end_subst - beg_subst) + 1 /* don't forget \0 */ ;
206           int newused = b->used + tooshort;
207           end += tooshort;      /* update the pointer of the overall loop */
208 //          XBT_DEBUG("Too short (by %d chars; %d chars left in area)",val_len-(end_subst-beg_subst),b->size - b->used);
209           if (newused > b->size) {
210             /* We have to realloc the data area before (because b->size is too small).
211              * We have to update our pointers, too */
212             char *newdata = xbt_realloc(b->data, b->used + MAX(minimal_increment, tooshort));
213             int offset = newdata - b->data;
214             b->data = newdata;
215             b->size = b->used + MAX(minimal_increment, tooshort);
216             end += offset;
217             beg_subst += offset;
218             end_subst += offset;
219           }
220           /* move the end of the string a bit further */
221           memmove(beg_subst + val_len, end_subst, b->used - (end_subst - b->data) + 1);
222           memmove(beg_subst, value, val_len);   /* substitute */
223           b->used = newused;
224 //          XBT_DEBUG("String is now: %s",b->data);
225         }
226         free(value);
227         free(default_value);
228         end--;                  /* compensate the next end++ */
229       }
230       break;
231     case '\0':
232       done = 1;
233       break;
234     }
235     end++;
236   }
237 }
238
239 #ifdef SIMGRID_TEST
240 #include "xbt/strbuff.h"
241
242 /* buffstr have 512 chars by default. Adding 1000 chars like this will force a resize, allowing us to test that
243  * b->used and b->size are consistent */
244 #define force_resize \
245   "1.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
246   "2.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
247   "3.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
248   "4.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
249   "5.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
250   "6.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
251   "7.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
252   "8.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
253   "9.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
254   "0.........1.........2.........3.........4.........5.........6.........7.........8.........9........."
255
256 static void mytest(const char *input, const char *patterns, const char *expected)
257 {
258   xbt_dynar_t dyn_patterns;     /* splited string */
259   xbt_dict_t p;                 /* patterns */
260   unsigned int cpt;
261   char *str;                    /*foreach */
262   xbt_strbuff_t sb;             /* what we test */
263
264   p = xbt_dict_new_homogeneous(free);
265   dyn_patterns = xbt_str_split(patterns, " ");
266   xbt_dynar_foreach(dyn_patterns, cpt, str) {
267     xbt_dynar_t keyvals = xbt_str_split(str, "=");
268     char *key = xbt_dynar_get_as(keyvals, 0, char *);
269     char *val = xbt_dynar_get_as(keyvals, 1, char *);
270     xbt_str_subst(key, '_', ' ', 0);    // to put space in names without breaking the enclosing dynar_foreach
271     xbt_dict_set(p, key, xbt_strdup(val), NULL);
272     xbt_dynar_free(&keyvals);
273   }
274   xbt_dynar_free(&dyn_patterns);
275   sb = xbt_strbuff_new();
276   xbt_strbuff_append(sb, input);
277   xbt_strbuff_varsubst(sb, p);
278   xbt_dict_free(&p);
279   xbt_test_assert(!strcmp(sb->data, expected), "Input (%s) with patterns (%s) leads to (%s) instead of (%s)",
280                    input, patterns, sb->data, expected);
281   xbt_strbuff_free(sb);
282 }
283
284 XBT_TEST_SUITE("xbt_strbuff", "String Buffers");
285 XBT_TEST_UNIT("xbt_strbuff_substitute", test_strbuff_substitute, "test the function xbt_strbuff_substitute")
286 {
287   xbt_test_add("Empty");
288   mytest("", "", "");
289
290   xbt_test_add("Value shorter, no braces, only variable");
291   mytest("$tutu", "tutu=t", "t");
292   xbt_test_add("Value shorter, braces, only variable");
293   mytest("${tutu}", "tutu=t", "t");
294   xbt_test_add("Value shorter, no braces, data after");
295   mytest("$tutu toto", "tutu=t", "t toto");
296   xbt_test_add("Value shorter, braces, data after");
297   mytest("${tutu} toto", "tutu=t", "t toto");
298   xbt_test_add("Value shorter, no braces, data before");
299   mytest("toto $tutu", "tutu=t", "toto t");
300   xbt_test_add("Value shorter, braces, data before");
301   mytest("toto ${tutu}", "tutu=t", "toto t");
302   xbt_test_add("Value shorter, no braces, data before and after");
303   mytest("toto $tutu tata", "tutu=t", "toto t tata");
304   xbt_test_add("Value shorter, braces, data before and after");
305   mytest("toto ${tutu} tata", "tutu=t", "toto t tata");
306
307   xbt_test_add("Value as long, no braces, only variable");
308   mytest("$tutu", "tutu=12345", "12345");
309   xbt_test_add("Value as long, braces, only variable");
310   mytest("${tutu}", "tutu=1234567", "1234567");
311   xbt_test_add("Value as long, no braces, data after");
312   mytest("$tutu toto", "tutu=12345", "12345 toto");
313   xbt_test_add("Value as long, braces, data after");
314   mytest("${tutu} toto", "tutu=1234567", "1234567 toto");
315   xbt_test_add("Value as long, no braces, data before");
316   mytest("toto $tutu", "tutu=12345", "toto 12345");
317   xbt_test_add("Value as long, braces, data before");
318   mytest("toto ${tutu}", "tutu=1234567", "toto 1234567");
319   xbt_test_add("Value as long, no braces, data before and after");
320   mytest("toto $tutu tata", "tutu=12345", "toto 12345 tata");
321   xbt_test_add("Value as long, braces, data before and after");
322   mytest("toto ${tutu} tata", "tutu=1234567", "toto 1234567 tata");
323
324   xbt_test_add("Value longer, no braces, only variable");
325   mytest("$t", "t=tututu", "tututu");
326   xbt_test_add("Value longer, braces, only variable");
327   mytest("${t}", "t=tututu", "tututu");
328   xbt_test_add("Value longer, no braces, data after");
329   mytest("$t toto", "t=tututu", "tututu toto");
330   xbt_test_add("Value longer, braces, data after");
331   mytest("${t} toto", "t=tututu", "tututu toto");
332   xbt_test_add("Value longer, no braces, data before");
333   mytest("toto $t", "t=tututu", "toto tututu");
334   xbt_test_add("Value longer, braces, data before");
335   mytest("toto ${t}", "t=tututu", "toto tututu");
336   xbt_test_add("Value longer, no braces, data before and after");
337   mytest("toto $t tata", "t=tututu", "toto tututu tata");
338   xbt_test_add("Value longer, braces, data before and after");
339   mytest("toto ${t} tata", "t=tututu", "toto tututu tata");
340
341   xbt_test_add("Value much longer, no braces, only variable");
342   mytest("$t", "t=" force_resize, force_resize);
343   xbt_test_add("Value much longer, no braces, data after");
344   mytest("$t toto", "t=" force_resize, force_resize " toto");
345   xbt_test_add("Value much longer, braces, data after");
346   mytest("${t} toto", "t=" force_resize, force_resize " toto");
347   xbt_test_add("Value much longer, no braces, data before");
348   mytest("toto $t", "t=" force_resize, "toto " force_resize);
349   xbt_test_add("Value much longer, braces, data before");
350   mytest("toto ${t}", "t=" force_resize, "toto " force_resize);
351   xbt_test_add("Value much longer, no braces, data before and after");
352   mytest("toto $t tata", "t=" force_resize, "toto " force_resize " tata");
353   xbt_test_add("Value much longer, braces, data before and after");
354   mytest("toto ${t} tata", "t=" force_resize, "toto " force_resize " tata");
355
356   xbt_test_add("Escaped $");
357   mytest("\\$tutu", "tutu=t", "\\$tutu");
358   xbt_test_add("Space in var name (with braces)");
359   mytest("${tu ti}", "tu_ti=t", "t");
360
361   xbt_test_add("Two variables");
362   mytest("$toto $tutu", "toto=1 tutu=2", "1 2");
363
364   // Commented: I'm too lazy to do a memmove in var name to remove the backslash after use.
365   // Users should use braces.
366   //  xbt_test_add("Escaped space in var name", "$tu\\ ti", "tu_ti=t", "t");
367
368   xbt_test_add("Default value");
369   mytest("${t:-toto}", "", "toto");
370   xbt_test_add("Useless default value (variable already defined)");
371   mytest("${t:-toto}", "t=TRUC", "TRUC");
372 }
373 #endif                          /* SIMGRID_TEST */