Logo AND Algorithmique Numérique Distribuée

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