Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
attach errhandlers to some forgotten calls
[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 #include "xbt/string.hpp"
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         throw std::invalid_argument("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         throw std::invalid_argument(simgrid::xbt::string_printf("End of string found while searching for %c in %s",
134                                                                 (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   xbt_free(str_to_free);
192   xbt_dynar_shrink(res, 0);
193   xbt_dynar_free(&parsed);
194   return res;
195 }
196
197 /** @brief Parse an integer out of a string, or raise an error
198  *
199  * The @a str is passed as argument to your @a error_msg, as follows:
200  * @verbatim throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str)); @endverbatim
201  */
202 long int xbt_str_parse_int(const char* str, const char* error_msg)
203 {
204   char* endptr;
205   if (str == nullptr || str[0] == '\0')
206     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
207
208   long int res = strtol(str, &endptr, 10);
209   if (endptr[0] != '\0')
210     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
211
212   return res;
213 }
214
215 /** @brief Parse a double out of a string, or raise an error
216  *
217  * The @a str is passed as argument to your @a error_msg, as follows:
218  * @verbatim throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str)); @endverbatim
219  */
220 double xbt_str_parse_double(const char* str, const char* error_msg)
221 {
222   char *endptr;
223   if (str == nullptr || str[0] == '\0')
224     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
225
226   double res = strtod(str, &endptr);
227   if (endptr[0] != '\0')
228     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
229
230   return res;
231 }