Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[sonar] Replace some C-style arrays.
[simgrid.git] / src / xbt / xbt_str.cpp
1 /* xbt_str.cpp - various helping functions to deal with strings             */
2
3 /* Copyright (c) 2007-2020. 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 #include <array>
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   std::array<bool, 256> is_sep;
33
34   /* check what are the separators */
35   is_sep.fill(false);
36   if (not sep) {
37     while (*sep_dflt)
38       is_sep[(unsigned char)*sep_dflt++] = true;
39   } else {
40     while (*sep)
41       is_sep[(unsigned char)*sep++] = true;
42   }
43   is_sep[0] = true; /* 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         throw std::invalid_argument("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         throw std::invalid_argument(simgrid::xbt::string_printf("End of string found while searching for %c in %s",
135                                                                 (in_simple_quote ? '\'' : '"'), s));
136       }
137       if (in_simple_quote || in_double_quote) {
138         end++;
139       } else {
140         if (*end == '\0')
141           done = 1;
142
143         *end = '\0';
144         if (ctn) {
145           /* Found a separator. Push the string if contains something */
146           xbt_dynar_push(res, &beg);
147         }
148         ctn = 0;
149
150         if (done)
151           break;
152
153         beg = ++end;
154         /* trim within the string, manually to speed things up */
155         while (*beg == ' ')
156           beg++;
157         end = beg;
158       }
159       break;
160     default:
161       ctn = 1;
162       end++;
163     }
164   }
165   return res;
166 }
167
168 /** @brief Splits a string into a dynar of strings, taking quotes into account
169  *
170  * It basically does the same argument separation than the shell, where white spaces can be escaped and where arguments
171  * are never split within a quote group.
172  * Several subsequent spaces are ignored (unless within quotes, of course).
173  * You may want to trim the input string, if you want to avoid empty entries
174  */
175 xbt_dynar_t xbt_str_split_quoted(const char *s)
176 {
177   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
178   xbt_dynar_t parsed;
179   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
180   unsigned int cursor;
181   char *p;
182
183   if (s[0] == '\0')
184     return res;
185   str_to_free = xbt_strdup(s);
186
187   parsed = xbt_str_split_quoted_in_place(str_to_free);
188   xbt_dynar_foreach(parsed,cursor,p) {
189     char *q=xbt_strdup(p);
190     xbt_dynar_push(res,&q);
191   }
192   xbt_free(str_to_free);
193   xbt_dynar_shrink(res, 0);
194   xbt_dynar_free(&parsed);
195   return res;
196 }
197
198 /** @brief Parse an integer out of a string, or raise an error
199  *
200  * The @a str is passed as argument to your @a error_msg, as follows:
201  * @verbatim throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str)); @endverbatim
202  */
203 long int xbt_str_parse_int(const char* str, const char* error_msg)
204 {
205   char* endptr;
206   if (str == nullptr || str[0] == '\0')
207     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
208
209   long int res = strtol(str, &endptr, 10);
210   if (endptr[0] != '\0')
211     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
212
213   return res;
214 }
215
216 /** @brief Parse a double out of a string, or raise an error
217  *
218  * The @a str is passed as argument to your @a error_msg, as follows:
219  * @verbatim throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str)); @endverbatim
220  */
221 double xbt_str_parse_double(const char* str, const char* error_msg)
222 {
223   char *endptr;
224   if (str == nullptr || str[0] == '\0')
225     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
226
227   double res = strtod(str, &endptr);
228   if (endptr[0] != '\0')
229     throw std::invalid_argument(simgrid::xbt::string_printf(error_msg, str));
230
231   return res;
232 }