Logo AND Algorithmique Numérique Distribuée

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