Logo AND Algorithmique Numérique Distribuée

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