Logo AND Algorithmique Numérique Distribuée

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