Logo AND Algorithmique Numérique Distribuée

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