1 /* xbt_str.c - various helping functions to deal with strings */
3 /* Copyright (c) 2007-2014. The SimGrid Team.
4 * All rights reserved. */
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. */
9 #include "src/portable.h"
11 #include "xbt/sysdep.h"
12 #include "xbt/str.h" /* headers of these functions */
13 #include "xbt/strbuff.h"
14 #include "xbt/matrix.h" /* for the diff */
16 /** @brief Strip whitespace (or other characters) from the end of a string.
18 * Strips the whitespaces from the end of s.
19 * By default (when char_list=NULL), these characters get stripped:
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)) NULL.
26 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
28 * @param s The string to strip. Modified in place.
29 * @param char_list A string which contains the characters you want to strip.
32 void xbt_str_rtrim(char *s, const char *char_list)
35 const char *__char_list = " \t\n\r\x0B";
36 char white_char[256] = { 1, 0 };
42 while (*__char_list) {
43 white_char[(unsigned char) *__char_list++] = 1;
47 white_char[(unsigned char) *char_list++] = 1;
54 while ((cur >= s) && white_char[(unsigned char) *cur])
60 /** @brief Strip whitespace (or other characters) from the beginning of a string.
62 * Strips the whitespaces from the begining of s.
63 * By default (when char_list=NULL), these characters get stripped:
65 * - " " (ASCII 32 (0x20)) space.
66 * - "\t" (ASCII 9 (0x09)) tab.
67 * - "\n" (ASCII 10 (0x0A)) line feed.
68 * - "\r" (ASCII 13 (0x0D)) carriage return.
69 * - "\0" (ASCII 0 (0x00)) NULL.
70 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
72 * @param s The string to strip. Modified in place.
73 * @param char_list A string which contains the characters you want to strip.
76 void xbt_str_ltrim(char *s, const char *char_list)
79 const char *__char_list = " \t\n\r\x0B";
80 char white_char[256] = { 1, 0 };
86 while (*__char_list) {
87 white_char[(unsigned char) *__char_list++] = 1;
91 white_char[(unsigned char) *char_list++] = 1;
95 while (*cur && white_char[(unsigned char) *cur])
98 memmove(s, cur, strlen(cur) + 1);
101 /** @brief Strip whitespace (or other characters) from the end and the begining of a string.
103 * Strips the whitespaces from both the beginning and the end of s.
104 * By default (when char_list=NULL), these characters get stripped:
106 * - " " (ASCII 32 (0x20)) space.
107 * - "\t" (ASCII 9 (0x09)) tab.
108 * - "\n" (ASCII 10 (0x0A)) line feed.
109 * - "\r" (ASCII 13 (0x0D)) carriage return.
110 * - "\0" (ASCII 0 (0x00)) NULL.
111 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
113 * @param s The string to strip.
114 * @param char_list A string which contains the characters you want to strip.
117 void xbt_str_trim(char *s, const char *char_list)
123 xbt_str_rtrim(s, char_list);
124 xbt_str_ltrim(s, char_list);
127 /** @brief Substitutes a char for another in a string
129 * @param str the string to modify
130 * @param from char to search
131 * @param to char to put instead
132 * @param occurence number of changes to do (=0 means all)
134 void xbt_str_subst(char *str, char from, char to, int occurence)
148 /** @brief Replaces a set of variables by their values
150 * @param str The input of the replacement process
151 * @param patterns The changes to apply
152 * @return The string modified
154 * Both '$toto' and '${toto}' are valid (and the two writing are equivalent).
156 * If the variable name contains spaces, use the brace version (ie, ${toto tutu})
158 * You can provide a default value to use if the variable is not set in the dict by using
159 * '${var:=default}' or '${var:-default}'. These two forms are equivalent, even if they
160 * shouldn't to respect the shell standard (:= form should set the value in the dict,
161 * but does not) (BUG).
164 char *xbt_str_varsubst(const char *str, xbt_dict_t patterns)
166 xbt_strbuff_t buff = xbt_strbuff_new_from(str);
168 xbt_strbuff_varsubst(buff, patterns);
170 xbt_strbuff_free_container(buff);
175 /** @brief Splits a string into a dynar of strings
177 * @param s: the string to split
178 * @param sep: a string of all chars to consider as separator.
180 * By default (with sep=NULL), these characters are used as separator:
182 * - " " (ASCII 32 (0x20)) space.
183 * - "\t" (ASCII 9 (0x09)) tab.
184 * - "\n" (ASCII 10 (0x0A)) line feed.
185 * - "\r" (ASCII 13 (0x0D)) carriage return.
186 * - "\0" (ASCII 0 (0x00)) NULL.
187 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
190 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
192 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
195 const char *sep_dflt = " \t\n\r\x0B";
196 char is_sep[256] = { 1, 0 };
198 /* check what are the separators */
199 memset(is_sep, 0, sizeof(is_sep));
202 is_sep[(unsigned char) *sep_dflt++] = 1;
205 is_sep[(unsigned char) *sep++] = 1;
207 is_sep[0] = 1; /* End of string is also separator */
218 while (!is_sep[(unsigned char) *q]) {
224 topush = xbt_malloc(q - p + 1);
225 memcpy(topush, p, q - p);
226 topush[q - p] = '\0';
227 xbt_dynar_push(res, &topush);
235 * \brief This functions splits a string after using another string as separator
236 * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
237 * \return An array of dynars containing the string tokens
239 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
241 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
250 if (sep[0] == '\0') {
252 xbt_dynar_push(res, &s);
259 //get the start of the first occurence of the substring
261 //if substring was not found add the entire string
264 to_push = xbt_malloc(v + 1);
265 memcpy(to_push, p, v);
267 xbt_dynar_push(res, &to_push);
271 to_push = xbt_malloc(q - p + 1);
272 memcpy(to_push, p, q - p);
273 //add string terminator
274 to_push[q - p] = '\0';
275 xbt_dynar_push(res, &to_push);
282 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
284 * The string passed as argument must be writable (not const)
285 * The elements of the dynar are just parts of the string passed as argument.
286 * So if you don't store that argument elsewhere, you should free it in addition
287 * to freeing the dynar. This can be done by simply freeing the first argument
289 * free(xbt_dynar_get_ptr(dynar,0));
291 * Actually this function puts a bunch of \0 in the memory area you passed as
292 * argument to separate the elements, and pushes the address of each chunk
293 * in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
295 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
296 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), NULL);
297 char *beg, *end; /* pointers around the parsed chunk */
298 int in_simple_quote = 0, in_double_quote = 0;
300 int ctn = 0; /* Got something in this block */
307 /* do not trim leading spaces: caller responsibility to clean his cruft */
316 /* Protected char; move it closer */
317 memmove(end, end + 1, strlen(end));
319 THROWF(arg_error, 0, "String ends with \\");
320 end++; /* Pass the protected char */
325 if (!in_double_quote) {
326 in_simple_quote = !in_simple_quote;
327 memmove(end, end + 1, strlen(end));
329 /* simple quote protected by double ones */
335 if (!in_simple_quote) {
336 in_double_quote = !in_double_quote;
337 memmove(end, end + 1, strlen(end));
339 /* double quote protected by simple ones */
348 if (*end == '\0' && (in_simple_quote || in_double_quote)) {
350 "End of string found while searching for %c in %s",
351 (in_simple_quote ? '\'' : '"'), s);
353 if (in_simple_quote || in_double_quote) {
361 /* Found a separator. Push the string if contains something */
362 xbt_dynar_push(res, &beg);
370 /* trim within the string, manually to speed things up */
385 /** @brief Splits a string into a dynar of strings, taking quotes into account
387 * It basically does the same argument separation than the shell, where white
388 * spaces can be escaped and where arguments are never split within a
390 * Several subsequent spaces are ignored (unless within quotes, of course).
391 * You may want to trim the input string, if you want to avoid empty entries
395 xbt_dynar_t xbt_str_split_quoted(const char *s)
397 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
399 char *str_to_free; /* we have to copy the string before, to handle backslashes */
405 str_to_free = xbt_strdup(s);
407 parsed = xbt_str_split_quoted_in_place(str_to_free);
408 xbt_dynar_foreach(parsed,cursor,p) {
409 char *q=xbt_strdup(p);
410 xbt_dynar_push(res,&q);
413 xbt_dynar_shrink(res, 0);
414 xbt_dynar_free(&parsed);
418 /** @brief Join a set of strings as a single string */
419 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
421 int len = 1, dyn_len = xbt_dynar_length(dyn);
427 return xbt_strdup("");
429 /* compute the length */
430 xbt_dynar_foreach(dyn, cpt, cursor) {
431 len += strlen(cursor);
433 len += strlen(sep) * dyn_len;
435 res = xbt_malloc(len);
437 xbt_dynar_foreach(dyn, cpt, cursor) {
438 if ((int) cpt < dyn_len - 1)
439 p += sprintf(p, "%s%s", cursor, sep);
441 p += sprintf(p, "%s", cursor);
445 /** @brief Join a set of strings as a single string
447 * The parameter must be a NULL-terminated array of chars,
448 * just like xbt_dynar_to_array() produces
450 char *xbt_str_join_array(const char *const *strs, const char *sep)
453 int amount_strings=0;
457 if ((!strs) || (!strs[0]))
458 return xbt_strdup("");
460 /* compute the length before malloc */
461 for (i=0;strs[i];i++) {
462 len += strlen(strs[i]);
465 len += strlen(sep) * amount_strings;
468 q = res = xbt_malloc(len);
469 for (i=0;strs[i];i++) {
470 if (i!=0) { // not first loop
471 q += sprintf(q, "%s%s", sep, strs[i]);
473 q += sprintf(q,"%s",strs[i]);
479 /** @brief creates a new string containing what can be read on a fd
482 char *xbt_str_from_file(FILE * file)
484 xbt_strbuff_t buff = xbt_strbuff_new();
487 memset(bread, 0, 1024);
489 while (!feof(file)) {
490 int got = fread(bread, 1, 1023, file);
492 xbt_strbuff_append(buff, bread);
496 xbt_strbuff_free_container(buff);
500 /** @brief Parse an integer out of a string, or raise an error
502 * The #str is passed as argument to your #error_msg, as follows:
503 * THROWF(arg_error, 0, error_msg, str);
505 long int xbt_str_parse_int(const char* str, const char* error_msg)
508 if (str == NULL || str[0] == '\0')
509 THROWF(arg_error, 0, error_msg, str);
511 long int res = strtol(str, &endptr, 10);
512 if (endptr[0] != '\0')
513 THROWF(arg_error, 0, error_msg, str);
517 /** @brief Parse a double out of a string, or raise an error
519 * The #str is passed as argument to your #error_msg, as follows:
520 * THROWF(arg_error, 0, error_msg, str);
522 double xbt_str_parse_double(const char* str, const char* error_msg)
525 if (str == NULL || str[0] == '\0')
526 THROWF(arg_error, 0, error_msg, str);
528 double res = strtod(str, &endptr);
529 if (endptr[0] != '\0')
530 THROWF(arg_error, 0, error_msg, str);
538 XBT_TEST_SUITE("xbt_str", "String Handling");
540 #define mytest(name, input, expected) \
541 xbt_test_add(name); \
542 d=xbt_str_split_quoted(input); \
543 s=xbt_str_join(d,"XXX"); \
544 xbt_test_assert(!strcmp(s,expected),\
545 "Input (%s) leads to (%s) instead of (%s)", \
549 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
554 mytest("Empty", "", "");
555 mytest("Basic test", "toto tutu", "totoXXXtutu");
556 mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u",
558 mytest("Protected space", "toto\\ tutu", "toto tutu");
559 mytest("Several spaces", "toto tutu", "totoXXXtutu");
560 mytest("LTriming", " toto tatu", "totoXXXtatu");
561 mytest("Triming", " toto tutu ", "totoXXXtutu");
562 mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
563 mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
564 mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
565 mytest("Backslashed quotes", "\\'toto tutu\\' tata",
566 "'totoXXXtutu'XXXtata");
567 mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
568 "toto 'tutuXXXtata");
572 #define mytest_str(name, input, separator, expected) \
573 xbt_test_add(name); \
574 d=xbt_str_split_str(input, separator); \
575 s=xbt_str_join(d,"XXX"); \
576 xbt_test_assert(!strcmp(s,expected),\
577 "Input (%s) leads to (%s) instead of (%s)", \
582 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
587 mytest_str("Empty string and separator", "", "", "");
588 mytest_str("Empty string", "", "##", "");
589 mytest_str("Empty separator", "toto", "", "toto");
590 mytest_str("String with no separator in it", "toto", "##", "toto");
591 mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
594 #define test_parse_error(function, name, variable, str) \
596 xbt_test_add(name); \
598 variable = function(str, "Parse error"); \
599 xbt_test_fail("The test '%s' did not detect the problem",name ); \
601 if (e.category != arg_error) { \
602 xbt_test_exception(e); \
608 #define test_parse_ok(function, name, variable, str, value) \
610 xbt_test_add(name); \
612 variable = function(str, "Parse error"); \
614 xbt_test_exception(e); \
616 xbt_test_assert(variable == value, "Fail to parse '%s'", str); \
619 XBT_TEST_UNIT("xbt_str_parse", test_parse, "Test the parsing functions")
623 test_parse_ok(xbt_str_parse_int, "Parse int", rint, "42", 42);
624 test_parse_ok(xbt_str_parse_int, "Parse 0 as an int", rint, "0", 0);
625 test_parse_ok(xbt_str_parse_int, "Parse -1 as an int", rint, "-1", -1);
627 test_parse_error(xbt_str_parse_int, "Parse int + noise", rint, "342 cruft");
628 test_parse_error(xbt_str_parse_int, "Parse NULL as an int", rint, NULL);
629 test_parse_error(xbt_str_parse_int, "Parse '' as an int", rint, "");
630 test_parse_error(xbt_str_parse_int, "Parse cruft as an int", rint, "cruft");
632 double rdouble = -9999;
633 test_parse_ok(xbt_str_parse_double, "Parse 42 as a double", rdouble, "42", 42);
634 test_parse_ok(xbt_str_parse_double, "Parse 42.5 as a double", rdouble, "42.5", 42.5);
635 test_parse_ok(xbt_str_parse_double, "Parse 0 as a double", rdouble, "0", 0);
636 test_parse_ok(xbt_str_parse_double, "Parse -1 as a double", rdouble, "-1", -1);
638 test_parse_error(xbt_str_parse_double, "Parse double + noise", rdouble, "342 cruft");
639 test_parse_error(xbt_str_parse_double, "Parse NULL as a double", rdouble, NULL);
640 test_parse_error(xbt_str_parse_double, "Parse '' as a double", rdouble, "");
641 test_parse_error(xbt_str_parse_double, "Parse cruft as a double", rdouble, "cruft");
644 #endif /* SIMGRID_TEST */