Logo AND Algorithmique Numérique Distribuée

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