Logo AND Algorithmique Numérique Distribuée

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