Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Avoid depending on C++11 stuff when including C/SMPI headers
[simgrid.git] / src / xbt / xbt_str.cpp
1 /* xbt_str.cpp - various helping functions to deal with strings               */
2
3 /* Copyright (c) 2007-2014. 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/ex.hpp>
10 #include "src/internal_config.h"
11 #include "xbt/misc.h"
12 #include "xbt/sysdep.h"
13 #include "xbt/str.h"            /* headers of these functions */
14 #include "xbt/strbuff.h"
15
16 /**  @brief Strip whitespace (or other characters) from the end of a string.
17  *
18  * Strips the whitespaces from the end of s.
19  * By default (when char_list=NULL), these characters get stripped:
20  *
21  *  - " "    (ASCII 32  (0x20))  space.
22  *  - "\t"    (ASCII 9  (0x09))  tab.
23  *  - "\n"    (ASCII 10  (0x0A))  line feed.
24  *  - "\r"    (ASCII 13  (0x0D))  carriage return.
25  *  - "\0"    (ASCII 0  (0x00))  NULL.
26  *  - "\x0B"  (ASCII 11  (0x0B))  vertical tab.
27  *
28  * @param s The string to strip. Modified in place.
29  * @param char_list A string which contains the characters you want to strip.
30  */
31 void xbt_str_rtrim(char *s, const char *char_list)
32 {
33   char *cur = s;
34   const char *__char_list = " \t\n\r\x0B";
35   char white_char[256] = { 1, 0 };
36
37   if (!s)
38     return;
39
40   if (!char_list) {
41     while (*__char_list) {
42       white_char[(unsigned char) *__char_list++] = 1;
43     }
44   } else {
45     while (*char_list) {
46       white_char[(unsigned char) *char_list++] = 1;
47     }
48   }
49
50   while (*cur)
51     ++cur;
52
53   while ((cur >= s) && white_char[(unsigned char) *cur])
54     --cur;
55
56   *++cur = '\0';
57 }
58
59 /**  @brief Strip whitespace (or other characters) from the beginning of a string.
60  *
61  * Strips the whitespaces from the begining of s.
62  * By default (when char_list=NULL), these characters get stripped:
63  *
64  *  - " "    (ASCII 32  (0x20))  space.
65  *  - "\t"    (ASCII 9  (0x09))  tab.
66  *  - "\n"    (ASCII 10  (0x0A))  line feed.
67  *  - "\r"    (ASCII 13  (0x0D))  carriage return.
68  *  - "\0"    (ASCII 0  (0x00))  NULL.
69  *  - "\x0B"  (ASCII 11  (0x0B))  vertical tab.
70  *
71  * @param s The string to strip. Modified in place.
72  * @param char_list A string which contains the characters you want to strip.
73  */
74 void xbt_str_ltrim(char *s, const char *char_list)
75 {
76   char *cur = s;
77   const char *__char_list = " \t\n\r\x0B";
78   char white_char[256] = { 1, 0 };
79
80   if (!s)
81     return;
82
83   if (!char_list) {
84     while (*__char_list) {
85       white_char[(unsigned char) *__char_list++] = 1;
86     }
87   } else {
88     while (*char_list) {
89       white_char[(unsigned char) *char_list++] = 1;
90     }
91   }
92
93   while (*cur && white_char[(unsigned char) *cur])
94     ++cur;
95
96   memmove(s, cur, strlen(cur) + 1);
97 }
98
99 /**  @brief Strip whitespace (or other characters) from the end and the begining of a string.
100  *
101  * Strips the whitespaces from both the beginning and the end of s.
102  * By default (when char_list=NULL), these characters get stripped:
103  *
104  *  - " "    (ASCII 32  (0x20))  space.
105  *  - "\t"    (ASCII 9  (0x09))  tab.
106  *  - "\n"    (ASCII 10  (0x0A))  line feed.
107  *  - "\r"    (ASCII 13  (0x0D))  carriage return.
108  *  - "\0"    (ASCII 0  (0x00))  NULL.
109  *  - "\x0B"  (ASCII 11  (0x0B))  vertical tab.
110  *
111  * @param s The string to strip.
112  * @param char_list A string which contains the characters you want to strip.
113  */
114 void xbt_str_trim(char *s, const char *char_list)
115 {
116   if (!s)
117     return;
118
119   xbt_str_rtrim(s, char_list);
120   xbt_str_ltrim(s, char_list);
121 }
122
123 /** @brief Substitutes a char for another in a string
124  *
125  * @param str the string to modify
126  * @param from char to search
127  * @param to char to put instead
128  * @param occurence number of changes to do (=0 means all)
129  */
130 void xbt_str_subst(char *str, char from, char to, int occurence)
131 {
132   char *p = str;
133   while (*p != '\0') {
134     if (*p == from) {
135       *p = to;
136       if (occurence == 1)
137         return;
138       occurence--;
139     }
140     p++;
141   }
142 }
143
144 /** @brief Replaces a set of variables by their values
145  *
146  * @param str The input of the replacement process
147  * @param patterns The changes to apply
148  * @return The string modified
149  *
150  * Both '$toto' and '${toto}' are valid (and the two writing are equivalent).
151  *
152  * If the variable name contains spaces, use the brace version (ie, ${toto tutu})
153  *
154  * You can provide a default value to use if the variable is not set in the dict by using '${var:=default}' or
155  * '${var:-default}'. These two forms are equivalent, even if they shouldn't to respect the shell standard (:= form
156  * should set the value in the dict, but does not) (BUG).
157  */
158 char *xbt_str_varsubst(const char *str, xbt_dict_t patterns)
159 {
160   xbt_strbuff_t buff = xbt_strbuff_new_from(str);
161   char *res;
162   xbt_strbuff_varsubst(buff, patterns);
163   res = buff->data;
164   xbt_strbuff_free_container(buff);
165   return res;
166 }
167
168
169 /** @brief Splits a string into a dynar of strings
170  *
171  * @param s: the string to split
172  * @param sep: a string of all chars to consider as separator.
173  *
174  * By default (with sep=NULL), these characters are used as separator:
175  *
176  *  - " "    (ASCII 32  (0x20))  space.
177  *  - "\t"    (ASCII 9  (0x09))  tab.
178  *  - "\n"    (ASCII 10  (0x0A))  line feed.
179  *  - "\r"    (ASCII 13  (0x0D))  carriage return.
180  *  - "\0"    (ASCII 0  (0x00))  NULL.
181  *  - "\x0B"  (ASCII 11  (0x0B))  vertical tab.
182  */
183 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
184 {
185   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
186   const char *p, *q;
187   int done;
188   const char *sep_dflt = " \t\n\r\x0B";
189   char is_sep[256] = { 1, 0 };
190
191   /* check what are the separators */
192   memset(is_sep, 0, sizeof(is_sep));
193   if (!sep) {
194     while (*sep_dflt)
195       is_sep[(unsigned char) *sep_dflt++] = 1;
196   } else {
197     while (*sep)
198       is_sep[(unsigned char) *sep++] = 1;
199   }
200   is_sep[0] = 1;                /* End of string is also separator */
201
202   /* Do the job */
203   p = s;
204   q = s;
205   done = 0;
206
207   if (s[0] == '\0')
208     return res;
209
210   while (!done) {
211     char *topush;
212     while (!is_sep[(unsigned char) *q]) {
213       q++;
214     }
215     if (*q == '\0')
216       done = 1;
217
218     topush = (char*) xbt_malloc(q - p + 1);
219     memcpy(topush, p, q - p);
220     topush[q - p] = '\0';
221     xbt_dynar_push(res, &topush);
222     p = ++q;
223   }
224
225   return res;
226 }
227
228 /**
229  * \brief This functions splits a string after using another string as separator
230  * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
231  * \return An array of dynars containing the string tokens
232  */
233 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
234 {
235   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
236   int done;
237   const char *p, *q;
238
239   p = s;
240   q = s;
241   done = 0;
242
243   if (s[0] == '\0')
244     return res;
245   if (sep[0] == '\0') {
246     s = xbt_strdup(s);
247     xbt_dynar_push(res, &s);
248     return res;
249   }
250
251   while (!done) {
252     char *to_push;
253     int v = 0;
254     //get the start of the first occurence of the substring
255     q = strstr(p, sep);
256     //if substring was not found add the entire string
257     if (NULL == q) {
258       v = strlen(p);
259       to_push = (char*) xbt_malloc(v + 1);
260       memcpy(to_push, p, v);
261       to_push[v] = '\0';
262       xbt_dynar_push(res, &to_push);
263       done = 1;
264     } else {
265       //get the appearance
266       to_push = (char*) xbt_malloc(q - p + 1);
267       memcpy(to_push, p, q - p);
268       //add string terminator
269       to_push[q - p] = '\0';
270       xbt_dynar_push(res, &to_push);
271       p = q + strlen(sep);
272     }
273   }
274   return res;
275 }
276
277 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
278  *
279  * The string passed as argument must be writable (not const)
280  * The elements of the dynar are just parts of the string passed as argument.
281  * So if you don't store that argument elsewhere, you should free it in addition to freeing the dynar. This can be done
282  * by simply freeing the first argument of the dynar:
283  *  free(xbt_dynar_get_ptr(dynar,0));
284  *
285  * Actually this function puts a bunch of \0 in the memory area you passed as argument to separate the elements, and
286  * pushes the address of each chunk in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
287  */
288 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
289   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), NULL);
290   char *beg, *end;              /* pointers around the parsed chunk */
291   int in_simple_quote = 0, in_double_quote = 0;
292   int done = 0;
293   int ctn = 0;                  /* Got something in this block */
294
295   if (s[0] == '\0')
296     return res;
297
298   beg = s;
299
300   /* do not trim leading spaces: caller responsibility to clean his cruft */
301   end = beg;
302
303   while (!done) {
304     switch (*end) {
305     case '\\':
306       ctn = 1;
307       /* Protected char; move it closer */
308       memmove(end, end + 1, strlen(end));
309       if (*end == '\0')
310         THROWF(arg_error, 0, "String ends with \\");
311       end++;                    /* Pass the protected char */
312       break;
313     case '\'':
314       ctn = 1;
315       if (!in_double_quote) {
316         in_simple_quote = !in_simple_quote;
317         memmove(end, end + 1, strlen(end));
318       } else {
319         /* simple quote protected by double ones */
320         end++;
321       }
322       break;
323     case '"':
324       ctn = 1;
325       if (!in_simple_quote) {
326         in_double_quote = !in_double_quote;
327         memmove(end, end + 1, strlen(end));
328       } else {
329         /* double quote protected by simple ones */
330         end++;
331       }
332       break;
333     case ' ':
334     case '\t':
335     case '\n':
336     case '\0':
337       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
338         THROWF(arg_error, 0, "End of string found while searching for %c in %s", (in_simple_quote ? '\'' : '"'), s);
339       }
340       if (in_simple_quote || in_double_quote) {
341         end++;
342       } else {
343         if (*end == '\0')
344           done = 1;
345
346         *end = '\0';
347         if (ctn) {
348           /* Found a separator. Push the string if contains something */
349           xbt_dynar_push(res, &beg);
350         }
351         ctn = 0;
352
353         if (done)
354           break;
355
356         beg = ++end;
357         /* trim within the string, manually to speed things up */
358         while (*beg == ' ')
359           beg++;
360         end = beg;
361       }
362       break;
363     default:
364       ctn = 1;
365       end++;
366     }
367   }
368   return res;
369 }
370
371 /** @brief Splits a string into a dynar of strings, taking quotes into account
372  *
373  * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
374  * are never split within a quote group.
375  * Several subsequent spaces are ignored (unless within quotes, of course).
376  * You may want to trim the input string, if you want to avoid empty entries
377  */
378 xbt_dynar_t xbt_str_split_quoted(const char *s)
379 {
380   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
381   xbt_dynar_t parsed;
382   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
383   unsigned int cursor;
384   char *p;
385
386   if (s[0] == '\0')
387     return res;
388   str_to_free = xbt_strdup(s);
389
390   parsed = xbt_str_split_quoted_in_place(str_to_free);
391   xbt_dynar_foreach(parsed,cursor,p) {
392     char *q=xbt_strdup(p);
393     xbt_dynar_push(res,&q);
394   }
395   free(str_to_free);
396   xbt_dynar_shrink(res, 0);
397   xbt_dynar_free(&parsed);
398   return res;
399 }
400
401 /** @brief Join a set of strings as a single string */
402 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
403 {
404   int len = 1, dyn_len = xbt_dynar_length(dyn);
405   unsigned int cpt;
406   char *cursor;
407   char *res, *p;
408
409   if (!dyn_len)
410     return xbt_strdup("");
411
412   /* compute the length */
413   xbt_dynar_foreach(dyn, cpt, cursor) {
414     len += strlen(cursor);
415   }
416   len += strlen(sep) * dyn_len;
417   /* Do the job */
418   res = (char*) xbt_malloc(len);
419   p = res;
420   xbt_dynar_foreach(dyn, cpt, cursor) {
421     if ((int) cpt < dyn_len - 1)
422       p += snprintf(p,len, "%s%s", cursor, sep);
423     else
424       p += snprintf(p,len, "%s", cursor);
425   }
426   return res;
427 }
428
429 /** @brief Join a set of strings as a single string
430  *
431  * The parameter must be a NULL-terminated array of chars,
432  * just like xbt_dynar_to_array() produces
433  */
434 char *xbt_str_join_array(const char *const *strs, const char *sep)
435 {
436   char *res,*q;
437   int amount_strings=0;
438   int len=0;
439   int i;
440
441   if ((!strs) || (!strs[0]))
442     return xbt_strdup("");
443
444   /* compute the length before malloc */
445   for (i=0;strs[i];i++) {
446     len += strlen(strs[i]);
447     amount_strings++;
448   }
449   len += strlen(sep) * amount_strings;
450
451   /* Do the job */
452   res = (char*) xbt_malloc(len);
453   q = res;
454   for (i=0;strs[i];i++) {
455     if (i!=0) { // not first loop
456       q += snprintf(q,len, "%s%s", sep, strs[i]);
457     } else {
458       q += snprintf(q,len, "%s",strs[i]);
459     }
460   }
461   return res;
462 }
463
464 /** @brief creates a new string containing what can be read on a fd */
465 char *xbt_str_from_file(FILE * file)
466 {
467   xbt_strbuff_t buff = xbt_strbuff_new();
468   char *res;
469   char bread[1024];
470   memset(bread, 0, 1024);
471
472   while (!feof(file)) {
473     int got = fread(bread, 1, 1023, file);
474     bread[got] = '\0';
475     xbt_strbuff_append(buff, bread);
476   }
477
478   res = buff->data;
479   xbt_strbuff_free_container(buff);
480   return res;
481 }
482
483 /** @brief Parse an integer out of a string, or raise an error
484  *
485  * The @a str is passed as argument to your @a error_msg, as follows:
486  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
487  */
488 long int xbt_str_parse_int(const char* str, const char* error_msg)
489 {
490   char *endptr;
491   if (str == NULL || str[0] == '\0')
492     THROWF(arg_error, 0, error_msg, str);
493
494   long int res = strtol(str, &endptr, 10);
495   if (endptr[0] != '\0')
496     THROWF(arg_error, 0, error_msg, str);
497
498   return res;
499 }
500
501 /** @brief Parse a double out of a string, or raise an error
502  *
503  * The @a str is passed as argument to your @a error_msg, as follows:
504  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
505  */
506 double xbt_str_parse_double(const char* str, const char* error_msg)
507 {
508   char *endptr;
509   if (str == NULL || str[0] == '\0')
510     THROWF(arg_error, 0, error_msg, str);
511
512   double res = strtod(str, &endptr);
513   if (endptr[0] != '\0')
514     THROWF(arg_error, 0, error_msg, str);
515
516   return res;
517 }
518
519 #ifdef SIMGRID_TEST
520 #include <xbt/ex.hpp>
521 #include "xbt/str.h"
522
523 XBT_TEST_SUITE("xbt_str", "String Handling");
524
525 #define mytest(name, input, expected) \
526   xbt_test_add(name); \
527   d=xbt_str_split_quoted(input); \
528   s=xbt_str_join(d,"XXX"); \
529   xbt_test_assert(!strcmp(s,expected),\
530                    "Input (%s) leads to (%s) instead of (%s)", \
531                    input,s,expected);\
532                    free(s); \
533                    xbt_dynar_free(&d);
534 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
535 {
536   xbt_dynar_t d;
537   char *s;
538
539   mytest("Empty", "", "");
540   mytest("Basic test", "toto tutu", "totoXXXtutu");
541   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
542   mytest("Protected space", "toto\\ tutu", "toto tutu");
543   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
544   mytest("LTriming", "  toto tatu", "totoXXXtatu");
545   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
546   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
547   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
548   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
549   mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
550   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
551 }
552
553 #define mytest_str(name, input, separator, expected) \
554   xbt_test_add(name); \
555   d=xbt_str_split_str(input, separator); \
556   s=xbt_str_join(d,"XXX"); \
557   xbt_test_assert(!strcmp(s,expected),\
558                    "Input (%s) leads to (%s) instead of (%s)", \
559                    input,s,expected);\
560                    free(s); \
561                    xbt_dynar_free(&d);
562
563 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
564 {
565   xbt_dynar_t d;
566   char *s;
567
568   mytest_str("Empty string and separator", "", "", "");
569   mytest_str("Empty string", "", "##", "");
570   mytest_str("Empty separator", "toto", "", "toto");
571   mytest_str("String with no separator in it", "toto", "##", "toto");
572   mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
573 }
574
575 #define test_parse_error(function, name, variable, str)                 \
576   do {                                                                  \
577     xbt_test_add(name);                                                 \
578     try {                                                               \
579       variable = function(str, "Parse error");                          \
580       xbt_test_fail("The test '%s' did not detect the problem",name );  \
581     } catch(xbt_ex& e) {                                                \
582       if (e.category != arg_error) {                                    \
583         xbt_test_exception(e);                                          \
584       }                                                                 \
585     }                                                                   \
586   } while (0)
587 #define test_parse_ok(function, name, variable, str, value)             \
588   do {                                                                  \
589     xbt_test_add(name);                                                 \
590     try {                                                               \
591       variable = function(str, "Parse error");                          \
592     } catch(xbt_ex& e) {                                                \
593       xbt_test_exception(e);                                            \
594     }                                                                   \
595     xbt_test_assert(variable == value, "Fail to parse '%s'", str);      \
596   } while (0)
597
598 XBT_TEST_UNIT("xbt_str_parse", test_parse, "Test the parsing functions")
599 {
600   int rint = -9999;
601   test_parse_ok(xbt_str_parse_int, "Parse int", rint, "42", 42);
602   test_parse_ok(xbt_str_parse_int, "Parse 0 as an int", rint, "0", 0);
603   test_parse_ok(xbt_str_parse_int, "Parse -1 as an int", rint, "-1", -1);
604
605   test_parse_error(xbt_str_parse_int, "Parse int + noise", rint, "342 cruft");
606   test_parse_error(xbt_str_parse_int, "Parse NULL as an int", rint, NULL);
607   test_parse_error(xbt_str_parse_int, "Parse '' as an int", rint, "");
608   test_parse_error(xbt_str_parse_int, "Parse cruft as an int", rint, "cruft");
609
610   double rdouble = -9999;
611   test_parse_ok(xbt_str_parse_double, "Parse 42 as a double", rdouble, "42", 42);
612   test_parse_ok(xbt_str_parse_double, "Parse 42.5 as a double", rdouble, "42.5", 42.5);
613   test_parse_ok(xbt_str_parse_double, "Parse 0 as a double", rdouble, "0", 0);
614   test_parse_ok(xbt_str_parse_double, "Parse -1 as a double", rdouble, "-1", -1);
615
616   test_parse_error(xbt_str_parse_double, "Parse double + noise", rdouble, "342 cruft");
617   test_parse_error(xbt_str_parse_double, "Parse NULL as a double", rdouble, NULL);
618   test_parse_error(xbt_str_parse_double, "Parse '' as a double", rdouble, "");
619   test_parse_error(xbt_str_parse_double, "Parse cruft as a double", rdouble, "cruft");
620 }
621 #endif                          /* SIMGRID_TEST */