Logo AND Algorithmique Numérique Distribuée

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