Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use C++11 <random> instead of rand().
[simgrid.git] / src / xbt / xbt_str.cpp
1 /* xbt_str.cpp - various helping functions to deal with strings             */
2
3 /* Copyright (c) 2007-2019. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include "simgrid/Exception.hpp"
9 #include "xbt/misc.h"
10 #include "xbt/str.h" /* headers of these functions */
11
12 /** @brief Splits a string into a dynar of strings
13  *
14  * @param s: the string to split
15  * @param sep: a string of all chars to consider as separator.
16  *
17  * By default (with sep=nullptr), these characters are used as separator:
18  *
19  *  - " "    (ASCII 32  (0x20))  space.
20  *  - "\t"    (ASCII 9  (0x09))  tab.
21  *  - "\n"    (ASCII 10  (0x0A))  line feed.
22  *  - "\r"    (ASCII 13  (0x0D))  carriage return.
23  *  - "\0"    (ASCII 0  (0x00))  nullptr.
24  *  - "\x0B"  (ASCII 11  (0x0B))  vertical tab.
25  */
26 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
27 {
28   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
29   const char *sep_dflt = " \t\n\r\x0B";
30   char is_sep[256] = { 1, 0 };
31
32   /* check what are the separators */
33   memset(is_sep, 0, sizeof(is_sep));
34   if (not sep) {
35     while (*sep_dflt)
36       is_sep[(unsigned char) *sep_dflt++] = 1;
37   } else {
38     while (*sep)
39       is_sep[(unsigned char) *sep++] = 1;
40   }
41   is_sep[0] = 1; /* End of string is also separator */
42
43   /* Do the job */
44   const char* p = s;
45   const char* q = s;
46   int done      = 0;
47
48   if (s[0] == '\0')
49     return res;
50
51   while (not done) {
52     char *topush;
53     while (not is_sep[(unsigned char)*q]) {
54       q++;
55     }
56     if (*q == '\0')
57       done = 1;
58
59     topush = (char*) xbt_malloc(q - p + 1);
60     memcpy(topush, p, q - p);
61     topush[q - p] = '\0';
62     xbt_dynar_push(res, &topush);
63     p = ++q;
64   }
65
66   return res;
67 }
68
69 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
70  *
71  * The string passed as argument must be writable (not const)
72  * The elements of the dynar are just parts of the string passed as argument.
73  * So if you don't store that argument elsewhere, you should free it in addition to freeing the dynar. This can be done
74  * by simply freeing the first argument of the dynar:
75  *  free(xbt_dynar_get_ptr(dynar,0));
76  *
77  * Actually this function puts a bunch of \0 in the memory area you passed as argument to separate the elements, and
78  * pushes the address of each chunk in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
79  */
80 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
81   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), nullptr);
82   char* beg;
83   char* end; /* pointers around the parsed chunk */
84   int in_simple_quote = 0;
85   int in_double_quote = 0;
86   int done            = 0;
87   int ctn             = 0; /* Got something in this block */
88
89   if (s[0] == '\0')
90     return res;
91
92   beg = s;
93
94   /* do not trim leading spaces: caller responsibility to clean his cruft */
95   end = beg;
96
97   while (not done) {
98     switch (*end) {
99     case '\\':
100       ctn = 1;
101       /* Protected char; move it closer */
102       memmove(end, end + 1, strlen(end));
103       if (*end == '\0')
104         THROWF(arg_error, 0, "String ends with \\");
105       end++;                    /* Pass the protected char */
106       break;
107     case '\'':
108       ctn = 1;
109       if (not in_double_quote) {
110         in_simple_quote = not in_simple_quote;
111         memmove(end, end + 1, strlen(end));
112       } else {
113         /* simple quote protected by double ones */
114         end++;
115       }
116       break;
117     case '"':
118       ctn = 1;
119       if (not in_simple_quote) {
120         in_double_quote = not in_double_quote;
121         memmove(end, end + 1, strlen(end));
122       } else {
123         /* double quote protected by simple ones */
124         end++;
125       }
126       break;
127     case ' ':
128     case '\t':
129     case '\n':
130     case '\0':
131       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
132         THROWF(arg_error, 0, "End of string found while searching for %c in %s", (in_simple_quote ? '\'' : '"'), s);
133       }
134       if (in_simple_quote || in_double_quote) {
135         end++;
136       } else {
137         if (*end == '\0')
138           done = 1;
139
140         *end = '\0';
141         if (ctn) {
142           /* Found a separator. Push the string if contains something */
143           xbt_dynar_push(res, &beg);
144         }
145         ctn = 0;
146
147         if (done)
148           break;
149
150         beg = ++end;
151         /* trim within the string, manually to speed things up */
152         while (*beg == ' ')
153           beg++;
154         end = beg;
155       }
156       break;
157     default:
158       ctn = 1;
159       end++;
160     }
161   }
162   return res;
163 }
164
165 /** @brief Splits a string into a dynar of strings, taking quotes into account
166  *
167  * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
168  * are never split within a quote group.
169  * Several subsequent spaces are ignored (unless within quotes, of course).
170  * You may want to trim the input string, if you want to avoid empty entries
171  */
172 xbt_dynar_t xbt_str_split_quoted(const char *s)
173 {
174   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
175   xbt_dynar_t parsed;
176   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
177   unsigned int cursor;
178   char *p;
179
180   if (s[0] == '\0')
181     return res;
182   str_to_free = xbt_strdup(s);
183
184   parsed = xbt_str_split_quoted_in_place(str_to_free);
185   xbt_dynar_foreach(parsed,cursor,p) {
186     char *q=xbt_strdup(p);
187     xbt_dynar_push(res,&q);
188   }
189   xbt_free(str_to_free);
190   xbt_dynar_shrink(res, 0);
191   xbt_dynar_free(&parsed);
192   return res;
193 }
194
195 /** @brief Join a set of strings as a single string
196  *
197  * The parameter must be a nullptr-terminated array of chars,
198  * just like xbt_dynar_to_array() produces
199  */
200 char *xbt_str_join_array(const char *const *strs, const char *sep)
201 {
202   int amount_strings=0;
203   int len=0;
204
205   if ((not strs) || (not strs[0]))
206     return xbt_strdup("");
207
208   /* compute the length before malloc */
209   for (int i = 0; strs[i]; i++) {
210     len += strlen(strs[i]);
211     amount_strings++;
212   }
213   len += strlen(sep) * amount_strings;
214
215   /* Do the job */
216   char* res = (char*)xbt_malloc(len);
217   char* q   = res;
218   for (int i = 0; strs[i]; i++) {
219     if (i != 0) { // not first loop
220       q += snprintf(q,len, "%s%s", sep, strs[i]);
221     } else {
222       q += snprintf(q,len, "%s",strs[i]);
223     }
224   }
225   return res;
226 }
227
228 /** @brief Parse an integer out of a string, or raise an error
229  *
230  * The @a str is passed as argument to your @a error_msg, as follows:
231  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
232  */
233 long int xbt_str_parse_int(const char* str, const char* error_msg)
234 {
235   char* endptr;
236   if (str == nullptr || str[0] == '\0')
237     THROWF(arg_error, 0, error_msg, str);
238
239   long int res = strtol(str, &endptr, 10);
240   if (endptr[0] != '\0')
241     THROWF(arg_error, 0, error_msg, str);
242
243   return res;
244 }
245
246 /** @brief Parse a double out of a string, or raise an error
247  *
248  * The @a str is passed as argument to your @a error_msg, as follows:
249  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
250  */
251 double xbt_str_parse_double(const char* str, const char* error_msg)
252 {
253   char *endptr;
254   if (str == nullptr || str[0] == '\0')
255     THROWF(arg_error, 0, error_msg, str);
256
257   double res = strtod(str, &endptr);
258   if (endptr[0] != '\0')
259     THROWF(arg_error, 0, error_msg, str);
260
261   return res;
262 }