Logo AND Algorithmique Numérique Distribuée

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