Logo AND Algorithmique Numérique Distribuée

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