Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
tiny documentation improvement
[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_new_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  * You can provide a default value to use if the variable is not set in the dict by using
99  * '${var:=default}' or '${var:-default}'. These two forms are equivalent, even if they
100  * shouldn't to respect the shell standard (:= form should set the value in the dict,
101  * but does not) (BUG).
102  */
103 void xbt_strbuff_varsubst(xbt_strbuff_t b, xbt_dict_t patterns) {
104
105   char *end; /* pointers around the parsed chunk */
106   int in_simple_quote=0, in_double_quote=0;
107   int done = 0;
108
109   if (b->data[0] == '\0')
110     return;
111   end = b->data;
112
113   while (!done) {
114
115     switch (*end) {
116       case '\\':
117         /* Protected char; pass the protection */
118         end++;
119         if (*end=='\0')
120           THROW0(arg_error,0,"String ends with \\");
121         break;
122
123       case '\'':
124         if (!in_double_quote) {
125           /* simple quote not protected by double ones, note it */
126           in_simple_quote = !in_simple_quote;
127         }
128         break;
129       case '"':
130         if (!in_simple_quote) {
131           /* double quote protected by simple ones, note it */
132           in_double_quote = !in_double_quote;
133         }
134         break;
135
136       case '$':
137         if (!in_simple_quote) {
138           /* Go for the substitution. First search the variable name */
139           char *beg_var,*end_var; /* variable name boundary */
140           char *beg_subst, *end_subst=NULL; /* where value should be written to */
141           char *value, *default_value=NULL;
142           int val_len;
143           beg_subst = end;
144
145
146           if (*(++end) == '{') {
147             /* the variable name is enclosed in braces. */
148             beg_var = end+1;
149             /* Search name's end */
150             end_var = beg_var;
151             while (*end_var != '\0' && *end_var != '}') {
152               /* TODO: we do not respect the standard for ":=", we should set this value in the dict */
153               if (*end_var == ':' && ((*(end_var+1) == '=') || (*(end_var+1) == '-'))) {
154                 /* damn, we have a default value */
155                 char *p = end_var+1;
156                 while (*p != '\0' && *p != '}')
157                   p++;
158                 if (*p == '\0')
159                   THROW0(arg_error,0,"Variable default value not terminated ('}' missing)");
160
161                 default_value = xbt_malloc(p-end_var-1);
162                 memcpy(default_value, end_var+2, p-end_var-2);
163                 default_value[p-end_var-2] = '\0';
164
165                 end_subst = p+1; /* eat '}' */
166
167                 break;
168               }
169               end_var++;
170             }
171             if (*end_var == '\0')
172               THROW0(arg_error,0,"Variable name not terminated ('}' missing)");
173
174             if (!end_subst) /* already set if there's a default value */
175               end_subst = end_var+1; /* also kill the } in the name */
176
177             if (end_var == beg_var)
178               THROW0(arg_error,0,"Variable name empty (${} is not valid)");
179
180
181           } else {
182             /* name given directly */
183             beg_var = end;
184             end_var = beg_var;
185             while (*end_var != '\0' && *end_var != ' ' && *end_var != '\t' && *end_var != '\n')
186               end_var++;
187             end_subst = end_var;
188             if (end_var == beg_var)
189               THROW0(arg_error,0,"Variable name empty ($ is not valid)");
190           }
191 //          DEBUG1("End_var = %s",end_var);
192
193           /* ok, we now have the variable name. Search the dictionary for the substituted value */
194           value = xbt_dict_get_or_null_ext(patterns,beg_var,end_var-beg_var);
195 //          DEBUG4("Search for %.*s, found %s (default value = %s)\n",
196 //                  end_var-beg_var,beg_var,
197 //                  (value?value:"NULL"),
198 //                  (default_value?default_value:"NULL"));
199
200           if (value)
201             value = xbt_strdup(value);
202           else
203             value = xbt_strdup(default_value);
204
205           if (!value)
206             value = xbt_strdup("");
207
208           /* En route for the actual substitution */
209           val_len = strlen(value);
210 //          DEBUG2("val_len = %d, key_len=%d",val_len,end_subst-beg_subst);
211           if (val_len <= end_subst-beg_subst) {
212             /* enough room to do the substitute in place */
213 //            INFO3("Substitute '%s' with '%s' for %d chars",beg_subst,value, val_len);
214             memmove(beg_subst,value,val_len); /* substitute */
215 //            INFO3("Substitute '%s' with '%s' for %d chars",beg_subst+val_len,end_subst, b->used-(end_subst-b->data)+1);
216             memmove(beg_subst+val_len,end_subst, b->used-(end_subst - b->data)+1); /* move the end of the string closer */
217             end = beg_subst+val_len; /* update the currently explored char in the overall loop*/
218             b->used -= end_subst-beg_subst-val_len;  /* update string buffer used size */
219           } else {
220             /* we have to extend the data area */
221             int tooshort = val_len-(end_subst-beg_subst) +1/*don't forget \0*/;
222             int newused = b->used + tooshort;
223             end += tooshort; /* update the pointer of the overall loop */
224 //            DEBUG2("Too short (by %d chars; %d chars left in area)",val_len- (end_subst-beg_subst), b->size - b->used);
225             if (newused > b->size) {
226               /* We have to realloc the data area before (because b->size is too small). We have to update our pointers, too */
227               char *newdata = realloc(b->data, b->used + MAX(minimal_increment,tooshort));
228               int offset = newdata - b->data;
229               b->data = newdata;
230               b->size = b->used + MAX(minimal_increment,tooshort);
231               end += offset;
232               beg_subst += offset;
233               end_subst += offset;
234             }
235             memmove(beg_subst+val_len,end_subst, b->used-(end_subst - b->data)+2); /* move the end of the string a bit further */
236             memmove(beg_subst,value,val_len); /* substitute */
237             b->used = newused;
238           }
239           free(value);
240
241           if (default_value)
242             free(default_value);
243         }
244         break;
245
246       case '\0':
247         done=1;
248     }
249     end++;
250   }
251 }
252
253 #ifdef SIMGRID_TEST
254 #include "xbt/strbuff.h"
255
256 /* 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 */
257 #define force_resize \
258   "1.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
259   "2.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
260   "3.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
261   "4.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
262   "5.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
263   "6.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
264   "7.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
265   "8.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
266   "9.........1.........2.........3.........4.........5.........6.........7.........8.........9........." \
267   "0.........1.........2.........3.........4.........5.........6.........7.........8.........9........."
268
269 static void mytest(const char *input, const char *patterns, const char *expected) {
270   xbt_dynar_t dyn_patterns; /* splited string */
271   xbt_dict_t p; /* patterns */
272   unsigned int cpt;  char *str; /*foreach*/
273   xbt_strbuff_t sb; /* what we test */
274
275   p=xbt_dict_new();
276   dyn_patterns=xbt_str_split(patterns," ");
277   xbt_dynar_foreach(dyn_patterns,cpt,str) {
278     xbt_dynar_t keyvals = xbt_str_split(str,"=");
279     char *key = xbt_dynar_get_as(keyvals,0,char*);
280     char *val = xbt_dynar_get_as(keyvals,1,char*);
281     xbt_str_subst(key,'_',' ',0); // to put space in names without breaking the enclosing dynar_foreach
282     xbt_dict_set(p,key,xbt_strdup(val),free);
283     xbt_dynar_free(&keyvals);
284   }
285   xbt_dynar_free(&dyn_patterns);
286   sb = xbt_strbuff_new();
287   xbt_strbuff_append(sb,input);
288   xbt_strbuff_varsubst(sb, p);
289   xbt_dict_free(&p);
290   xbt_test_assert4(!strcmp(sb->data,expected),
291                    "Input (%s) with patterns (%s) leads to (%s) instead of (%s)",
292                    input,patterns,sb->data,expected);
293   xbt_strbuff_free(sb);
294 }
295
296 XBT_TEST_SUITE("xbt_strbuff","String Buffers");
297 XBT_TEST_UNIT("xbt_strbuff_substitute",test_strbuff_substitute, "test the function xbt_strbuff_substitute") {
298   xbt_test_add0("Empty");mytest("", "", "");
299
300   xbt_test_add0("Value shorter, no braces, only variable");mytest("$tutu", "tutu=t", "t");
301   xbt_test_add0("Value shorter, braces, only variable");mytest("${tutu}", "tutu=t", "t");
302   xbt_test_add0("Value shorter, no braces, data after");mytest("$tutu toto", "tutu=t", "t toto");
303   xbt_test_add0("Value shorter, braces, data after");mytest("${tutu} toto", "tutu=t", "t toto");
304   xbt_test_add0("Value shorter, no braces, data before");mytest("toto $tutu", "tutu=t", "toto t");
305   xbt_test_add0("Value shorter, braces, data before");mytest("toto ${tutu}", "tutu=t", "toto t");
306   xbt_test_add0("Value shorter, no braces, data before and after");mytest("toto $tutu tata", "tutu=t", "toto t tata");
307   xbt_test_add0("Value shorter, braces, data before and after");mytest("toto ${tutu} tata", "tutu=t", "toto t tata");
308
309   xbt_test_add0("Value as long, no braces, only variable");mytest("$tutu", "tutu=12345", "12345");
310   xbt_test_add0("Value as long, braces, only variable");mytest("${tutu}", "tutu=1234567", "1234567");
311   xbt_test_add0("Value as long, no braces, data after");mytest("$tutu toto", "tutu=12345", "12345 toto");
312   xbt_test_add0("Value as long, braces, data after");mytest("${tutu} toto", "tutu=1234567", "1234567 toto");
313   xbt_test_add0("Value as long, no braces, data before");mytest("toto $tutu", "tutu=12345", "toto 12345");
314   xbt_test_add0("Value as long, braces, data before");mytest("toto ${tutu}", "tutu=1234567", "toto 1234567");
315   xbt_test_add0("Value as long, no braces, data before and after");mytest("toto $tutu tata", "tutu=12345", "toto 12345 tata");
316   xbt_test_add0("Value as long, braces, data before and after");mytest("toto ${tutu} tata", "tutu=1234567", "toto 1234567 tata");
317
318   xbt_test_add0("Value longer, no braces, only variable");mytest("$t", "t=tututu", "tututu");
319   xbt_test_add0("Value longer, braces, only variable");mytest("${t}", "t=tututu", "tututu");
320   xbt_test_add0("Value longer, no braces, data after");mytest("$t toto", "t=tututu", "tututu toto");
321   xbt_test_add0("Value longer, braces, data after");mytest("${t} toto", "t=tututu", "tututu toto");
322   xbt_test_add0("Value longer, no braces, data before");mytest("toto $t", "t=tututu", "toto tututu");
323   xbt_test_add0("Value longer, braces, data before");mytest("toto ${t}", "t=tututu", "toto tututu");
324   xbt_test_add0("Value longer, no braces, data before and after");mytest("toto $t tata", "t=tututu", "toto tututu tata");
325   xbt_test_add0("Value longer, braces, data before and after");mytest("toto ${t} tata", "t=tututu", "toto tututu tata");
326
327   xbt_test_add0("Value much longer, no braces, only variable");mytest("$t", "t=" force_resize, force_resize);
328   xbt_test_add0("Value much longer, no braces, data after");mytest("$t toto", "t=" force_resize, force_resize " toto");
329   xbt_test_add0("Value much longer, braces, data after");mytest("${t} toto", "t=" force_resize, force_resize " toto");
330   xbt_test_add0("Value much longer, no braces, data before");mytest("toto $t", "t=" force_resize, "toto " force_resize);
331   xbt_test_add0("Value much longer, braces, data before");mytest("toto ${t}", "t=" force_resize, "toto " force_resize);
332   xbt_test_add0("Value much longer, no braces, data before and after");mytest("toto $t tata", "t=" force_resize, "toto " force_resize " tata");
333   xbt_test_add0("Value much longer, braces, data before and after");mytest("toto ${t} tata", "t=" force_resize, "toto " force_resize " tata");
334
335   xbt_test_add0("Escaped $");mytest("\\$tutu", "tutu=t", "\\$tutu");
336   xbt_test_add0("Space in var name (with braces)");mytest("${tu ti}", "tu_ti=t", "t");
337
338   xbt_test_add0("Two variables");mytest("$toto $tutu","toto=1 tutu=2", "1 2");
339
340   // Commented: I'm too lazy to do a memmove in var name to remove the backslash after use.
341   // Users should use braces.
342   //  xbt_test_add0("Escaped space in var name", "$tu\\ ti", "tu_ti=t", "t");
343
344   xbt_test_add0("Default value");mytest("${t:-toto}", "", "toto");
345   xbt_test_add0("Useless default value (variable already defined)");mytest("${t:-toto}", "t=TRUC", "TRUC");
346
347 }
348
349 #endif /* SIMGRID_TEST */