Logo AND Algorithmique Numérique Distribuée

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