Logo AND Algorithmique Numérique Distribuée

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