Logo AND Algorithmique Numérique Distribuée

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