Logo AND Algorithmique Numérique Distribuée

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