3 /* xbt_str.c - various helping functions to deal with strings */
5 /* Copyright (C) 2005-2008 The SimGrid Team. */
6 /* All rights reserved. */
8 /* This program is free software; you can redistribute it and/or modify it
9 * under the terms of the license (GNU LGPL) which comes with this package.
14 #include "xbt/sysdep.h"
15 #include "xbt/str.h" /* headers of these functions */
16 #include "xbt/strbuff.h"
17 #include "xbt/matrix.h" /* for the diff */
19 /** @brief Strip whitespace (or other characters) from the end of a string.
21 * Strips the whitespaces from the end of s.
22 * By default (when char_list=NULL), these characters get stripped:
24 * - " " (ASCII 32 (0x20)) space.
25 * - "\t" (ASCII 9 (0x09)) tab.
26 * - "\n" (ASCII 10 (0x0A)) line feed.
27 * - "\r" (ASCII 13 (0x0D)) carriage return.
28 * - "\0" (ASCII 0 (0x00)) NULL.
29 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
31 * @param s The string to strip. Modified in place.
32 * @param char_list A string which contains the characters you want to strip.
35 void xbt_str_rtrim(char *s, const char *char_list)
38 const char *__char_list = " \t\n\r\x0B";
39 char white_char[256] = { 1, 0 };
45 while (*__char_list) {
46 white_char[(unsigned char) *__char_list++] = 1;
50 white_char[(unsigned char) *char_list++] = 1;
57 while ((cur >= s) && white_char[(unsigned char) *cur])
63 /** @brief Strip whitespace (or other characters) from the beginning of a string.
65 * Strips the whitespaces from the begining of s.
66 * By default (when char_list=NULL), these characters get stripped:
68 * - " " (ASCII 32 (0x20)) space.
69 * - "\t" (ASCII 9 (0x09)) tab.
70 * - "\n" (ASCII 10 (0x0A)) line feed.
71 * - "\r" (ASCII 13 (0x0D)) carriage return.
72 * - "\0" (ASCII 0 (0x00)) NULL.
73 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
75 * @param s The string to strip. Modified in place.
76 * @param char_list A string which contains the characters you want to strip.
79 void xbt_str_ltrim(char *s, const char *char_list)
82 const char *__char_list = " \t\n\r\x0B";
83 char white_char[256] = { 1, 0 };
89 while (*__char_list) {
90 white_char[(unsigned char) *__char_list++] = 1;
94 white_char[(unsigned char) *char_list++] = 1;
98 while (*cur && white_char[(unsigned char) *cur])
101 memmove(s, cur, strlen(cur) + 1);
104 /** @brief Strip whitespace (or other characters) from the end and the begining of a string.
106 * Strips the whitespaces from both the beginning and the end of s.
107 * By default (when char_list=NULL), these characters get stripped:
109 * - " " (ASCII 32 (0x20)) space.
110 * - "\t" (ASCII 9 (0x09)) tab.
111 * - "\n" (ASCII 10 (0x0A)) line feed.
112 * - "\r" (ASCII 13 (0x0D)) carriage return.
113 * - "\0" (ASCII 0 (0x00)) NULL.
114 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
116 * @param s The string to strip.
117 * @param char_list A string which contains the characters you want to strip.
120 void xbt_str_trim(char *s, const char *char_list)
126 xbt_str_rtrim(s, char_list);
127 xbt_str_ltrim(s, char_list);
130 /** @brief Replace double whitespaces (but no other characters) from the string.
132 * The function modifies the string so that each time that several spaces appear,
133 * they are replaced by a single space. It will only do so for spaces (ASCII 32, 0x20).
135 * @param s The string to strip. Modified in place.
138 void xbt_str_strip_spaces(char *s)
174 /** @brief Substitutes a char for another in a string
176 * @param str the string to modify
177 * @param from char to search
178 * @param to char to put instead
179 * @param amount amount of changes to do (=0 means all)
181 void xbt_str_subst(char *str, char from, char to, int occurence)
195 /** @brief Replaces a set of variables by their values
197 * @param str where to apply the change
198 * @param patterns what to change
199 * @return The string modified
201 * Check xbt_strbuff_varsubst() for more details, and remember that the string may be reallocated (moved) in the process.
204 char *xbt_str_varsubst(char *str, xbt_dict_t patterns)
206 xbt_strbuff_t buff = xbt_strbuff_new_from(str);
208 xbt_strbuff_varsubst(buff, patterns);
210 xbt_strbuff_free_container(buff);
215 /** @brief Splits a string into a dynar of strings
217 * @param s: the string to split
218 * @param sep: a string of all chars to consider as separator.
220 * By default (with sep=NULL), these characters are used as separator:
222 * - " " (ASCII 32 (0x20)) space.
223 * - "\t" (ASCII 9 (0x09)) tab.
224 * - "\n" (ASCII 10 (0x0A)) line feed.
225 * - "\r" (ASCII 13 (0x0D)) carriage return.
226 * - "\0" (ASCII 0 (0x00)) NULL.
227 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
230 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
232 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
235 const char *sep_dflt = " \t\n\r\x0B";
236 char is_sep[256] = { 1, 0 };
238 /* check what are the separators */
239 memset(is_sep, 0, sizeof(is_sep));
242 is_sep[(unsigned char) *sep_dflt++] = 1;
245 is_sep[(unsigned char) *sep++] = 1;
247 is_sep[0] = 1; /* End of string is also separator */
258 while (!is_sep[(unsigned char) *q]) {
264 topush = xbt_malloc(q - p + 1);
265 memcpy(topush, p, q - p);
266 topush[q - p] = '\0';
267 xbt_dynar_push(res, &topush);
275 * \brief This functions splits a string after using another string as separator
276 * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
277 * \return An array of dynars containing the string tokens
279 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
281 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
290 if (sep[0] == '\0') {
292 xbt_dynar_push(res, &s);
299 //get the start of the first occurence of the substring
301 //if substring was not found add the entire string
304 to_push = malloc(v + 1);
305 memcpy(to_push, p, v);
307 xbt_dynar_push(res, &to_push);
311 to_push = malloc(q - p + 1);
312 memcpy(to_push, p, q - p);
313 //add string terminator
314 to_push[q - p] = '\0';
315 xbt_dynar_push(res, &to_push);
322 /** @brief Splits a string into a dynar of strings, taking quotes into account
324 * It basically does the same argument separation than the shell, where white
325 * spaces can be escaped and where arguments are never splitted within a
327 * Several subsequent spaces are ignored (unless within quotes, of course).
331 xbt_dynar_t xbt_str_split_quoted(const char *s)
333 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
334 char *str_to_free; /* we have to copy the string before, to handle backslashes */
335 char *beg, *end; /* pointers around the parsed chunk */
336 int in_simple_quote = 0, in_double_quote = 0;
338 int ctn = 0; /* Got something in this block */
342 beg = str_to_free = xbt_strdup(s);
344 /* trim leading spaces */
345 xbt_str_ltrim(beg, " ");
354 /* Protected char; move it closer */
355 memmove(end, end + 1, strlen(end));
357 THROW0(arg_error, 0, "String ends with \\");
358 end++; /* Pass the protected char */
363 if (!in_double_quote) {
364 in_simple_quote = !in_simple_quote;
365 memmove(end, end + 1, strlen(end));
367 /* simple quote protected by double ones */
373 if (!in_simple_quote) {
374 in_double_quote = !in_double_quote;
375 memmove(end, end + 1, strlen(end));
377 /* double quote protected by simple ones */
386 if (*end == '\0' && (in_simple_quote || in_double_quote)) {
388 "End of string found while searching for %c in %s",
389 (in_simple_quote ? '\'' : '"'), s);
391 if (in_simple_quote || in_double_quote) {
395 /* Found a separator. Push the string if contains something */
396 char *topush = xbt_malloc(end - beg + 1);
397 memcpy(topush, beg, end - beg);
398 topush[end - beg] = '\0';
399 xbt_dynar_push(res, &topush);
409 xbt_str_ltrim(beg, " ");
426 #define mytest(name, input, expected) \
427 xbt_test_add0(name); \
428 d=xbt_str_split_quoted(input); \
429 s=xbt_str_join(d,"XXX"); \
430 xbt_test_assert3(!strcmp(s,expected),\
431 "Input (%s) leads to (%s) instead of (%s)", \
436 XBT_TEST_SUITE("xbt_str", "String Handling");
437 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted,"test the function xbt_str_split_quoted")
442 mytest("Empty", "", "");
443 mytest("Basic test", "toto tutu", "totoXXXtutu");
444 mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
445 mytest("Protected space", "toto\\ tutu", "toto tutu");
446 mytest("Several spaces", "toto tutu", "totoXXXtutu");
447 mytest("LTriming", " toto tatu", "totoXXXtatu");
448 mytest("Triming", " toto tutu ", "totoXXXtutu");
449 mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
450 mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
451 mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
452 mytest("Backslashed quotes", "\\'toto tutu\\' tata",
453 "'totoXXXtutu'XXXtata");
454 mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
455 "toto 'tutuXXXtata");
459 #define mytest_str(name, input, separator, expected) \
460 xbt_test_add0(name); \
461 d=xbt_str_split_str(input, separator); \
462 s=xbt_str_join(d,"XXX"); \
463 xbt_test_assert3(!strcmp(s,expected),\
464 "Input (%s) leads to (%s) instead of (%s)", \
469 XBT_TEST_UNIT("xbt_str_split_str", test_split_str,"test the function xbt_str_split_str")
474 mytest_str("Empty string and separator", "", "", "");
475 mytest_str("Empty string", "", "##", "");
476 mytest_str("Empty separator", "toto", "", "toto");
477 mytest_str("String with no separator in it", "toto", "##", "toto");
478 mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
480 #endif /* SIMGRID_TEST */
482 /** @brief Join a set of strings as a single string */
484 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
486 int len = 1, dyn_len = xbt_dynar_length(dyn);
492 return xbt_strdup("");
494 /* compute the length */
495 xbt_dynar_foreach(dyn, cpt, cursor) {
496 len += strlen(cursor);
498 len += strlen(sep) * dyn_len;
500 res = xbt_malloc(len);
502 xbt_dynar_foreach(dyn, cpt, cursor) {
503 if ((int) cpt < dyn_len - 1)
504 p += sprintf(p, "%s%s", cursor, sep);
506 p += sprintf(p, "%s", cursor);
511 #if defined(SIMGRID_NEED_GETLINE) || defined(DOXYGEN)
512 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
514 * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
516 * getline() reads an entire line from stream, storing the address of the buffer
517 * containing the text into *buf. The buffer is null-terminated and includes
518 * the newline character, if one was found.
520 * If *buf is NULL, then getline() will allocate a buffer for storing the line,
521 * which should be freed by the user program. Alternatively, before calling getline(),
522 * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size. If the buffer
523 * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n
524 * as necessary. In either case, on a successful call, *buf and *n will be updated to
525 * reflect the buffer address and allocated size respectively.
527 long getline(char **buf, size_t * n, FILE * stream)
534 *buf = xbt_malloc(512);
539 return (ssize_t) - 1;
541 for (i = 0; (ch = fgetc(stream)) != EOF; i++) {
544 *buf = xbt_realloc(*buf, *n += 512);
548 if ((*buf)[i] == '\n') {
556 *buf = xbt_realloc(*buf, *n += 1);
563 #endif /* HAVE_GETLINE */
566 * Diff related functions
568 static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db)
570 xbt_matrix_t C = xbt_matrix_new(xbt_dynar_length(da), xbt_dynar_length(db),
574 /* Compute the LCS */
576 C = array(0..m, 0..n)
584 C[i,j] := C[i-1,j-1] + 1
586 C[i,j] := max(C[i,j-1], C[i-1,j])
589 if (xbt_dynar_length(db) != 0)
590 for (i = 0; i < xbt_dynar_length(da); i++)
591 *((int *) xbt_matrix_get_ptr(C, i, 0)) = 0;
593 if (xbt_dynar_length(da) != 0)
594 for (j = 0; j < xbt_dynar_length(db); j++)
595 *((int *) xbt_matrix_get_ptr(C, 0, j)) = 0;
597 for (i = 1; i < xbt_dynar_length(da); i++)
598 for (j = 1; j < xbt_dynar_length(db); j++) {
601 (xbt_dynar_get_as(da, i, char *), xbt_dynar_get_as(db, j, char *)))
602 *((int *) xbt_matrix_get_ptr(C, i, j)) =
603 xbt_matrix_get_as(C, i - 1, j - 1, int) + 1;
605 *((int *) xbt_matrix_get_ptr(C, i, j)) =
606 max(xbt_matrix_get_as(C, i, j - 1, int),
607 xbt_matrix_get_as(C, i - 1, j, int));
612 static void diff_build_diff(xbt_dynar_t res,
614 xbt_dynar_t da, xbt_dynar_t db, int i, int j)
617 /* Construct the diff
618 function printDiff(C[0..m,0..n], X[1..m], Y[1..n], i, j)
619 if i > 0 and j > 0 and X[i] = Y[j]
620 printDiff(C, X, Y, i-1, j-1)
623 if j > 0 and (i = 0 or C[i,j-1] >= C[i-1,j])
624 printDiff(C, X, Y, i, j-1)
626 else if i > 0 and (j = 0 or C[i,j-1] < C[i-1,j])
627 printDiff(C, X, Y, i-1, j)
631 if (i >= 0 && j >= 0 && !strcmp(xbt_dynar_get_as(da, i, char *),
632 xbt_dynar_get_as(db, j, char *))) {
633 diff_build_diff(res, C, da, db, i - 1, j - 1);
634 topush = bprintf(" %s", xbt_dynar_get_as(da, i, char *));
635 xbt_dynar_push(res, &topush);
638 || xbt_matrix_get_as(C, i, j - 1, int) >= xbt_matrix_get_as(C,
644 diff_build_diff(res, C, da, db, i, j - 1);
645 topush = bprintf("+ %s", xbt_dynar_get_as(db, j, char *));
646 xbt_dynar_push(res, &topush);
649 || xbt_matrix_get_as(C, i, j - 1, int) < xbt_matrix_get_as(C,
654 diff_build_diff(res, C, da, db, i - 1, j);
655 topush = bprintf("- %s", xbt_dynar_get_as(da, i, char *));
656 xbt_dynar_push(res, &topush);
657 } else if (i <= 0 && j <= 0) {
660 THROW2(arg_error, 0, "Invalid values: i=%d, j=%d", i, j);
665 /** @brief Compute the unified diff of two strings */
666 char *xbt_str_diff(char *a, char *b)
668 xbt_dynar_t da = xbt_str_split(a, "\n");
669 xbt_dynar_t db = xbt_str_split(b, "\n");
671 xbt_matrix_t C = diff_build_LCS(da, db);
672 xbt_dynar_t diff = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
675 diff_build_diff(diff, C, da, db, xbt_dynar_length(da) - 1,
676 xbt_dynar_length(db) - 1);
677 /* Clean empty lines at the end */
678 while (xbt_dynar_length(diff) > 0) {
680 xbt_dynar_pop(diff, &str);
681 if (str[0] == '\0' || !strcmp(str, " ")) {
684 xbt_dynar_push(diff, &str);
688 res = xbt_str_join(diff, "\n");
692 xbt_dynar_free(&diff);
699 /** @brief creates a new string containing what can be read on a fd
702 char* xbt_str_from_file(FILE *file) {
703 xbt_strbuff_t buff = xbt_strbuff_new();
706 memset(bread,0,1024);
708 while (!feof(file)) {
709 int got = fread(bread, 1, 1023, file);
711 xbt_strbuff_append(buff,bread);
715 xbt_strbuff_free_container(buff);