Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Drop unused functions: xbt_str_varsubst(), xbt_strbuff_varsubst()
[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=nullptr), 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))  nullptr.
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=nullptr), 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))  nullptr.
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=nullptr), 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))  nullptr.
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 Splits a string into a dynar of strings
145  *
146  * @param s: the string to split
147  * @param sep: a string of all chars to consider as separator.
148  *
149  * By default (with sep=nullptr), these characters are used as separator:
150  *
151  *  - " "    (ASCII 32  (0x20))  space.
152  *  - "\t"    (ASCII 9  (0x09))  tab.
153  *  - "\n"    (ASCII 10  (0x0A))  line feed.
154  *  - "\r"    (ASCII 13  (0x0D))  carriage return.
155  *  - "\0"    (ASCII 0  (0x00))  nullptr.
156  *  - "\x0B"  (ASCII 11  (0x0B))  vertical tab.
157  */
158 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
159 {
160   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
161   const char *sep_dflt = " \t\n\r\x0B";
162   char is_sep[256] = { 1, 0 };
163
164   /* check what are the separators */
165   memset(is_sep, 0, sizeof(is_sep));
166   if (!sep) {
167     while (*sep_dflt)
168       is_sep[(unsigned char) *sep_dflt++] = 1;
169   } else {
170     while (*sep)
171       is_sep[(unsigned char) *sep++] = 1;
172   }
173   is_sep[0] = 1; /* End of string is also separator */
174
175   /* Do the job */
176   const char* p = s;
177   const char* q = s;
178   int done      = 0;
179
180   if (s[0] == '\0')
181     return res;
182
183   while (!done) {
184     char *topush;
185     while (!is_sep[(unsigned char) *q]) {
186       q++;
187     }
188     if (*q == '\0')
189       done = 1;
190
191     topush = (char*) xbt_malloc(q - p + 1);
192     memcpy(topush, p, q - p);
193     topush[q - p] = '\0';
194     xbt_dynar_push(res, &topush);
195     p = ++q;
196   }
197
198   return res;
199 }
200
201 /**
202  * \brief This functions splits a string after using another string as separator
203  * For example A!!B!!C split after !! will return the dynar {A,B,C}
204  * \return An array of dynars containing the string tokens
205  */
206 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
207 {
208   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
209
210   const char* p = s;
211   const char* q = s;
212   int done      = 0;
213
214   if (s[0] == '\0')
215     return res;
216   if (sep[0] == '\0') {
217     s = xbt_strdup(s);
218     xbt_dynar_push(res, &s);
219     return res;
220   }
221
222   while (!done) {
223     char *to_push;
224     int v = 0;
225     // get the start of the first occurrence of the substring
226     q = strstr(p, sep);
227     //if substring was not found add the entire string
228     if (nullptr == q) {
229       v = strlen(p);
230       to_push = (char*) xbt_malloc(v + 1);
231       memcpy(to_push, p, v);
232       to_push[v] = '\0';
233       xbt_dynar_push(res, &to_push);
234       done = 1;
235     } else {
236       //get the appearance
237       to_push = (char*) xbt_malloc(q - p + 1);
238       memcpy(to_push, p, q - p);
239       //add string terminator
240       to_push[q - p] = '\0';
241       xbt_dynar_push(res, &to_push);
242       p = q + strlen(sep);
243     }
244   }
245   return res;
246 }
247
248 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
249  *
250  * The string passed as argument must be writable (not const)
251  * The elements of the dynar are just parts of the string passed as argument.
252  * So if you don't store that argument elsewhere, you should free it in addition to freeing the dynar. This can be done
253  * by simply freeing the first argument of the dynar:
254  *  free(xbt_dynar_get_ptr(dynar,0));
255  *
256  * Actually this function puts a bunch of \0 in the memory area you passed as argument to separate the elements, and
257  * pushes the address of each chunk in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
258  */
259 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
260   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), nullptr);
261   char* beg;
262   char* end; /* pointers around the parsed chunk */
263   int in_simple_quote = 0;
264   int in_double_quote = 0;
265   int done            = 0;
266   int ctn             = 0; /* Got something in this block */
267
268   if (s[0] == '\0')
269     return res;
270
271   beg = s;
272
273   /* do not trim leading spaces: caller responsibility to clean his cruft */
274   end = beg;
275
276   while (!done) {
277     switch (*end) {
278     case '\\':
279       ctn = 1;
280       /* Protected char; move it closer */
281       memmove(end, end + 1, strlen(end));
282       if (*end == '\0')
283         THROWF(arg_error, 0, "String ends with \\");
284       end++;                    /* Pass the protected char */
285       break;
286     case '\'':
287       ctn = 1;
288       if (!in_double_quote) {
289         in_simple_quote = !in_simple_quote;
290         memmove(end, end + 1, strlen(end));
291       } else {
292         /* simple quote protected by double ones */
293         end++;
294       }
295       break;
296     case '"':
297       ctn = 1;
298       if (!in_simple_quote) {
299         in_double_quote = !in_double_quote;
300         memmove(end, end + 1, strlen(end));
301       } else {
302         /* double quote protected by simple ones */
303         end++;
304       }
305       break;
306     case ' ':
307     case '\t':
308     case '\n':
309     case '\0':
310       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
311         THROWF(arg_error, 0, "End of string found while searching for %c in %s", (in_simple_quote ? '\'' : '"'), s);
312       }
313       if (in_simple_quote || in_double_quote) {
314         end++;
315       } else {
316         if (*end == '\0')
317           done = 1;
318
319         *end = '\0';
320         if (ctn) {
321           /* Found a separator. Push the string if contains something */
322           xbt_dynar_push(res, &beg);
323         }
324         ctn = 0;
325
326         if (done)
327           break;
328
329         beg = ++end;
330         /* trim within the string, manually to speed things up */
331         while (*beg == ' ')
332           beg++;
333         end = beg;
334       }
335       break;
336     default:
337       ctn = 1;
338       end++;
339     }
340   }
341   return res;
342 }
343
344 /** @brief Splits a string into a dynar of strings, taking quotes into account
345  *
346  * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
347  * are never split within a quote group.
348  * Several subsequent spaces are ignored (unless within quotes, of course).
349  * You may want to trim the input string, if you want to avoid empty entries
350  */
351 xbt_dynar_t xbt_str_split_quoted(const char *s)
352 {
353   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
354   xbt_dynar_t parsed;
355   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
356   unsigned int cursor;
357   char *p;
358
359   if (s[0] == '\0')
360     return res;
361   str_to_free = xbt_strdup(s);
362
363   parsed = xbt_str_split_quoted_in_place(str_to_free);
364   xbt_dynar_foreach(parsed,cursor,p) {
365     char *q=xbt_strdup(p);
366     xbt_dynar_push(res,&q);
367   }
368   free(str_to_free);
369   xbt_dynar_shrink(res, 0);
370   xbt_dynar_free(&parsed);
371   return res;
372 }
373
374 /** @brief Join a set of strings as a single string */
375 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
376 {
377   int len = 1, dyn_len = xbt_dynar_length(dyn);
378   unsigned int cpt;
379   char* cursor;
380
381   if (!dyn_len)
382     return xbt_strdup("");
383
384   /* compute the length */
385   xbt_dynar_foreach(dyn, cpt, cursor) {
386     len += strlen(cursor);
387   }
388   len += strlen(sep) * dyn_len;
389   /* Do the job */
390   char* res = (char*)xbt_malloc(len);
391   char* p   = res;
392   xbt_dynar_foreach(dyn, cpt, cursor) {
393     if ((int) cpt < dyn_len - 1)
394       p += snprintf(p,len, "%s%s", cursor, sep);
395     else
396       p += snprintf(p,len, "%s", cursor);
397   }
398   return res;
399 }
400
401 /** @brief Join a set of strings as a single string
402  *
403  * The parameter must be a nullptr-terminated array of chars,
404  * just like xbt_dynar_to_array() produces
405  */
406 char *xbt_str_join_array(const char *const *strs, const char *sep)
407 {
408   int amount_strings=0;
409   int len=0;
410
411   if ((!strs) || (!strs[0]))
412     return xbt_strdup("");
413
414   /* compute the length before malloc */
415   for (int i = 0; strs[i]; i++) {
416     len += strlen(strs[i]);
417     amount_strings++;
418   }
419   len += strlen(sep) * amount_strings;
420
421   /* Do the job */
422   char* res = (char*)xbt_malloc(len);
423   char* q   = res;
424   for (int i = 0; strs[i]; i++) {
425     if (i != 0) { // not first loop
426       q += snprintf(q,len, "%s%s", sep, strs[i]);
427     } else {
428       q += snprintf(q,len, "%s",strs[i]);
429     }
430   }
431   return res;
432 }
433
434 /** @brief Parse an integer out of a string, or raise an error
435  *
436  * The @a str is passed as argument to your @a error_msg, as follows:
437  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
438  */
439 long int xbt_str_parse_int(const char* str, const char* error_msg)
440 {
441   char* endptr;
442   if (str == nullptr || str[0] == '\0')
443     THROWF(arg_error, 0, error_msg, str);
444
445   long int res = strtol(str, &endptr, 10);
446   if (endptr[0] != '\0')
447     THROWF(arg_error, 0, error_msg, str);
448
449   return res;
450 }
451
452 /** @brief Parse a double out of a string, or raise an error
453  *
454  * The @a str is passed as argument to your @a error_msg, as follows:
455  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
456  */
457 double xbt_str_parse_double(const char* str, const char* error_msg)
458 {
459   char *endptr;
460   if (str == nullptr || str[0] == '\0')
461     THROWF(arg_error, 0, error_msg, str);
462
463   double res = strtod(str, &endptr);
464   if (endptr[0] != '\0')
465     THROWF(arg_error, 0, error_msg, str);
466
467   return res;
468 }
469
470 #ifdef SIMGRID_TEST
471 #include <xbt/ex.hpp>
472 #include "xbt/str.h"
473
474 XBT_TEST_SUITE("xbt_str", "String Handling");
475
476 #define mytest(name, input, expected) \
477   xbt_test_add(name); \
478   d=xbt_str_split_quoted(input); \
479   s=xbt_str_join(d,"XXX"); \
480   xbt_test_assert(!strcmp(s,expected),\
481                    "Input (%s) leads to (%s) instead of (%s)", \
482                    input,s,expected);\
483                    free(s); \
484                    xbt_dynar_free(&d);
485 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
486 {
487   xbt_dynar_t d;
488   char *s;
489
490   mytest("Empty", "", "");
491   mytest("Basic test", "toto tutu", "totoXXXtutu");
492   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
493   mytest("Protected space", "toto\\ tutu", "toto tutu");
494   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
495   mytest("LTriming", "  toto tatu", "totoXXXtatu");
496   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
497   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
498   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
499   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
500   mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
501   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
502 }
503
504 #define mytest_str(name, input, separator, expected) \
505   xbt_test_add(name); \
506   d=xbt_str_split_str(input, separator); \
507   s=xbt_str_join(d,"XXX"); \
508   xbt_test_assert(!strcmp(s,expected),\
509                    "Input (%s) leads to (%s) instead of (%s)", \
510                    input,s,expected);\
511                    free(s); \
512                    xbt_dynar_free(&d);
513
514 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
515 {
516   xbt_dynar_t d;
517   char *s;
518
519   mytest_str("Empty string and separator", "", "", "");
520   mytest_str("Empty string", "", "##", "");
521   mytest_str("Empty separator", "toto", "", "toto");
522   mytest_str("String with no separator in it", "toto", "##", "toto");
523   mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
524 }
525
526 #define test_parse_error(function, name, variable, str)                 \
527   do {                                                                  \
528     xbt_test_add(name);                                                 \
529     try {                                                               \
530       variable = function(str, "Parse error");                          \
531       xbt_test_fail("The test '%s' did not detect the problem",name );  \
532     } catch(xbt_ex& e) {                                                \
533       if (e.category != arg_error) {                                    \
534         xbt_test_exception(e);                                          \
535       }                                                                 \
536     }                                                                   \
537   } while (0)
538 #define test_parse_ok(function, name, variable, str, value)             \
539   do {                                                                  \
540     xbt_test_add(name);                                                 \
541     try {                                                               \
542       variable = function(str, "Parse error");                          \
543     } catch(xbt_ex& e) {                                                \
544       xbt_test_exception(e);                                            \
545     }                                                                   \
546     xbt_test_assert(variable == value, "Fail to parse '%s'", str);      \
547   } while (0)
548
549 XBT_TEST_UNIT("xbt_str_parse", test_parse, "Test the parsing functions")
550 {
551   int rint = -9999;
552   test_parse_ok(xbt_str_parse_int, "Parse int", rint, "42", 42);
553   test_parse_ok(xbt_str_parse_int, "Parse 0 as an int", rint, "0", 0);
554   test_parse_ok(xbt_str_parse_int, "Parse -1 as an int", rint, "-1", -1);
555
556   test_parse_error(xbt_str_parse_int, "Parse int + noise", rint, "342 cruft");
557   test_parse_error(xbt_str_parse_int, "Parse nullptr as an int", rint, nullptr);
558   test_parse_error(xbt_str_parse_int, "Parse '' as an int", rint, "");
559   test_parse_error(xbt_str_parse_int, "Parse cruft as an int", rint, "cruft");
560
561   double rdouble = -9999;
562   test_parse_ok(xbt_str_parse_double, "Parse 42 as a double", rdouble, "42", 42);
563   test_parse_ok(xbt_str_parse_double, "Parse 42.5 as a double", rdouble, "42.5", 42.5);
564   test_parse_ok(xbt_str_parse_double, "Parse 0 as a double", rdouble, "0", 0);
565   test_parse_ok(xbt_str_parse_double, "Parse -1 as a double", rdouble, "-1", -1);
566
567   test_parse_error(xbt_str_parse_double, "Parse double + noise", rdouble, "342 cruft");
568   test_parse_error(xbt_str_parse_double, "Parse nullptr as a double", rdouble, nullptr);
569   test_parse_error(xbt_str_parse_double, "Parse '' as a double", rdouble, "");
570   test_parse_error(xbt_str_parse_double, "Parse cruft as a double", rdouble, "cruft");
571 }
572 #endif                          /* SIMGRID_TEST */