Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
81f5c1846d2ca099f9db41583ae28eca5aa0cd1d
[simgrid.git] / src / xbt / xbt_str.c
1 /* xbt_str.c - various helping functions to deal with strings               */
2
3 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
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. */
8
9 #include "portable.h"
10 #include "xbt/misc.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 */
15
16 /**  @brief Strip whitespace (or other characters) from the end of a string.
17  *
18  * Strips the whitespaces from the end of s.
19  * By default (when char_list=NULL), these characters get stripped:
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)) NULL.
26  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
27  *
28  * @param s The string to strip. Modified in place.
29  * @param char_list A string which contains the characters you want to strip.
30  *
31  */
32 void xbt_str_rtrim(char *s, const char *char_list)
33 {
34   char *cur = s;
35   const char *__char_list = " \t\n\r\x0B";
36   char white_char[256] = { 1, 0 };
37
38   if (!s)
39     return;
40
41   if (!char_list) {
42     while (*__char_list) {
43       white_char[(unsigned char) *__char_list++] = 1;
44     }
45   } else {
46     while (*char_list) {
47       white_char[(unsigned char) *char_list++] = 1;
48     }
49   }
50
51   while (*cur)
52     ++cur;
53
54   while ((cur >= s) && white_char[(unsigned char) *cur])
55     --cur;
56
57   *++cur = '\0';
58 }
59
60 /**  @brief Strip whitespace (or other characters) from the beginning of a string.
61  *
62  * Strips the whitespaces from the begining of s.
63  * By default (when char_list=NULL), these characters get stripped:
64  *
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.
71  *
72  * @param s The string to strip. Modified in place.
73  * @param char_list A string which contains the characters you want to strip.
74  *
75  */
76 void xbt_str_ltrim(char *s, const char *char_list)
77 {
78   char *cur = s;
79   const char *__char_list = " \t\n\r\x0B";
80   char white_char[256] = { 1, 0 };
81
82   if (!s)
83     return;
84
85   if (!char_list) {
86     while (*__char_list) {
87       white_char[(unsigned char) *__char_list++] = 1;
88     }
89   } else {
90     while (*char_list) {
91       white_char[(unsigned char) *char_list++] = 1;
92     }
93   }
94
95   while (*cur && white_char[(unsigned char) *cur])
96     ++cur;
97
98   memmove(s, cur, strlen(cur) + 1);
99 }
100
101 /**  @brief Strip whitespace (or other characters) from the end and the begining of a string.
102  *
103  * Strips the whitespaces from both the beginning and the end of s.
104  * By default (when char_list=NULL), these characters get stripped:
105  *
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.
112  *
113  * @param s The string to strip.
114  * @param char_list A string which contains the characters you want to strip.
115  *
116  */
117 void xbt_str_trim(char *s, const char *char_list)
118 {
119
120   if (!s)
121     return;
122
123   xbt_str_rtrim(s, char_list);
124   xbt_str_ltrim(s, char_list);
125 }
126
127 /**  @brief Replace double whitespaces (but no other characters) from the string.
128  *
129  * The function modifies the string so that each time that several spaces appear,
130  * they are replaced by a single space. It will only do so for spaces (ASCII 32, 0x20).
131  *
132  * @param s The string to strip. Modified in place.
133  *
134  */
135 void xbt_str_strip_spaces(char *s)
136 {
137   char *p = s;
138   int e = 0;
139
140   if (!s)
141     return;
142
143   while (1) {
144     if (!*p)
145       goto end;
146
147     if (*p != ' ')
148       break;
149
150     p++;
151   }
152
153   e = 1;
154
155   do {
156     if (e)
157       *s++ = *p;
158
159     if (!*++p)
160       goto end;
161
162     if (e ^ (*p != ' '))
163       if ((e = !e))
164         *s++ = ' ';
165   } while (1);
166
167 end:
168   *s = '\0';
169 }
170
171 /** @brief Substitutes a char for another in a string
172  *
173  * @param str the string to modify
174  * @param from char to search
175  * @param to char to put instead
176  * @param occurence number of changes to do (=0 means all)
177  */
178 void xbt_str_subst(char *str, char from, char to, int occurence)
179 {
180   char *p = str;
181   while (*p != '\0') {
182     if (*p == from) {
183       *p = to;
184       if (occurence == 1)
185         return;
186       occurence--;
187     }
188     p++;
189   }
190 }
191
192 /** @brief Replaces a set of variables by their values
193  *
194  * @param str The input of the replacement process
195  * @param patterns The changes to apply
196  * @return The string modified
197  *
198  * Both '$toto' and '${toto}' are valid (and the two writing are equivalent).
199  *
200  * If the variable name contains spaces, use the brace version (ie, ${toto tutu})
201  *
202  * You can provide a default value to use if the variable is not set in the dict by using
203  * '${var:=default}' or '${var:-default}'. These two forms are equivalent, even if they
204  * shouldn't to respect the shell standard (:= form should set the value in the dict,
205  * but does not) (BUG).
206  */
207
208 char *xbt_str_varsubst(const char *str, xbt_dict_t patterns)
209 {
210   xbt_strbuff_t buff = xbt_strbuff_new_from(str);
211   char *res;
212   xbt_strbuff_varsubst(buff, patterns);
213   res = buff->data;
214   xbt_strbuff_free_container(buff);
215   return res;
216 }
217
218
219 /** @brief Splits a string into a dynar of strings
220  *
221  * @param s: the string to split
222  * @param sep: a string of all chars to consider as separator.
223  *
224  * By default (with sep=NULL), these characters are used as separator:
225  *
226  *      - " "           (ASCII 32       (0x20)) space.
227  *      - "\t"          (ASCII 9        (0x09)) tab.
228  *      - "\n"          (ASCII 10       (0x0A)) line feed.
229  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
230  *      - "\0"          (ASCII 0        (0x00)) NULL.
231  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
232  */
233
234 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
235 {
236   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
237   const char *p, *q;
238   int done;
239   const char *sep_dflt = " \t\n\r\x0B";
240   char is_sep[256] = { 1, 0 };
241
242   /* check what are the separators */
243   memset(is_sep, 0, sizeof(is_sep));
244   if (!sep) {
245     while (*sep_dflt)
246       is_sep[(unsigned char) *sep_dflt++] = 1;
247   } else {
248     while (*sep)
249       is_sep[(unsigned char) *sep++] = 1;
250   }
251   is_sep[0] = 1;                /* End of string is also separator */
252
253   /* Do the job */
254   p = q = s;
255   done = 0;
256
257   if (s[0] == '\0')
258     return res;
259
260   while (!done) {
261     char *topush;
262     while (!is_sep[(unsigned char) *q]) {
263       q++;
264     }
265     if (*q == '\0')
266       done = 1;
267
268     topush = xbt_malloc(q - p + 1);
269     memcpy(topush, p, q - p);
270     topush[q - p] = '\0';
271     xbt_dynar_push(res, &topush);
272     p = ++q;
273   }
274
275   return res;
276 }
277
278 /**
279  * \brief This functions splits a string after using another string as separator
280  * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
281  * \return An array of dynars containing the string tokens
282  */
283 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
284 {
285   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
286   int done;
287   const char *p, *q;
288
289   p = q = s;
290   done = 0;
291
292   if (s[0] == '\0')
293     return res;
294   if (sep[0] == '\0') {
295     s = xbt_strdup(s);
296     xbt_dynar_push(res, &s);
297     return res;
298   }
299
300   while (!done) {
301     char *to_push;
302     int v = 0;
303     //get the start of the first occurence of the substring
304     q = strstr(p, sep);
305     //if substring was not found add the entire string
306     if (NULL == q) {
307       v = strlen(p);
308       to_push = malloc(v + 1);
309       memcpy(to_push, p, v);
310       to_push[v] = '\0';
311       xbt_dynar_push(res, &to_push);
312       done = 1;
313     } else {
314       //get the appearance
315       to_push = malloc(q - p + 1);
316       memcpy(to_push, p, q - p);
317       //add string terminator
318       to_push[q - p] = '\0';
319       xbt_dynar_push(res, &to_push);
320       p = q + strlen(sep);
321     }
322   }
323   return res;
324 }
325
326 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
327  *
328  * The string passed as argument must be writable (not const)
329  * The elements of the dynar are just parts of the string passed as argument.
330  *
331  * To free the structure constructed by this function, free the first element and free the dynar:
332  *
333  * free(xbt_dynar_get_ptr(dynar,0));
334  * xbt_dynar_free(&dynar);
335  */
336 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
337   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), NULL);
338   char *beg, *end;              /* pointers around the parsed chunk */
339   int in_simple_quote = 0, in_double_quote = 0;
340   int done = 0;
341   int ctn = 0;                  /* Got something in this block */
342
343   if (s[0] == '\0')
344     return res;
345
346   beg = s;
347
348   /* do not trim leading spaces: caller responsability to clean his cruft */
349   end = beg;
350
351   while (!done) {
352
353
354     switch (*end) {
355     case '\\':
356       ctn = 1;
357       /* Protected char; move it closer */
358       memmove(end, end + 1, strlen(end));
359       if (*end == '\0')
360         THROWF(arg_error, 0, "String ends with \\");
361       end++;                    /* Pass the protected char */
362       break;
363
364     case '\'':
365       ctn = 1;
366       if (!in_double_quote) {
367         in_simple_quote = !in_simple_quote;
368         memmove(end, end + 1, strlen(end));
369       } else {
370         /* simple quote protected by double ones */
371         end++;
372       }
373       break;
374     case '"':
375       ctn = 1;
376       if (!in_simple_quote) {
377         in_double_quote = !in_double_quote;
378         memmove(end, end + 1, strlen(end));
379       } else {
380         /* double quote protected by simple ones */
381         end++;
382       }
383       break;
384
385     case ' ':
386     case '\t':
387     case '\n':
388     case '\0':
389       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
390         THROWF(arg_error, 0,
391                "End of string found while searching for %c in %s",
392                (in_simple_quote ? '\'' : '"'), s);
393       }
394       if (in_simple_quote || in_double_quote) {
395         end++;
396       } else {
397         if (*end == '\0')
398           done = 1;
399
400         *end = '\0';
401         if (ctn) {
402           /* Found a separator. Push the string if contains something */
403           xbt_dynar_push(res, &beg);
404         }
405         ctn = 0;
406
407         if (done)
408           break;
409
410         beg = ++end;
411         /* trim within the string, manually to speed things up */
412         while (*beg == ' ')
413           beg++;
414         end = beg;
415       }
416       break;
417
418     default:
419       ctn = 1;
420       end++;
421     }
422   }
423   return res;
424 }
425
426 /** @brief Splits a string into a dynar of strings, taking quotes into account
427  *
428  * It basically does the same argument separation than the shell, where white
429  * spaces can be escaped and where arguments are never split within a
430  * quote group.
431  * Several subsequent spaces are ignored (unless within quotes, of course).
432  * You may want to trim the input string, if you want to avoid empty entries
433  *
434  */
435
436 xbt_dynar_t xbt_str_split_quoted(const char *s)
437 {
438   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
439   xbt_dynar_t parsed;
440   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
441   unsigned int cursor;
442   char *p;
443
444   if (s[0] == '\0')
445     return res;
446   str_to_free = xbt_strdup(s);
447
448   parsed = xbt_str_split_quoted_in_place(str_to_free);
449   xbt_dynar_foreach(parsed,cursor,p) {
450     char *q=xbt_strdup(p);
451     xbt_dynar_push(res,&q);
452   }
453   free(str_to_free);
454   xbt_dynar_shrink(res, 0);
455   xbt_dynar_free(&parsed);
456   return res;
457 }
458
459 /** @brief Join a set of strings as a single string */
460 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
461 {
462   int len = 1, dyn_len = xbt_dynar_length(dyn);
463   unsigned int cpt;
464   char *cursor;
465   char *res, *p;
466
467   if (!dyn_len)
468     return xbt_strdup("");
469
470   /* compute the length */
471   xbt_dynar_foreach(dyn, cpt, cursor) {
472     len += strlen(cursor);
473   }
474   len += strlen(sep) * dyn_len;
475   /* Do the job */
476   res = xbt_malloc(len);
477   p = res;
478   xbt_dynar_foreach(dyn, cpt, cursor) {
479     if ((int) cpt < dyn_len - 1)
480       p += sprintf(p, "%s%s", cursor, sep);
481     else
482       p += sprintf(p, "%s", cursor);
483   }
484   return res;
485 }
486 /** @brief Join a set of strings as a single string
487  *
488  * The parameter must be a NULL-terminated array of chars,
489  * just like xbt_dynar_to_array() produces
490  */
491 char *xbt_str_join_array(const char *const *strs, const char *sep)
492 {
493   char *res,*q;
494   int amount_strings=0;
495   int len=0;
496   int i;
497
498   if ((!strs) || (!strs[0]))
499     return xbt_strdup("");
500
501   /* compute the length before malloc */
502   for (i=0;strs[i];i++) {
503     len += strlen(strs[i]);
504     amount_strings++;
505   }
506   len += strlen(sep) * amount_strings;
507
508   /* Do the job */
509   q = res = xbt_malloc(len);
510   for (i=0;strs[i];i++) {
511     if (i!=0) { // not first loop
512       q += sprintf(q, "%s%s", sep, strs[i]);
513     } else {
514       q += sprintf(q,"%s",strs[i]);
515     }
516   }
517   return res;
518 }
519
520 #if defined(SIMGRID_NEED_GETLINE) || defined(DOXYGEN)
521 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
522  *
523  * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
524  *
525  * getline() reads an entire line from stream, storing the address of the buffer
526  * containing the text into *buf.  The buffer is null-terminated and includes
527  * the newline character, if one was found.
528  *
529  * If *buf is NULL, then getline() will allocate a buffer for storing the line,
530  * which should be freed by the user program.  Alternatively, before calling getline(),
531  * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size.  If the buffer
532  * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n
533  * as necessary.  In either case, on a successful call, *buf and *n will be updated to
534  * reflect the buffer address and allocated size respectively.
535  */
536 long getline(char **buf, size_t * n, FILE * stream)
537 {
538
539   size_t i;
540   int ch;
541
542   if (!*buf) {
543     *buf = xbt_malloc(512);
544     *n = 512;
545   }
546
547   if (feof(stream))
548     return (ssize_t) - 1;
549
550   for (i = 0; (ch = fgetc(stream)) != EOF; i++) {
551
552     if (i >= (*n) + 1)
553       *buf = xbt_realloc(*buf, *n += 512);
554
555     (*buf)[i] = ch;
556
557     if ((*buf)[i] == '\n') {
558       i++;
559       (*buf)[i] = '\0';
560       break;
561     }
562   }
563
564   if (i == *n)
565     *buf = xbt_realloc(*buf, *n += 1);
566
567   (*buf)[i] = '\0';
568
569   return (ssize_t) i;
570 }
571
572 #endif                          /* HAVE_GETLINE */
573
574 /*
575  * Diff related functions
576  *
577  * Implementation of the algorithm described in "An O(NP) Sequence
578  * Comparison Algorithm", by Sun Wu, Udi Manber, Gene Myers, and Webb
579  * Miller.
580  */
581
582 struct subsequence {
583     int x, y;                   /* starting coordinates */
584     int len;                    /* length */
585 };
586
587 static XBT_INLINE
588 void diff_snake(const xbt_dynar_t da, int a0, int len_a,
589                 const xbt_dynar_t db, int b0, int len_b,
590                 struct subsequence *seqs, int *fp, int k, int limit)
591 {
592   int record_seq;
593   int x, y;
594   int fp_left = fp[k - 1] + 1;
595   int fp_right = fp[k + 1];
596   if (fp_left > fp_right) {
597     x = fp_left;
598     record_seq = k - 1;
599   } else {
600     x = fp_right;
601     record_seq = k + 1;
602   }
603   y = x - k;
604   if (x + y <= limit) {
605     seqs[k].x = x;
606     seqs[k].y = y;
607     record_seq = k;
608   } else {
609     seqs[k] = seqs[record_seq];
610   }
611   while (x < len_a && y < len_b && !strcmp(xbt_dynar_get_as(da, a0 + x, char*),
612                                            xbt_dynar_get_as(db, b0 + y, char*)))
613     ++x, ++y;
614   fp[k] = x;
615   if (record_seq == k)
616     seqs[k].len = x - seqs[k].x;
617 }
618
619 /* Returns the length of a shortest edit script, and a common
620  * subsequence from the middle.
621  */
622 static int diff_middle_subsequence(const xbt_dynar_t da, int a0,  int len_a,
623                                    const xbt_dynar_t db, int b0,  int len_b,
624                                    struct subsequence *subseq,
625                                    struct subsequence *seqs, int *fp)
626 {
627   const int delta = len_a - len_b;
628   const int limit = (len_a + len_b) / 2;
629   int kmin;
630   int kmax;
631   int k;
632   int p = -1;
633
634   if (delta >= 0) {
635     kmin = 0;
636     kmax = delta;
637   } else {
638     kmin = delta;
639     kmax = 0;
640   }
641   for (k = kmin; k <= kmax; k++)
642     fp[k] = -1;
643   do {
644     p++;
645     fp[kmin - p - 1] = fp[kmax + p + 1] = -1;
646     for (k = kmax + p; k > delta; k--)
647       diff_snake(da, a0, len_a, db, b0, len_b, seqs, fp, k, limit);
648     for (k = kmin - p; k <= delta; k++)
649       diff_snake(da, a0, len_a, db, b0, len_b, seqs, fp, k, limit);
650   } while (fp[delta] != len_a);
651
652   subseq->x = a0 + seqs[delta].x;
653   subseq->y = b0 + seqs[delta].y;
654   subseq->len = seqs[delta].len;
655   return abs(delta) + 2 * p;;
656 }
657
658 /* Finds a longest common subsequence.
659  */
660 static void diff_compute_lcs(const xbt_dynar_t da, int a0, int len_a,
661                              const xbt_dynar_t db, int b0, int len_b,
662                              xbt_dynar_t common_sequence,
663                              struct subsequence *seqs, int *fp)
664 {
665   if (len_a > 0 && len_b > 0) {
666     struct subsequence subseq;
667     int ses_len = diff_middle_subsequence(da, a0, len_a, db, b0, len_b,
668                                           &subseq, seqs, fp);
669     if (ses_len > 1) {
670       int u = subseq.x + subseq.len;
671       int v = subseq.y + subseq.len;
672       diff_compute_lcs(da, a0, subseq.x - a0, db, b0, subseq.y - b0,
673                        common_sequence, seqs, fp);
674       if (subseq.len > 0)
675         xbt_dynar_push(common_sequence, &subseq);
676       diff_compute_lcs(da, u, a0 + len_a - u, db, v, b0 + len_b - v,
677                        common_sequence, seqs, fp);
678     } else {
679       int len = MIN(len_a, len_b) - subseq.len;
680       if (subseq.x == a0 && subseq.y == b0) {
681         if (subseq.len > 0)
682           xbt_dynar_push(common_sequence, &subseq);
683         if (len > 0) {
684           struct subsequence subseq0 = {a0 + len_a - len,
685                                         b0 + len_b - len, len};
686           xbt_dynar_push(common_sequence, &subseq0);
687         }
688       } else {
689         if (len > 0) {
690           struct subsequence subseq0 = {a0, b0, len};
691           xbt_dynar_push(common_sequence, &subseq0);
692         }
693         if (subseq.len > 0)
694           xbt_dynar_push(common_sequence, &subseq);
695       }
696     }
697   }
698 }
699
700 static int diff_member(const char *s, xbt_dynar_t d, int from, int to)
701 {
702   for ( ; from < to ; from++)
703     if (!strcmp(s, xbt_dynar_get_as(d, from, char *)))
704       return 1;
705   return 0;
706 }
707
708 /* Extract common prefix.
709  */
710 static void diff_easy_prefix(const xbt_dynar_t da, int *a0_p, int *len_a_p,
711                              const xbt_dynar_t db, int *b0_p, int *len_b_p,
712                              xbt_dynar_t common_sequence)
713 {
714   int a0 = *a0_p;
715   int b0 = *b0_p;
716   int len_a = *len_a_p;
717   int len_b = *len_b_p;
718
719   while (len_a > 0 && len_b > 0) {
720     struct subsequence subseq = {a0, b0, 0};
721     while (len_a > 0 && len_b > 0 && !strcmp(xbt_dynar_get_as(da, a0, char*),
722                                              xbt_dynar_get_as(db, b0, char*))) {
723       a0++, len_a--;
724       b0++, len_b--;
725       subseq.len++;
726     }
727     if (subseq.len > 0)
728       xbt_dynar_push(common_sequence, &subseq);
729     if (len_a > 0 && len_b > 0 &&
730         !diff_member(xbt_dynar_get_as(da, a0, char*),
731                      db, b0 + 1, b0 + len_b)) {
732       a0++, len_a--;
733     } else {
734       break;
735     }
736   }
737
738   *a0_p = a0;
739   *b0_p = b0;
740   *len_a_p = len_a;
741   *len_b_p = len_b;
742 }
743
744 /* Extract common suffix.
745  */
746 static void diff_easy_suffix(const xbt_dynar_t da, int *a0_p, int *len_a_p,
747                              const xbt_dynar_t db, int *b0_p, int *len_b_p,
748                              xbt_dynar_t common_suffix)
749 {
750   int a0 = *a0_p;
751   int b0 = *b0_p;
752   int len_a = *len_a_p;
753   int len_b = *len_b_p;
754
755   while (len_a > 0 && len_b > 0){
756     struct subsequence subseq;
757     subseq.len = 0;
758     while (len_a > 0 && len_b > 0 &&
759            !strcmp(xbt_dynar_get_as(da, a0 + len_a - 1, char*),
760                    xbt_dynar_get_as(db, b0 + len_b - 1, char*))) {
761       len_a--;
762       len_b--;
763       subseq.len++;
764     }
765     if (subseq.len > 0) {
766       subseq.x = a0 + len_a;
767       subseq.y = b0 + len_b;
768       xbt_dynar_push(common_suffix, &subseq);
769     }
770     if (len_a > 0 && len_b > 0 &&
771         !diff_member(xbt_dynar_get_as(db, b0 + len_b - 1, char*),
772                      da, a0, a0 + len_a - 1)) {
773       len_b--;
774     } else {
775       break;
776     }
777   }
778
779   *a0_p = a0;
780   *b0_p = b0;
781   *len_a_p = len_a;
782   *len_b_p = len_b;
783 }
784
785 /** @brief Compute the unified diff of two strings */
786 char *xbt_str_diff(const char *a, const char *b)
787 {
788   xbt_dynar_t da = xbt_str_split(a, "\n");
789   xbt_dynar_t db = xbt_str_split(b, "\n");
790   xbt_dynar_t common_sequence, common_suffix;
791   size_t len;
792   int a0, b0;
793   int len_a, len_b;
794   int max;
795   int *fp_base, *fp;
796   struct subsequence *seqs_base, *seqs;
797   struct subsequence subseq;
798   xbt_dynar_t diff;
799   char *res;
800   int x, y;
801   unsigned s;
802
803   /* Clean empty lines at the end of da and db */
804   len = strlen(a);
805   if (len > 0 && a[len - 1] == '\n')
806     xbt_dynar_pop(da, NULL);
807   len = strlen(b);
808   if (len > 0 && b[len - 1] == '\n')
809     xbt_dynar_pop(db, NULL);
810
811   /* Various initializations */
812   a0 = 0;
813   len_a = xbt_dynar_length(da);
814   b0 = 0;
815   len_b = xbt_dynar_length(db);
816   max = MAX(len_a, len_b) + 1;
817   fp_base = xbt_new(int, 2 * max + 1);
818   fp = fp_base + max;           /* indexes in [-max..max] */
819   seqs_base = xbt_new(struct subsequence, 2 * max + 1);
820   seqs = seqs_base + max;       /* indexes in [-max..max] */
821   common_sequence = xbt_dynar_new(sizeof(struct subsequence), NULL);
822   common_suffix = xbt_dynar_new(sizeof(struct subsequence), NULL);
823
824   /* Add a sentinel a the end of the sequence */
825   subseq.x = len_a;
826   subseq.y = len_b;
827   subseq.len = 0;
828   xbt_dynar_push(common_suffix, &subseq);
829
830   /* Compute the Longest Common Subsequence */
831   diff_easy_prefix(da, &a0, &len_a, db, &b0, &len_b, common_sequence);
832   diff_easy_suffix(da, &a0, &len_a, db, &b0, &len_b, common_suffix);
833   diff_compute_lcs(da, a0, len_a, db, b0, len_b, common_sequence, seqs, fp);
834   while (!xbt_dynar_is_empty(common_suffix)) {
835     xbt_dynar_pop(common_suffix, &subseq);
836     xbt_dynar_push(common_sequence, &subseq);
837   }
838
839   /* Build a Shortest Edit Script, and the final result */
840   diff = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
841   x = 0;
842   y = 0;
843   xbt_dynar_foreach(common_sequence, s, subseq) {
844     while (x < subseq.x) {
845       char *topush = bprintf("- %s", xbt_dynar_get_as(da, x++, char*));
846       xbt_dynar_push_as(diff, char*, topush);
847     }
848     while (y < subseq.y) {
849       char *topush = bprintf("+ %s", xbt_dynar_get_as(db, y++, char*));
850       xbt_dynar_push_as(diff, char*, topush);
851     }
852     while (x < subseq.x + subseq.len) {
853       char *topush = bprintf("  %s", xbt_dynar_get_as(da, x++, char*));
854       xbt_dynar_push_as(diff, char*, topush);
855       y++;
856     }
857   }
858   res = xbt_str_join(diff, "\n");
859
860   xbt_free(fp_base);
861   xbt_free(seqs_base);
862   xbt_dynar_free(&db);
863   xbt_dynar_free(&da);
864   xbt_dynar_free(&common_sequence);
865   xbt_dynar_free(&common_suffix);
866   xbt_dynar_free(&diff);
867
868   return res;
869 }
870
871
872 /** @brief creates a new string containing what can be read on a fd
873  *
874  */
875 char *xbt_str_from_file(FILE * file)
876 {
877   xbt_strbuff_t buff = xbt_strbuff_new();
878   char *res;
879   char bread[1024];
880   memset(bread, 0, 1024);
881
882   while (!feof(file)) {
883     int got = fread(bread, 1, 1023, file);
884     bread[got] = '\0';
885     xbt_strbuff_append(buff, bread);
886   }
887
888   res = buff->data;
889   xbt_strbuff_free_container(buff);
890   return res;
891 }
892
893 #ifdef SIMGRID_TEST
894 #include "xbt/str.h"
895
896 #define mytest(name, input, expected) \
897   xbt_test_add(name); \
898   d=xbt_str_split_quoted(input); \
899   s=xbt_str_join(d,"XXX"); \
900   xbt_test_assert(!strcmp(s,expected),\
901                    "Input (%s) leads to (%s) instead of (%s)", \
902                    input,s,expected);\
903                    free(s); \
904                    xbt_dynar_free(&d);
905
906 XBT_TEST_SUITE("xbt_str", "String Handling");
907 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
908 {
909   xbt_dynar_t d;
910   char *s;
911
912   mytest("Empty", "", "");
913   mytest("Basic test", "toto tutu", "totoXXXtutu");
914   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u",
915          "totoXXXtutu");
916   mytest("Protected space", "toto\\ tutu", "toto tutu");
917   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
918   mytest("LTriming", "  toto tatu", "totoXXXtatu");
919   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
920   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
921   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
922   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
923   mytest("Backslashed quotes", "\\'toto tutu\\' tata",
924          "'totoXXXtutu'XXXtata");
925   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
926          "toto 'tutuXXXtata");
927
928 }
929
930 #define mytest_str(name, input, separator, expected) \
931   xbt_test_add(name); \
932   d=xbt_str_split_str(input, separator); \
933   s=xbt_str_join(d,"XXX"); \
934   xbt_test_assert(!strcmp(s,expected),\
935                    "Input (%s) leads to (%s) instead of (%s)", \
936                    input,s,expected);\
937                    free(s); \
938                    xbt_dynar_free(&d);
939
940 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
941 {
942   xbt_dynar_t d;
943   char *s;
944
945   mytest_str("Empty string and separator", "", "", "");
946   mytest_str("Empty string", "", "##", "");
947   mytest_str("Empty separator", "toto", "", "toto");
948   mytest_str("String with no separator in it", "toto", "##", "toto");
949   mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
950 }
951
952 /* Last args are format string and parameters for xbt_test_add */
953 #define mytest_diff(s1, s2, diff, ...)                                  \
954   do {                                                                  \
955     char *mytest_diff_res;                                              \
956     xbt_test_add(__VA_ARGS__);                                          \
957     mytest_diff_res = xbt_str_diff(s1, s2);                             \
958     xbt_test_assert(!strcmp(mytest_diff_res, diff),                     \
959                     "Wrong output:\n--- got:\n%s\n--- expected:\n%s\n---", \
960                     mytest_diff_res, diff);                             \
961     free(mytest_diff_res);                                              \
962   } while (0)
963
964 XBT_TEST_UNIT("xbt_str_diff", test_diff, "test the function xbt_str_diff")
965 {
966   unsigned i;
967
968   /* Trivial cases */
969   mytest_diff("a", "a", "  a", "1 word, no difference");
970   mytest_diff("a", "A", "- a\n+ A", "1 word, different");
971   mytest_diff("a\n", "a\n", "  a", "1 line, no difference");
972   mytest_diff("a\n", "A\n", "- a\n+ A", "1 line, different");
973
974   /* Empty strings */
975   mytest_diff("", "", "", "empty strings");
976   mytest_diff("", "a", "+ a", "1 word, added");
977   mytest_diff("a", "", "- a", "1 word, removed");
978   mytest_diff("", "a\n", "+ a", "1 line, added");
979   mytest_diff("a\n", "", "- a", "1 line, removed");
980   mytest_diff("", "a\nb\nc\n", "+ a\n+ b\n+ c", "4 lines, all added");
981   mytest_diff("a\nb\nc\n", "", "- a\n- b\n- c", "4 lines, all removed");
982
983   /* Empty lines */
984   mytest_diff("\n", "\n", "  ", "empty lines");
985   mytest_diff("", "\n", "+ ", "empty line, added");
986   mytest_diff("\n", "", "- ", "empty line, removed");
987
988   mytest_diff("a", "\na", "+ \n  a", "empty line added before word");
989   mytest_diff("a", "a\n\n", "  a\n+ ", "empty line added after word");
990   mytest_diff("\na", "a", "- \n  a", "empty line removed before word");
991   mytest_diff("a\n\n", "a", "  a\n- ", "empty line removed after word");
992
993   mytest_diff("a\n", "\na\n", "+ \n  a", "empty line added before line");
994   mytest_diff("a\n", "a\n\n", "  a\n+ ", "empty line added after line");
995   mytest_diff("\na\n", "a\n", "- \n  a", "empty line removed before line");
996   mytest_diff("a\n\n", "a\n", "  a\n- ", "empty line removed after line");
997
998   mytest_diff("a\nb\nc\nd\n", "\na\nb\nc\nd\n", "+ \n  a\n  b\n  c\n  d",
999               "empty line added before 4 lines");
1000   mytest_diff("a\nb\nc\nd\n", "a\nb\nc\nd\n\n", "  a\n  b\n  c\n  d\n+ ",
1001               "empty line added after 4 lines");
1002   mytest_diff("\na\nb\nc\nd\n", "a\nb\nc\nd\n", "- \n  a\n  b\n  c\n  d",
1003               "empty line removed before 4 lines");
1004   mytest_diff("a\nb\nc\nd\n\n", "a\nb\nc\nd\n", "  a\n  b\n  c\n  d\n- ",
1005               "empty line removed after 4 lines");
1006
1007   /* Missing newline at the end of one of the strings */
1008   mytest_diff("a\n", "a", "  a", "1 line, 1 word, no difference");
1009   mytest_diff("a", "a\n", "  a", "1 word, 1 line, no difference");
1010   mytest_diff("a\n", "A", "- a\n+ A", "1 line, 1 word, different");
1011   mytest_diff("a", "A\n", "- a\n+ A", "1 word, 1 line, different");
1012
1013   mytest_diff("a\nb\nc\nd", "a\nb\nc\nd\n", "  a\n  b\n  c\n  d",
1014               "4 lines, no newline on first");
1015   mytest_diff("a\nb\nc\nd\n", "a\nb\nc\nd", "  a\n  b\n  c\n  d",
1016               "4 lines, no newline on second");
1017
1018   /* Four lines, all combinations of differences */
1019   for (i = 0 ; i < (1U << 4) ; i++) {
1020     char d2[4 + 1];
1021     char s2[4 * 2 + 1];
1022     char res[4 * 8 + 1];
1023     char *pd = d2;
1024     char *ps = s2;
1025     char *pr = res;
1026     unsigned j = 0;
1027     while (j < 4) {
1028       unsigned k;
1029       for (/* j */ ; j < 4 && !(i & (1U << j)) ; j++) {
1030         *pd++ = "abcd"[j];
1031         ps += sprintf(ps, "%c\n", "abcd"[j]);
1032         pr += sprintf(pr, "  %c\n", "abcd"[j]);
1033       }
1034       for (k = j ; k < 4 && (i & (1U << k)) ; k++) {
1035         *pd++ = "ABCD"[k];
1036         ps += sprintf(ps, "%c\n", "ABCD"[k]);
1037         pr += sprintf(pr, "- %c\n", "abcd"[k]);
1038       }
1039       for (/* j */ ; j < k ; j++) {
1040         pr += sprintf(pr, "+ %c\n", "ABCD"[j]);
1041       }
1042     }
1043     *pd = '\0';
1044     *--pr = '\0';               /* strip last '\n' from expected result */
1045     mytest_diff("a\nb\nc\nd\n", s2, res,
1046                 "compare (abcd) with changed (%s)", d2);
1047   }
1048
1049   /* Subsets of four lines, do not test for empty subset */
1050   for (i = 1 ; i < (1U << 4) ; i++) {
1051     char d2[4 + 1];
1052     char s2[4 * 2 + 1];
1053     char res[4 * 8 + 1];
1054     char *pd = d2;
1055     char *ps = s2;
1056     char *pr = res;
1057     unsigned j = 0;
1058     while (j < 4) {
1059       for (/* j */ ; j < 4 && (i & (1U << j)) ; j++) {
1060         *pd++ = "abcd"[j];
1061         ps += sprintf(ps, "%c\n", "abcd"[j]);
1062         pr += sprintf(pr, "  %c\n", "abcd"[j]);
1063       }
1064       for (/* j */; j < 4 && !(i & (1U << j)) ; j++) {
1065         pr += sprintf(pr, "- %c\n", "abcd"[j]);
1066       }
1067     }
1068     *pd = '\0';
1069     *--pr = '\0';               /* strip last '\n' from expected result */
1070     mytest_diff("a\nb\nc\nd\n", s2, res,
1071                 "compare (abcd) with subset (%s)", d2);
1072
1073     for (pr = res ; *pr != '\0' ; pr++)
1074       if (*pr == '-')
1075         *pr = '+';
1076     mytest_diff(s2, "a\nb\nc\nd\n", res,
1077                 "compare subset (%s) with (abcd)", d2);
1078   }
1079 }
1080
1081 #endif                          /* SIMGRID_TEST */