Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
b5300552bf8e46422a6f96b9d012a7767a9a8c55
[simgrid.git] / src / xbt / xbt_str.cpp
1 /* xbt_str.cpp - various helping functions to deal with strings             */
2
3 /* Copyright (c) 2007-2018. 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 #include "xbt/sysdep.h"
12
13 /** @brief Splits a string into a dynar of strings
14  *
15  * @param s: the string to split
16  * @param sep: a string of all chars to consider as separator.
17  *
18  * By default (with sep=nullptr), these characters are used as separator:
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 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
28 {
29   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
30   const char *sep_dflt = " \t\n\r\x0B";
31   char is_sep[256] = { 1, 0 };
32
33   /* check what are the separators */
34   memset(is_sep, 0, sizeof(is_sep));
35   if (not sep) {
36     while (*sep_dflt)
37       is_sep[(unsigned char) *sep_dflt++] = 1;
38   } else {
39     while (*sep)
40       is_sep[(unsigned char) *sep++] = 1;
41   }
42   is_sep[0] = 1; /* End of string is also separator */
43
44   /* Do the job */
45   const char* p = s;
46   const char* q = s;
47   int done      = 0;
48
49   if (s[0] == '\0')
50     return res;
51
52   while (not done) {
53     char *topush;
54     while (not is_sep[(unsigned char)*q]) {
55       q++;
56     }
57     if (*q == '\0')
58       done = 1;
59
60     topush = (char*) xbt_malloc(q - p + 1);
61     memcpy(topush, p, q - p);
62     topush[q - p] = '\0';
63     xbt_dynar_push(res, &topush);
64     p = ++q;
65   }
66
67   return res;
68 }
69
70 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
71  *
72  * The string passed as argument must be writable (not const)
73  * The elements of the dynar are just parts of the string passed as argument.
74  * So if you don't store that argument elsewhere, you should free it in addition to freeing the dynar. This can be done
75  * by simply freeing the first argument of the dynar:
76  *  free(xbt_dynar_get_ptr(dynar,0));
77  *
78  * Actually this function puts a bunch of \0 in the memory area you passed as argument to separate the elements, and
79  * pushes the address of each chunk in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
80  */
81 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
82   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), nullptr);
83   char* beg;
84   char* end; /* pointers around the parsed chunk */
85   int in_simple_quote = 0;
86   int in_double_quote = 0;
87   int done            = 0;
88   int ctn             = 0; /* Got something in this block */
89
90   if (s[0] == '\0')
91     return res;
92
93   beg = s;
94
95   /* do not trim leading spaces: caller responsibility to clean his cruft */
96   end = beg;
97
98   while (not done) {
99     switch (*end) {
100     case '\\':
101       ctn = 1;
102       /* Protected char; move it closer */
103       memmove(end, end + 1, strlen(end));
104       if (*end == '\0')
105         THROWF(arg_error, 0, "String ends with \\");
106       end++;                    /* Pass the protected char */
107       break;
108     case '\'':
109       ctn = 1;
110       if (not in_double_quote) {
111         in_simple_quote = not in_simple_quote;
112         memmove(end, end + 1, strlen(end));
113       } else {
114         /* simple quote protected by double ones */
115         end++;
116       }
117       break;
118     case '"':
119       ctn = 1;
120       if (not in_simple_quote) {
121         in_double_quote = not in_double_quote;
122         memmove(end, end + 1, strlen(end));
123       } else {
124         /* double quote protected by simple ones */
125         end++;
126       }
127       break;
128     case ' ':
129     case '\t':
130     case '\n':
131     case '\0':
132       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
133         THROWF(arg_error, 0, "End of string found while searching for %c in %s", (in_simple_quote ? '\'' : '"'), s);
134       }
135       if (in_simple_quote || in_double_quote) {
136         end++;
137       } else {
138         if (*end == '\0')
139           done = 1;
140
141         *end = '\0';
142         if (ctn) {
143           /* Found a separator. Push the string if contains something */
144           xbt_dynar_push(res, &beg);
145         }
146         ctn = 0;
147
148         if (done)
149           break;
150
151         beg = ++end;
152         /* trim within the string, manually to speed things up */
153         while (*beg == ' ')
154           beg++;
155         end = beg;
156       }
157       break;
158     default:
159       ctn = 1;
160       end++;
161     }
162   }
163   return res;
164 }
165
166 /** @brief Splits a string into a dynar of strings, taking quotes into account
167  *
168  * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
169  * are never split within a quote group.
170  * Several subsequent spaces are ignored (unless within quotes, of course).
171  * You may want to trim the input string, if you want to avoid empty entries
172  */
173 xbt_dynar_t xbt_str_split_quoted(const char *s)
174 {
175   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
176   xbt_dynar_t parsed;
177   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
178   unsigned int cursor;
179   char *p;
180
181   if (s[0] == '\0')
182     return res;
183   str_to_free = xbt_strdup(s);
184
185   parsed = xbt_str_split_quoted_in_place(str_to_free);
186   xbt_dynar_foreach(parsed,cursor,p) {
187     char *q=xbt_strdup(p);
188     xbt_dynar_push(res,&q);
189   }
190   xbt_free(str_to_free);
191   xbt_dynar_shrink(res, 0);
192   xbt_dynar_free(&parsed);
193   return res;
194 }
195
196 /** @brief Join a set of strings as a single string
197  *
198  * The parameter must be a nullptr-terminated array of chars,
199  * just like xbt_dynar_to_array() produces
200  */
201 char *xbt_str_join_array(const char *const *strs, const char *sep)
202 {
203   int amount_strings=0;
204   int len=0;
205
206   if ((not strs) || (not strs[0]))
207     return xbt_strdup("");
208
209   /* compute the length before malloc */
210   for (int i = 0; strs[i]; i++) {
211     len += strlen(strs[i]);
212     amount_strings++;
213   }
214   len += strlen(sep) * amount_strings;
215
216   /* Do the job */
217   char* res = (char*)xbt_malloc(len);
218   char* q   = res;
219   for (int i = 0; strs[i]; i++) {
220     if (i != 0) { // not first loop
221       q += snprintf(q,len, "%s%s", sep, strs[i]);
222     } else {
223       q += snprintf(q,len, "%s",strs[i]);
224     }
225   }
226   return res;
227 }
228
229 /** @brief Parse an integer out of a string, or raise an error
230  *
231  * The @a str is passed as argument to your @a error_msg, as follows:
232  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
233  */
234 long int xbt_str_parse_int(const char* str, const char* error_msg)
235 {
236   char* endptr;
237   if (str == nullptr || str[0] == '\0')
238     THROWF(arg_error, 0, error_msg, str);
239
240   long int res = strtol(str, &endptr, 10);
241   if (endptr[0] != '\0')
242     THROWF(arg_error, 0, error_msg, str);
243
244   return res;
245 }
246
247 /** @brief Parse a double out of a string, or raise an error
248  *
249  * The @a str is passed as argument to your @a error_msg, as follows:
250  * @verbatim THROWF(arg_error, 0, error_msg, str); @endverbatim
251  */
252 double xbt_str_parse_double(const char* str, const char* error_msg)
253 {
254   char *endptr;
255   if (str == nullptr || str[0] == '\0')
256     THROWF(arg_error, 0, error_msg, str);
257
258   double res = strtod(str, &endptr);
259   if (endptr[0] != '\0')
260     THROWF(arg_error, 0, error_msg, str);
261
262   return res;
263 }
264
265 #ifdef SIMGRID_TEST
266 #include "simgrid/exception.hpp"
267 #include "xbt/str.h"
268
269 XBT_TEST_SUITE("xbt_str", "String Handling");
270
271 #define mytest(name, input, expected)                                                                                  \
272   xbt_test_add(name);                                                                                                  \
273   a = static_cast<char**>(xbt_dynar_to_array(xbt_str_split_quoted(input)));                                            \
274   s = xbt_str_join_array(a, "XXX");                                                                                    \
275   xbt_test_assert(not strcmp(s, expected), "Input (%s) leads to (%s) instead of (%s)", input, s, expected);            \
276   xbt_free(s);                                                                                                         \
277   for (int i = 0; a[i] != nullptr; i++)                                                                                \
278     xbt_free(a[i]);                                                                                                    \
279   xbt_free(a);
280 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "Test the function xbt_str_split_quoted")
281 {
282   char** a;
283   char *s;
284
285   mytest("Empty", "", "");
286   mytest("Basic test", "toto tutu", "totoXXXtutu");
287   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
288   mytest("Protected space", "toto\\ tutu", "toto tutu");
289   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
290   mytest("LTriming", "  toto tatu", "totoXXXtatu");
291   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
292   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
293   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
294   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
295   mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
296   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
297 }
298
299 #define test_parse_error(function, name, variable, str)                 \
300   do {                                                                  \
301     xbt_test_add(name);                                                 \
302     try {                                                               \
303       variable = function(str, "Parse error");                          \
304       xbt_test_fail("The test '%s' did not detect the problem",name );  \
305     } catch(xbt_ex& e) {                                                \
306       if (e.category != arg_error) {                                    \
307         xbt_test_exception(e);                                          \
308       }                                                                 \
309     }                                                                   \
310   } while (0)
311 #define test_parse_ok(function, name, variable, str, value)             \
312   do {                                                                  \
313     xbt_test_add(name);                                                 \
314     try {                                                               \
315       variable = function(str, "Parse error");                          \
316     } catch(xbt_ex& e) {                                                \
317       xbt_test_exception(e);                                            \
318     }                                                                   \
319     xbt_test_assert(variable == value, "Fail to parse '%s'", str);      \
320   } while (0)
321
322 XBT_TEST_UNIT("xbt_str_parse", test_parse, "Test the parsing functions")
323 {
324   int rint = -9999;
325   test_parse_ok(xbt_str_parse_int, "Parse int", rint, "42", 42);
326   test_parse_ok(xbt_str_parse_int, "Parse 0 as an int", rint, "0", 0);
327   test_parse_ok(xbt_str_parse_int, "Parse -1 as an int", rint, "-1", -1);
328
329   test_parse_error(xbt_str_parse_int, "Parse int + noise", rint, "342 cruft");
330   test_parse_error(xbt_str_parse_int, "Parse nullptr as an int", rint, nullptr);
331   test_parse_error(xbt_str_parse_int, "Parse '' as an int", rint, "");
332   test_parse_error(xbt_str_parse_int, "Parse cruft as an int", rint, "cruft");
333
334   double rdouble = -9999;
335   test_parse_ok(xbt_str_parse_double, "Parse 42 as a double", rdouble, "42", 42);
336   test_parse_ok(xbt_str_parse_double, "Parse 42.5 as a double", rdouble, "42.5", 42.5);
337   test_parse_ok(xbt_str_parse_double, "Parse 0 as a double", rdouble, "0", 0);
338   test_parse_ok(xbt_str_parse_double, "Parse -1 as a double", rdouble, "-1", -1);
339
340   test_parse_error(xbt_str_parse_double, "Parse double + noise", rdouble, "342 cruft");
341   test_parse_error(xbt_str_parse_double, "Parse nullptr as a double", rdouble, nullptr);
342   test_parse_error(xbt_str_parse_double, "Parse '' as a double", rdouble, "");
343   test_parse_error(xbt_str_parse_double, "Parse cruft as a double", rdouble, "cruft");
344 }
345 #endif                          /* SIMGRID_TEST */