Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Move the stack as field of SafetyChecker and CommDetChecker
[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 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 = 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 = 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 = q = s;
239   done = 0;
240
241   if (s[0] == '\0')
242     return res;
243   if (sep[0] == '\0') {
244     s = xbt_strdup(s);
245     xbt_dynar_push(res, &s);
246     return res;
247   }
248
249   while (!done) {
250     char *to_push;
251     int v = 0;
252     //get the start of the first occurence of the substring
253     q = strstr(p, sep);
254     //if substring was not found add the entire string
255     if (NULL == q) {
256       v = strlen(p);
257       to_push = xbt_malloc(v + 1);
258       memcpy(to_push, p, v);
259       to_push[v] = '\0';
260       xbt_dynar_push(res, &to_push);
261       done = 1;
262     } else {
263       //get the appearance
264       to_push = xbt_malloc(q - p + 1);
265       memcpy(to_push, p, q - p);
266       //add string terminator
267       to_push[q - p] = '\0';
268       xbt_dynar_push(res, &to_push);
269       p = q + strlen(sep);
270     }
271   }
272   return res;
273 }
274
275 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
276  *
277  * The string passed as argument must be writable (not const)
278  * The elements of the dynar are just parts of the string passed as argument.
279  * So if you don't store that argument elsewhere, you should free it in addition to freeing the dynar. This can be done
280  * by simply freeing the first argument of the dynar:
281  *  free(xbt_dynar_get_ptr(dynar,0));
282  *
283  * Actually this function puts a bunch of \0 in the memory area you passed as argument to separate the elements, and
284  * pushes the address of each chunk in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
285  */
286 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
287   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), NULL);
288   char *beg, *end;              /* pointers around the parsed chunk */
289   int in_simple_quote = 0, in_double_quote = 0;
290   int done = 0;
291   int ctn = 0;                  /* Got something in this block */
292
293   if (s[0] == '\0')
294     return res;
295
296   beg = s;
297
298   /* do not trim leading spaces: caller responsibility to clean his cruft */
299   end = beg;
300
301   while (!done) {
302     switch (*end) {
303     case '\\':
304       ctn = 1;
305       /* Protected char; move it closer */
306       memmove(end, end + 1, strlen(end));
307       if (*end == '\0')
308         THROWF(arg_error, 0, "String ends with \\");
309       end++;                    /* Pass the protected char */
310       break;
311     case '\'':
312       ctn = 1;
313       if (!in_double_quote) {
314         in_simple_quote = !in_simple_quote;
315         memmove(end, end + 1, strlen(end));
316       } else {
317         /* simple quote protected by double ones */
318         end++;
319       }
320       break;
321     case '"':
322       ctn = 1;
323       if (!in_simple_quote) {
324         in_double_quote = !in_double_quote;
325         memmove(end, end + 1, strlen(end));
326       } else {
327         /* double quote protected by simple ones */
328         end++;
329       }
330       break;
331     case ' ':
332     case '\t':
333     case '\n':
334     case '\0':
335       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
336         THROWF(arg_error, 0, "End of string found while searching for %c in %s", (in_simple_quote ? '\'' : '"'), s);
337       }
338       if (in_simple_quote || in_double_quote) {
339         end++;
340       } else {
341         if (*end == '\0')
342           done = 1;
343
344         *end = '\0';
345         if (ctn) {
346           /* Found a separator. Push the string if contains something */
347           xbt_dynar_push(res, &beg);
348         }
349         ctn = 0;
350
351         if (done)
352           break;
353
354         beg = ++end;
355         /* trim within the string, manually to speed things up */
356         while (*beg == ' ')
357           beg++;
358         end = beg;
359       }
360       break;
361     default:
362       ctn = 1;
363       end++;
364     }
365   }
366   return res;
367 }
368
369 /** @brief Splits a string into a dynar of strings, taking quotes into account
370  *
371  * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
372  * are never split within a quote group.
373  * Several subsequent spaces are ignored (unless within quotes, of course).
374  * You may want to trim the input string, if you want to avoid empty entries
375  */
376 xbt_dynar_t xbt_str_split_quoted(const char *s)
377 {
378   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
379   xbt_dynar_t parsed;
380   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
381   unsigned int cursor;
382   char *p;
383
384   if (s[0] == '\0')
385     return res;
386   str_to_free = xbt_strdup(s);
387
388   parsed = xbt_str_split_quoted_in_place(str_to_free);
389   xbt_dynar_foreach(parsed,cursor,p) {
390     char *q=xbt_strdup(p);
391     xbt_dynar_push(res,&q);
392   }
393   free(str_to_free);
394   xbt_dynar_shrink(res, 0);
395   xbt_dynar_free(&parsed);
396   return res;
397 }
398
399 /** @brief Join a set of strings as a single string */
400 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
401 {
402   int len = 1, dyn_len = xbt_dynar_length(dyn);
403   unsigned int cpt;
404   char *cursor;
405   char *res, *p;
406
407   if (!dyn_len)
408     return xbt_strdup("");
409
410   /* compute the length */
411   xbt_dynar_foreach(dyn, cpt, cursor) {
412     len += strlen(cursor);
413   }
414   len += strlen(sep) * dyn_len;
415   /* Do the job */
416   res = xbt_malloc(len);
417   p = res;
418   xbt_dynar_foreach(dyn, cpt, cursor) {
419     if ((int) cpt < dyn_len - 1)
420       p += sprintf(p, "%s%s", cursor, sep);
421     else
422       p += sprintf(p, "%s", cursor);
423   }
424   return res;
425 }
426
427 /** @brief Join a set of strings as a single string
428  *
429  * The parameter must be a NULL-terminated array of chars,
430  * just like xbt_dynar_to_array() produces
431  */
432 char *xbt_str_join_array(const char *const *strs, const char *sep)
433 {
434   char *res,*q;
435   int amount_strings=0;
436   int len=0;
437   int i;
438
439   if ((!strs) || (!strs[0]))
440     return xbt_strdup("");
441
442   /* compute the length before malloc */
443   for (i=0;strs[i];i++) {
444     len += strlen(strs[i]);
445     amount_strings++;
446   }
447   len += strlen(sep) * amount_strings;
448
449   /* Do the job */
450   q = res = xbt_malloc(len);
451   for (i=0;strs[i];i++) {
452     if (i!=0) { // not first loop
453       q += sprintf(q, "%s%s", sep, strs[i]);
454     } else {
455       q += sprintf(q,"%s",strs[i]);
456     }
457   }
458   return res;
459 }
460
461 /** @brief creates a new string containing what can be read on a fd */
462 char *xbt_str_from_file(FILE * file)
463 {
464   xbt_strbuff_t buff = xbt_strbuff_new();
465   char *res;
466   char bread[1024];
467   memset(bread, 0, 1024);
468
469   while (!feof(file)) {
470     int got = fread(bread, 1, 1023, file);
471     bread[got] = '\0';
472     xbt_strbuff_append(buff, bread);
473   }
474
475   res = buff->data;
476   xbt_strbuff_free_container(buff);
477   return res;
478 }
479
480 /** @brief Parse an integer out of a string, or raise an error
481  *
482  * The #str is passed as argument to your #error_msg, as follows:
483  *       THROWF(arg_error, 0, error_msg, str);
484  */
485 long int xbt_str_parse_int(const char* str, const char* error_msg)
486 {
487   char *endptr;
488   if (str == NULL || str[0] == '\0')
489     THROWF(arg_error, 0, error_msg, str);
490
491   long int res = strtol(str, &endptr, 10);
492   if (endptr[0] != '\0')
493     THROWF(arg_error, 0, error_msg, str);
494
495   return res;
496 }
497
498 /** @brief Parse a double out of a string, or raise an error
499  *
500  * The #str is passed as argument to your #error_msg, as follows:
501  *       THROWF(arg_error, 0, error_msg, str);
502  */
503 double xbt_str_parse_double(const char* str, const char* error_msg)
504 {
505   char *endptr;
506   if (str == NULL || str[0] == '\0')
507     THROWF(arg_error, 0, error_msg, str);
508
509   double res = strtod(str, &endptr);
510   if (endptr[0] != '\0')
511     THROWF(arg_error, 0, error_msg, str);
512
513   return res;
514 }
515
516 #ifdef SIMGRID_TEST
517 #include "xbt/str.h"
518
519 XBT_TEST_SUITE("xbt_str", "String Handling");
520
521 #define mytest(name, input, expected) \
522   xbt_test_add(name); \
523   d=xbt_str_split_quoted(input); \
524   s=xbt_str_join(d,"XXX"); \
525   xbt_test_assert(!strcmp(s,expected),\
526                    "Input (%s) leads to (%s) instead of (%s)", \
527                    input,s,expected);\
528                    free(s); \
529                    xbt_dynar_free(&d);
530 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
531 {
532   xbt_dynar_t d;
533   char *s;
534
535   mytest("Empty", "", "");
536   mytest("Basic test", "toto tutu", "totoXXXtutu");
537   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
538   mytest("Protected space", "toto\\ tutu", "toto tutu");
539   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
540   mytest("LTriming", "  toto tatu", "totoXXXtatu");
541   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
542   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
543   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
544   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
545   mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
546   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
547 }
548
549 #define mytest_str(name, input, separator, expected) \
550   xbt_test_add(name); \
551   d=xbt_str_split_str(input, separator); \
552   s=xbt_str_join(d,"XXX"); \
553   xbt_test_assert(!strcmp(s,expected),\
554                    "Input (%s) leads to (%s) instead of (%s)", \
555                    input,s,expected);\
556                    free(s); \
557                    xbt_dynar_free(&d);
558
559 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
560 {
561   xbt_dynar_t d;
562   char *s;
563
564   mytest_str("Empty string and separator", "", "", "");
565   mytest_str("Empty string", "", "##", "");
566   mytest_str("Empty separator", "toto", "", "toto");
567   mytest_str("String with no separator in it", "toto", "##", "toto");
568   mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
569 }
570
571 #define test_parse_error(function, name, variable, str)                 \
572   do {                                                                  \
573     xbt_test_add(name);                                                 \
574     TRY {                                                               \
575       variable = function(str, "Parse error");                          \
576       xbt_test_fail("The test '%s' did not detect the problem",name );  \
577     } CATCH(e) {                                                        \
578       if (e.category != arg_error) {                                    \
579         xbt_test_exception(e);                                          \
580       } else {                                                          \
581         xbt_ex_free(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(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   xbt_ex_t e;
599   int rint = -9999;
600   test_parse_ok(xbt_str_parse_int, "Parse int", rint, "42", 42);
601   test_parse_ok(xbt_str_parse_int, "Parse 0 as an int", rint, "0", 0);
602   test_parse_ok(xbt_str_parse_int, "Parse -1 as an int", rint, "-1", -1);
603
604   test_parse_error(xbt_str_parse_int, "Parse int + noise", rint, "342 cruft");
605   test_parse_error(xbt_str_parse_int, "Parse NULL as an int", rint, NULL);
606   test_parse_error(xbt_str_parse_int, "Parse '' as an int", rint, "");
607   test_parse_error(xbt_str_parse_int, "Parse cruft as an int", rint, "cruft");
608
609   double rdouble = -9999;
610   test_parse_ok(xbt_str_parse_double, "Parse 42 as a double", rdouble, "42", 42);
611   test_parse_ok(xbt_str_parse_double, "Parse 42.5 as a double", rdouble, "42.5", 42.5);
612   test_parse_ok(xbt_str_parse_double, "Parse 0 as a double", rdouble, "0", 0);
613   test_parse_ok(xbt_str_parse_double, "Parse -1 as a double", rdouble, "-1", -1);
614
615   test_parse_error(xbt_str_parse_double, "Parse double + noise", rdouble, "342 cruft");
616   test_parse_error(xbt_str_parse_double, "Parse NULL as a double", rdouble, NULL);
617   test_parse_error(xbt_str_parse_double, "Parse '' as a double", rdouble, "");
618   test_parse_error(xbt_str_parse_double, "Parse cruft as a double", rdouble, "cruft");
619 }
620 #endif                          /* SIMGRID_TEST */