Logo AND Algorithmique Numérique Distribuée

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