1 /* xbt_str.c - various helping functions to deal with strings */
3 /* Copyright (C) 2005-2008 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.
12 #include "xbt/sysdep.h"
13 #include "xbt/str.h" /* headers of these functions */
14 #include "xbt/strbuff.h"
15 #include "xbt/matrix.h" /* for the diff */
17 /** @brief Strip whitespace (or other characters) from the end of a string.
19 * Strips the whitespaces from the end of s.
20 * By default (when char_list=NULL), these characters get stripped:
22 * - " " (ASCII 32 (0x20)) space.
23 * - "\t" (ASCII 9 (0x09)) tab.
24 * - "\n" (ASCII 10 (0x0A)) line feed.
25 * - "\r" (ASCII 13 (0x0D)) carriage return.
26 * - "\0" (ASCII 0 (0x00)) NULL.
27 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
29 * @param s The string to strip. Modified in place.
30 * @param char_list A string which contains the characters you want to strip.
33 void xbt_str_rtrim(char *s, const char *char_list)
36 const char *__char_list = " \t\n\r\x0B";
37 char white_char[256] = { 1, 0 };
43 while (*__char_list) {
44 white_char[(unsigned char) *__char_list++] = 1;
48 white_char[(unsigned char) *char_list++] = 1;
55 while ((cur >= s) && white_char[(unsigned char) *cur])
61 /** @brief Strip whitespace (or other characters) from the beginning of a string.
63 * Strips the whitespaces from the begining of s.
64 * By default (when char_list=NULL), these characters get stripped:
66 * - " " (ASCII 32 (0x20)) space.
67 * - "\t" (ASCII 9 (0x09)) tab.
68 * - "\n" (ASCII 10 (0x0A)) line feed.
69 * - "\r" (ASCII 13 (0x0D)) carriage return.
70 * - "\0" (ASCII 0 (0x00)) NULL.
71 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
73 * @param s The string to strip. Modified in place.
74 * @param char_list A string which contains the characters you want to strip.
77 void xbt_str_ltrim(char *s, const char *char_list)
80 const char *__char_list = " \t\n\r\x0B";
81 char white_char[256] = { 1, 0 };
87 while (*__char_list) {
88 white_char[(unsigned char) *__char_list++] = 1;
92 white_char[(unsigned char) *char_list++] = 1;
96 while (*cur && white_char[(unsigned char) *cur])
99 memmove(s, cur, strlen(cur) + 1);
102 /** @brief Strip whitespace (or other characters) from the end and the begining of a string.
104 * Strips the whitespaces from both the beginning and the end of s.
105 * By default (when char_list=NULL), these characters get stripped:
107 * - " " (ASCII 32 (0x20)) space.
108 * - "\t" (ASCII 9 (0x09)) tab.
109 * - "\n" (ASCII 10 (0x0A)) line feed.
110 * - "\r" (ASCII 13 (0x0D)) carriage return.
111 * - "\0" (ASCII 0 (0x00)) NULL.
112 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
114 * @param s The string to strip.
115 * @param char_list A string which contains the characters you want to strip.
118 void xbt_str_trim(char *s, const char *char_list)
124 xbt_str_rtrim(s, char_list);
125 xbt_str_ltrim(s, char_list);
128 /** @brief Replace double whitespaces (but no other characters) from the string.
130 * The function modifies the string so that each time that several spaces appear,
131 * they are replaced by a single space. It will only do so for spaces (ASCII 32, 0x20).
133 * @param s The string to strip. Modified in place.
136 void xbt_str_strip_spaces(char *s)
172 /** @brief Substitutes a char for another in a string
174 * @param str the string to modify
175 * @param from char to search
176 * @param to char to put instead
177 * @param amount amount of changes to do (=0 means all)
179 void xbt_str_subst(char *str, char from, char to, int occurence)
193 /** @brief Replaces a set of variables by their values
195 * @param str where to apply the change
196 * @param patterns what to change
197 * @return The string modified
199 * Check xbt_strbuff_varsubst() for more details, and remember that the string may be reallocated (moved) in the process.
202 char *xbt_str_varsubst(char *str, xbt_dict_t patterns)
204 xbt_strbuff_t buff = xbt_strbuff_new_from(str);
206 xbt_strbuff_varsubst(buff, patterns);
208 xbt_strbuff_free_container(buff);
213 /** @brief Splits a string into a dynar of strings
215 * @param s: the string to split
216 * @param sep: a string of all chars to consider as separator.
218 * By default (with sep=NULL), these characters are used as separator:
220 * - " " (ASCII 32 (0x20)) space.
221 * - "\t" (ASCII 9 (0x09)) tab.
222 * - "\n" (ASCII 10 (0x0A)) line feed.
223 * - "\r" (ASCII 13 (0x0D)) carriage return.
224 * - "\0" (ASCII 0 (0x00)) NULL.
225 * - "\x0B" (ASCII 11 (0x0B)) vertical tab.
228 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
230 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
233 const char *sep_dflt = " \t\n\r\x0B";
234 char is_sep[256] = { 1, 0 };
236 /* check what are the separators */
237 memset(is_sep, 0, sizeof(is_sep));
240 is_sep[(unsigned char) *sep_dflt++] = 1;
243 is_sep[(unsigned char) *sep++] = 1;
245 is_sep[0] = 1; /* End of string is also separator */
256 while (!is_sep[(unsigned char) *q]) {
262 topush = xbt_malloc(q - p + 1);
263 memcpy(topush, p, q - p);
264 topush[q - p] = '\0';
265 xbt_dynar_push(res, &topush);
273 * \brief This functions splits a string after using another string as separator
274 * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
275 * \return An array of dynars containing the string tokens
277 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
279 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
288 if (sep[0] == '\0') {
290 xbt_dynar_push(res, &s);
297 //get the start of the first occurence of the substring
299 //if substring was not found add the entire string
302 to_push = malloc(v + 1);
303 memcpy(to_push, p, v);
305 xbt_dynar_push(res, &to_push);
309 to_push = malloc(q - p + 1);
310 memcpy(to_push, p, q - p);
311 //add string terminator
312 to_push[q - p] = '\0';
313 xbt_dynar_push(res, &to_push);
320 /** @brief Splits a string into a dynar of strings, taking quotes into account
322 * It basically does the same argument separation than the shell, where white
323 * spaces can be escaped and where arguments are never splitted within a
325 * Several subsequent spaces are ignored (unless within quotes, of course).
329 xbt_dynar_t xbt_str_split_quoted(const char *s)
331 xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
332 char *str_to_free; /* we have to copy the string before, to handle backslashes */
333 char *beg, *end; /* pointers around the parsed chunk */
334 int in_simple_quote = 0, in_double_quote = 0;
336 int ctn = 0; /* Got something in this block */
340 beg = str_to_free = xbt_strdup(s);
342 /* trim leading spaces */
343 xbt_str_ltrim(beg, " ");
352 /* Protected char; move it closer */
353 memmove(end, end + 1, strlen(end));
355 THROW0(arg_error, 0, "String ends with \\");
356 end++; /* Pass the protected char */
361 if (!in_double_quote) {
362 in_simple_quote = !in_simple_quote;
363 memmove(end, end + 1, strlen(end));
365 /* simple quote protected by double ones */
371 if (!in_simple_quote) {
372 in_double_quote = !in_double_quote;
373 memmove(end, end + 1, strlen(end));
375 /* double quote protected by simple ones */
384 if (*end == '\0' && (in_simple_quote || in_double_quote)) {
386 "End of string found while searching for %c in %s",
387 (in_simple_quote ? '\'' : '"'), s);
389 if (in_simple_quote || in_double_quote) {
393 /* Found a separator. Push the string if contains something */
394 char *topush = xbt_malloc(end - beg + 1);
395 memcpy(topush, beg, end - beg);
396 topush[end - beg] = '\0';
397 xbt_dynar_push(res, &topush);
407 xbt_str_ltrim(beg, " ");
418 xbt_dynar_shrink(res,0);
425 #define mytest(name, input, expected) \
426 xbt_test_add0(name); \
427 d=xbt_str_split_quoted(input); \
428 s=xbt_str_join(d,"XXX"); \
429 xbt_test_assert3(!strcmp(s,expected),\
430 "Input (%s) leads to (%s) instead of (%s)", \
435 XBT_TEST_SUITE("xbt_str", "String Handling");
436 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted,"test the function xbt_str_split_quoted")
441 mytest("Empty", "", "");
442 mytest("Basic test", "toto tutu", "totoXXXtutu");
443 mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
444 mytest("Protected space", "toto\\ tutu", "toto tutu");
445 mytest("Several spaces", "toto tutu", "totoXXXtutu");
446 mytest("LTriming", " toto tatu", "totoXXXtatu");
447 mytest("Triming", " toto tutu ", "totoXXXtutu");
448 mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
449 mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
450 mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
451 mytest("Backslashed quotes", "\\'toto tutu\\' tata",
452 "'totoXXXtutu'XXXtata");
453 mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
454 "toto 'tutuXXXtata");
458 #define mytest_str(name, input, separator, expected) \
459 xbt_test_add0(name); \
460 d=xbt_str_split_str(input, separator); \
461 s=xbt_str_join(d,"XXX"); \
462 xbt_test_assert3(!strcmp(s,expected),\
463 "Input (%s) leads to (%s) instead of (%s)", \
468 XBT_TEST_UNIT("xbt_str_split_str", test_split_str,"test the function xbt_str_split_str")
473 mytest_str("Empty string and separator", "", "", "");
474 mytest_str("Empty string", "", "##", "");
475 mytest_str("Empty separator", "toto", "", "toto");
476 mytest_str("String with no separator in it", "toto", "##", "toto");
477 mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
479 #endif /* SIMGRID_TEST */
481 /** @brief Join a set of strings as a single string */
483 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
485 int len = 1, dyn_len = xbt_dynar_length(dyn);
491 return xbt_strdup("");
493 /* compute the length */
494 xbt_dynar_foreach(dyn, cpt, cursor) {
495 len += strlen(cursor);
497 len += strlen(sep) * dyn_len;
499 res = xbt_malloc(len);
501 xbt_dynar_foreach(dyn, cpt, cursor) {
502 if ((int) cpt < dyn_len - 1)
503 p += sprintf(p, "%s%s", cursor, sep);
505 p += sprintf(p, "%s", cursor);
510 #if defined(SIMGRID_NEED_GETLINE) || defined(DOXYGEN)
511 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
513 * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
515 * getline() reads an entire line from stream, storing the address of the buffer
516 * containing the text into *buf. The buffer is null-terminated and includes
517 * the newline character, if one was found.
519 * If *buf is NULL, then getline() will allocate a buffer for storing the line,
520 * which should be freed by the user program. Alternatively, before calling getline(),
521 * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size. If the buffer
522 * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n
523 * as necessary. In either case, on a successful call, *buf and *n will be updated to
524 * reflect the buffer address and allocated size respectively.
526 long getline(char **buf, size_t * n, FILE * stream)
533 *buf = xbt_malloc(512);
538 return (ssize_t) - 1;
540 for (i = 0; (ch = fgetc(stream)) != EOF; i++) {
543 *buf = xbt_realloc(*buf, *n += 512);
547 if ((*buf)[i] == '\n') {
555 *buf = xbt_realloc(*buf, *n += 1);
562 #endif /* HAVE_GETLINE */
565 * Diff related functions
567 static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db)
569 xbt_matrix_t C = xbt_matrix_new(xbt_dynar_length(da), xbt_dynar_length(db),
573 /* Compute the LCS */
575 C = array(0..m, 0..n)
583 C[i,j] := C[i-1,j-1] + 1
585 C[i,j] := max(C[i,j-1], C[i-1,j])
588 if (xbt_dynar_length(db) != 0)
589 for (i = 0; i < xbt_dynar_length(da); i++)
590 *((int *) xbt_matrix_get_ptr(C, i, 0)) = 0;
592 if (xbt_dynar_length(da) != 0)
593 for (j = 0; j < xbt_dynar_length(db); j++)
594 *((int *) xbt_matrix_get_ptr(C, 0, j)) = 0;
596 for (i = 1; i < xbt_dynar_length(da); i++)
597 for (j = 1; j < xbt_dynar_length(db); j++) {
600 (xbt_dynar_get_as(da, i, char *), xbt_dynar_get_as(db, j, char *)))
601 *((int *) xbt_matrix_get_ptr(C, i, j)) =
602 xbt_matrix_get_as(C, i - 1, j - 1, int) + 1;
604 *((int *) xbt_matrix_get_ptr(C, i, j)) =
605 max(xbt_matrix_get_as(C, i, j - 1, int),
606 xbt_matrix_get_as(C, i - 1, j, int));
611 static void diff_build_diff(xbt_dynar_t res,
613 xbt_dynar_t da, xbt_dynar_t db, int i, int j)
616 /* Construct the diff
617 function printDiff(C[0..m,0..n], X[1..m], Y[1..n], i, j)
618 if i > 0 and j > 0 and X[i] = Y[j]
619 printDiff(C, X, Y, i-1, j-1)
622 if j > 0 and (i = 0 or C[i,j-1] >= C[i-1,j])
623 printDiff(C, X, Y, i, j-1)
625 else if i > 0 and (j = 0 or C[i,j-1] < C[i-1,j])
626 printDiff(C, X, Y, i-1, j)
630 if (i >= 0 && j >= 0 && !strcmp(xbt_dynar_get_as(da, i, char *),
631 xbt_dynar_get_as(db, j, char *))) {
632 diff_build_diff(res, C, da, db, i - 1, j - 1);
633 topush = bprintf(" %s", xbt_dynar_get_as(da, i, char *));
634 xbt_dynar_push(res, &topush);
637 || xbt_matrix_get_as(C, i, j - 1, int) >= xbt_matrix_get_as(C,
643 diff_build_diff(res, C, da, db, i, j - 1);
644 topush = bprintf("+ %s", xbt_dynar_get_as(db, j, char *));
645 xbt_dynar_push(res, &topush);
648 || xbt_matrix_get_as(C, i, j - 1, int) < xbt_matrix_get_as(C,
653 diff_build_diff(res, C, da, db, i - 1, j);
654 topush = bprintf("- %s", xbt_dynar_get_as(da, i, char *));
655 xbt_dynar_push(res, &topush);
656 } else if (i <= 0 && j <= 0) {
659 THROW2(arg_error, 0, "Invalid values: i=%d, j=%d", i, j);
664 /** @brief Compute the unified diff of two strings */
665 char *xbt_str_diff(char *a, char *b)
667 xbt_dynar_t da = xbt_str_split(a, "\n");
668 xbt_dynar_t db = xbt_str_split(b, "\n");
670 xbt_matrix_t C = diff_build_LCS(da, db);
671 xbt_dynar_t diff = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
674 diff_build_diff(diff, C, da, db, xbt_dynar_length(da) - 1,
675 xbt_dynar_length(db) - 1);
676 /* Clean empty lines at the end */
677 while (xbt_dynar_length(diff) > 0) {
679 xbt_dynar_pop(diff, &str);
680 if (str[0] == '\0' || !strcmp(str, " ")) {
683 xbt_dynar_push(diff, &str);
687 res = xbt_str_join(diff, "\n");
691 xbt_dynar_free(&diff);
698 /** @brief creates a new string containing what can be read on a fd
701 char* xbt_str_from_file(FILE *file) {
702 xbt_strbuff_t buff = xbt_strbuff_new();
705 memset(bread,0,1024);
707 while (!feof(file)) {
708 int got = fread(bread, 1, 1023, file);
710 xbt_strbuff_append(buff,bread);
714 xbt_strbuff_free_container(buff);