Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge pull request #1 from mquinson/master
[simgrid.git] / src / xbt / xbt_str.c
1 /* xbt_str.c - various helping functions to deal with strings               */
2
3 /* Copyright (c) 2007-2014. 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 "src/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 = xbt_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 = xbt_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  * So if you don't store that argument elsewhere, you should free it in addition
331  * to freeing the dynar. This can be done by simply freeing the first argument
332  * of the dynar:
333  *  free(xbt_dynar_get_ptr(dynar,0));
334  *
335  * Actually this function puts a bunch of \0 in the memory area you passed as
336  * argument to separate the elements, and pushes the address of each chunk
337  * in the resulting dynar. Yes, that's uneven. Yes, that's gory. But that's efficient.
338  */
339 xbt_dynar_t xbt_str_split_quoted_in_place(char *s) {
340   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), NULL);
341   char *beg, *end;              /* pointers around the parsed chunk */
342   int in_simple_quote = 0, in_double_quote = 0;
343   int done = 0;
344   int ctn = 0;                  /* Got something in this block */
345
346   if (s[0] == '\0')
347     return res;
348
349   beg = s;
350
351   /* do not trim leading spaces: caller responsibility to clean his cruft */
352   end = beg;
353
354   while (!done) {
355
356
357     switch (*end) {
358     case '\\':
359       ctn = 1;
360       /* Protected char; move it closer */
361       memmove(end, end + 1, strlen(end));
362       if (*end == '\0')
363         THROWF(arg_error, 0, "String ends with \\");
364       end++;                    /* Pass the protected char */
365       break;
366
367     case '\'':
368       ctn = 1;
369       if (!in_double_quote) {
370         in_simple_quote = !in_simple_quote;
371         memmove(end, end + 1, strlen(end));
372       } else {
373         /* simple quote protected by double ones */
374         end++;
375       }
376       break;
377     case '"':
378       ctn = 1;
379       if (!in_simple_quote) {
380         in_double_quote = !in_double_quote;
381         memmove(end, end + 1, strlen(end));
382       } else {
383         /* double quote protected by simple ones */
384         end++;
385       }
386       break;
387
388     case ' ':
389     case '\t':
390     case '\n':
391     case '\0':
392       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
393         THROWF(arg_error, 0,
394                "End of string found while searching for %c in %s",
395                (in_simple_quote ? '\'' : '"'), s);
396       }
397       if (in_simple_quote || in_double_quote) {
398         end++;
399       } else {
400         if (*end == '\0')
401           done = 1;
402
403         *end = '\0';
404         if (ctn) {
405           /* Found a separator. Push the string if contains something */
406           xbt_dynar_push(res, &beg);
407         }
408         ctn = 0;
409
410         if (done)
411           break;
412
413         beg = ++end;
414         /* trim within the string, manually to speed things up */
415         while (*beg == ' ')
416           beg++;
417         end = beg;
418       }
419       break;
420
421     default:
422       ctn = 1;
423       end++;
424     }
425   }
426   return res;
427 }
428
429 /** @brief Splits a string into a dynar of strings, taking quotes into account
430  *
431  * It basically does the same argument separation than the shell, where white
432  * spaces can be escaped and where arguments are never split within a
433  * quote group.
434  * Several subsequent spaces are ignored (unless within quotes, of course).
435  * You may want to trim the input string, if you want to avoid empty entries
436  *
437  */
438
439 xbt_dynar_t xbt_str_split_quoted(const char *s)
440 {
441   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
442   xbt_dynar_t parsed;
443   char *str_to_free;            /* we have to copy the string before, to handle backslashes */
444   unsigned int cursor;
445   char *p;
446
447   if (s[0] == '\0')
448     return res;
449   str_to_free = xbt_strdup(s);
450
451   parsed = xbt_str_split_quoted_in_place(str_to_free);
452   xbt_dynar_foreach(parsed,cursor,p) {
453     char *q=xbt_strdup(p);
454     xbt_dynar_push(res,&q);
455   }
456   free(str_to_free);
457   xbt_dynar_shrink(res, 0);
458   xbt_dynar_free(&parsed);
459   return res;
460 }
461
462 /** @brief Join a set of strings as a single string */
463 char *xbt_str_join(xbt_dynar_t dyn, const char *sep)
464 {
465   int len = 1, dyn_len = xbt_dynar_length(dyn);
466   unsigned int cpt;
467   char *cursor;
468   char *res, *p;
469
470   if (!dyn_len)
471     return xbt_strdup("");
472
473   /* compute the length */
474   xbt_dynar_foreach(dyn, cpt, cursor) {
475     len += strlen(cursor);
476   }
477   len += strlen(sep) * dyn_len;
478   /* Do the job */
479   res = xbt_malloc(len);
480   p = res;
481   xbt_dynar_foreach(dyn, cpt, cursor) {
482     if ((int) cpt < dyn_len - 1)
483       p += sprintf(p, "%s%s", cursor, sep);
484     else
485       p += sprintf(p, "%s", cursor);
486   }
487   return res;
488 }
489 /** @brief Join a set of strings as a single string
490  *
491  * The parameter must be a NULL-terminated array of chars,
492  * just like xbt_dynar_to_array() produces
493  */
494 char *xbt_str_join_array(const char *const *strs, const char *sep)
495 {
496   char *res,*q;
497   int amount_strings=0;
498   int len=0;
499   int i;
500
501   if ((!strs) || (!strs[0]))
502     return xbt_strdup("");
503
504   /* compute the length before malloc */
505   for (i=0;strs[i];i++) {
506     len += strlen(strs[i]);
507     amount_strings++;
508   }
509   len += strlen(sep) * amount_strings;
510
511   /* Do the job */
512   q = res = xbt_malloc(len);
513   for (i=0;strs[i];i++) {
514     if (i!=0) { // not first loop
515       q += sprintf(q, "%s%s", sep, strs[i]);
516     } else {
517       q += sprintf(q,"%s",strs[i]);
518     }
519   }
520   return res;
521 }
522
523 /*
524  * Diff related functions
525  *
526  * Implementation of the algorithm described in "An O(NP) Sequence Comparison
527  * Algorithm", by Sun Wu, Udi Manber, Gene Myers, and Webb Miller (Information
528  * Processing Letters 35(6):317-323, 1990), with the linear-space
529  * divide-and-conquer strategy described in "An O(ND) Difference Algorithm and
530  * Its Variations", by Eugene W. Myers (Algorithmica 1:251-266, 1986).
531  */
532
533 struct subsequence {
534     int x, y;                   /* starting coordinates */
535     int len;                    /* length */
536 };
537
538 static XBT_INLINE
539 void diff_snake(const char *vec_a[], int a0, int len_a,
540                 const char *vec_b[], int b0, int len_b,
541                 struct subsequence *seqs, int *fp, int k, int limit)
542 {
543   int record_seq;
544   int x, y;
545   int fp_left = fp[k - 1] + 1;
546   int fp_right = fp[k + 1];
547   if (fp_left > fp_right) {
548     x = fp_left;
549     record_seq = k - 1;
550   } else {
551     x = fp_right;
552     record_seq = k + 1;
553   }
554   y = x - k;
555   if (x + y <= limit) {
556     seqs[k].x = x;
557     seqs[k].y = y;
558     record_seq = k;
559   } else {
560     seqs[k] = seqs[record_seq];
561   }
562   while (x < len_a && y < len_b && !strcmp(vec_a[a0 + x], vec_b[b0 + y]))
563     ++x, ++y;
564   fp[k] = x;
565   if (record_seq == k)
566     seqs[k].len = x - seqs[k].x;
567 }
568
569 /* Returns the length of a shortest edit script, and a common
570  * subsequence from the middle.
571  */
572 static int diff_middle_subsequence(const char *vec_a[], int a0,  int len_a,
573                                    const char *vec_b[], int b0,  int len_b,
574                                    struct subsequence *subseq,
575                                    struct subsequence *seqs, int *fp)
576 {
577   const int delta = len_a - len_b;
578   const int limit = (len_a + len_b) / 2;
579   int kmin;
580   int kmax;
581   int k;
582   int p = -1;
583
584   if (delta >= 0) {
585     kmin = 0;
586     kmax = delta;
587   } else {
588     kmin = delta;
589     kmax = 0;
590   }
591   for (k = kmin; k <= kmax; k++)
592     fp[k] = -1;
593   do {
594     p++;
595     fp[kmin - p - 1] = fp[kmax + p + 1] = -1;
596     for (k = kmax + p; k > delta; k--)
597       diff_snake(vec_a, a0, len_a, vec_b, b0, len_b, seqs, fp, k, limit);
598     for (k = kmin - p; k <= delta; k++)
599       diff_snake(vec_a, a0, len_a, vec_b, b0, len_b, seqs, fp, k, limit);
600   } while (fp[delta] != len_a);
601
602   subseq->x = a0 + seqs[delta].x;
603   subseq->y = b0 + seqs[delta].y;
604   subseq->len = seqs[delta].len;
605   return abs(delta) + 2 * p;;
606 }
607
608 /* Finds a longest common subsequence.
609  * Returns its length.
610  */
611 static int diff_compute_lcs(const char *vec_a[], int a0, int len_a,
612                             const char *vec_b[], int b0, int len_b,
613                             xbt_dynar_t common_sequence,
614                             struct subsequence *seqs, int *fp)
615 {
616   if (len_a > 0 && len_b > 0) {
617     struct subsequence subseq;
618     int ses_len = diff_middle_subsequence(vec_a, a0, len_a, vec_b, b0, len_b,
619                                           &subseq, seqs, fp);
620     int lcs_len = (len_a + len_b - ses_len) / 2;
621     if (lcs_len == 0) {
622       return 0;
623     } else if (ses_len > 1) {
624       int lcs_len1 = subseq.len;
625       if (lcs_len1 < lcs_len)
626         lcs_len1 += diff_compute_lcs(vec_a, a0, subseq.x - a0,
627                                      vec_b, b0, subseq.y - b0,
628                                      common_sequence, seqs, fp);
629       if (subseq.len > 0)
630         xbt_dynar_push(common_sequence, &subseq);
631       if (lcs_len1 < lcs_len) {
632         int u = subseq.x + subseq.len;
633         int v = subseq.y + subseq.len;
634         diff_compute_lcs(vec_a, u, a0 + len_a - u, vec_b, v, b0 + len_b - v,
635                          common_sequence, seqs, fp);
636       }
637     } else {
638       int len = MIN(len_a, len_b) - subseq.len;
639       if (subseq.x == a0 && subseq.y == b0) {
640         if (subseq.len > 0)
641           xbt_dynar_push(common_sequence, &subseq);
642         if (len > 0) {
643           struct subsequence subseq0 = {a0 + len_a - len,
644                                         b0 + len_b - len, len};
645           xbt_dynar_push(common_sequence, &subseq0);
646         }
647       } else {
648         if (len > 0) {
649           struct subsequence subseq0 = {a0, b0, len};
650           xbt_dynar_push(common_sequence, &subseq0);
651         }
652         if (subseq.len > 0)
653           xbt_dynar_push(common_sequence, &subseq);
654       }
655     }
656     return lcs_len;
657   } else {
658     return 0;
659   }
660 }
661
662 static int diff_member(const char *s, const char *vec[], int from, int to)
663 {
664   for ( ; from < to ; from++)
665     if (!strcmp(s, vec[from]))
666       return 1;
667   return 0;
668 }
669
670 /* Extract common prefix.
671  */
672 static void diff_easy_prefix(const char *vec_a[], int *a0_p, int *len_a_p,
673                              const char *vec_b[], int *b0_p, int *len_b_p,
674                              xbt_dynar_t common_sequence)
675 {
676   int a0 = *a0_p;
677   int b0 = *b0_p;
678   int len_a = *len_a_p;
679   int len_b = *len_b_p;
680
681   while (len_a > 0 && len_b > 0) {
682     struct subsequence subseq = {a0, b0, 0};
683     while (len_a > 0 && len_b > 0 && !strcmp(vec_a[a0], vec_b[b0])) {
684       a0++, len_a--;
685       b0++, len_b--;
686       subseq.len++;
687     }
688     if (subseq.len > 0)
689       xbt_dynar_push(common_sequence, &subseq);
690     if (len_a > 0 && len_b > 0 &&
691         !diff_member(vec_a[a0], vec_b, b0 + 1, b0 + len_b)) {
692       a0++, len_a--;
693     } else {
694       break;
695     }
696   }
697
698   *a0_p = a0;
699   *b0_p = b0;
700   *len_a_p = len_a;
701   *len_b_p = len_b;
702 }
703
704 /* Extract common suffix.
705  */
706 static void diff_easy_suffix(const char *vec_a[], int *a0_p, int *len_a_p,
707                              const char *vec_b[], int *b0_p, int *len_b_p,
708                              xbt_dynar_t common_suffix)
709 {
710   int a0 = *a0_p;
711   int b0 = *b0_p;
712   int len_a = *len_a_p;
713   int len_b = *len_b_p;
714
715   while (len_a > 0 && len_b > 0){
716     struct subsequence subseq;
717     subseq.len = 0;
718     while (len_a > 0 && len_b > 0 &&
719            !strcmp(vec_a[a0 + len_a - 1], vec_b[b0 + len_b - 1])) {
720       len_a--;
721       len_b--;
722       subseq.len++;
723     }
724     if (subseq.len > 0) {
725       subseq.x = a0 + len_a;
726       subseq.y = b0 + len_b;
727       xbt_dynar_push(common_suffix, &subseq);
728     }
729     if (len_a > 0 && len_b > 0 &&
730         !diff_member(vec_b[b0 + len_b - 1], vec_a, a0, a0 + len_a - 1)) {
731       len_b--;
732     } else {
733       break;
734     }
735   }
736
737   *a0_p = a0;
738   *b0_p = b0;
739   *len_a_p = len_a;
740   *len_b_p = len_b;
741 }
742
743 /** @brief Compute the unified diff of two strings */
744 char *xbt_str_diff(const char *a, const char *b)
745 {
746   xbt_dynar_t da = xbt_str_split(a, "\n");
747   xbt_dynar_t db = xbt_str_split(b, "\n");
748   xbt_dynar_t common_sequence, common_suffix;
749   size_t len;
750   const char **vec_a, **vec_b;
751   int a0, b0;
752   int len_a, len_b;
753   int max;
754   int *fp_base, *fp;
755   struct subsequence *seqs_base, *seqs;
756   struct subsequence subseq;
757   xbt_dynar_t diff;
758   char *res;
759   int x, y;
760   unsigned s;
761
762   /* Clean empty lines at the end of da and db */
763   len = strlen(a);
764   if (len > 0 && a[len - 1] == '\n')
765     xbt_dynar_pop(da, NULL);
766   len = strlen(b);
767   if (len > 0 && b[len - 1] == '\n')
768     xbt_dynar_pop(db, NULL);
769
770   /* Various initializations */
771   /* Assume that dynar's content is contiguous */
772   a0 = 0;
773   len_a = xbt_dynar_length(da);
774   vec_a = len_a ? xbt_dynar_get_ptr(da, 0) : NULL;
775   b0 = 0;
776   len_b = xbt_dynar_length(db);
777   vec_b = len_b ? xbt_dynar_get_ptr(db, 0) : NULL;
778   max = MAX(len_a, len_b) + 1;
779   fp_base = xbt_new(int, 2 * max + 1);
780   fp = fp_base + max;           /* indexes in [-max..max] */
781   seqs_base = xbt_new(struct subsequence, 2 * max + 1);
782   seqs = seqs_base + max;       /* indexes in [-max..max] */
783   common_sequence = xbt_dynar_new(sizeof(struct subsequence), NULL);
784   common_suffix = xbt_dynar_new(sizeof(struct subsequence), NULL);
785
786   /* Add a sentinel a the end of the sequence */
787   subseq.x = len_a;
788   subseq.y = len_b;
789   subseq.len = 0;
790   xbt_dynar_push(common_suffix, &subseq);
791
792   /* Compute the Longest Common Subsequence */
793   diff_easy_prefix(vec_a, &a0, &len_a, vec_b, &b0, &len_b, common_sequence);
794   diff_easy_suffix(vec_a, &a0, &len_a, vec_b, &b0, &len_b, common_suffix);
795   diff_compute_lcs(vec_a, a0, len_a, vec_b, b0, len_b, common_sequence, seqs, fp);
796   while (!xbt_dynar_is_empty(common_suffix)) {
797     xbt_dynar_pop(common_suffix, &subseq);
798     xbt_dynar_push(common_sequence, &subseq);
799   }
800
801   /* Build a Shortest Edit Script, and the final result */
802   diff = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
803   x = 0;
804   y = 0;
805   xbt_dynar_foreach(common_sequence, s, subseq) {
806     while (x < subseq.x) {
807       char *topush = bprintf("- %s", vec_a[x++]);
808       xbt_dynar_push_as(diff, char*, topush);
809     }
810     while (y < subseq.y) {
811       char *topush = bprintf("+ %s", vec_b[y++]);
812       xbt_dynar_push_as(diff, char*, topush);
813     }
814     while (x < subseq.x + subseq.len) {
815       char *topush = bprintf("  %s", vec_a[x++]);
816       xbt_dynar_push_as(diff, char*, topush);
817       y++;
818     }
819   }
820   res = xbt_str_join(diff, "\n");
821
822   xbt_free(fp_base);
823   xbt_free(seqs_base);
824   xbt_dynar_free(&db);
825   xbt_dynar_free(&da);
826   xbt_dynar_free(&common_sequence);
827   xbt_dynar_free(&common_suffix);
828   xbt_dynar_free(&diff);
829
830   return res;
831 }
832
833
834 /** @brief creates a new string containing what can be read on a fd
835  *
836  */
837 char *xbt_str_from_file(FILE * file)
838 {
839   xbt_strbuff_t buff = xbt_strbuff_new();
840   char *res;
841   char bread[1024];
842   memset(bread, 0, 1024);
843
844   while (!feof(file)) {
845     int got = fread(bread, 1, 1023, file);
846     bread[got] = '\0';
847     xbt_strbuff_append(buff, bread);
848   }
849
850   res = buff->data;
851   xbt_strbuff_free_container(buff);
852   return res;
853 }
854
855 /* @brief Retrun 1 if string 'str' starts with string 'start'
856  *
857  * \param str a string
858  * \param start the string to search in str
859  *
860  * \return 1 if 'str' starts with 'start'
861  */
862 int xbt_str_start_with(const char* str, const char* start)
863 {
864   unsigned int i;
865   size_t l_str = strlen(str);
866   size_t l_start = strlen(start);
867
868   if(l_start > l_str) return 0;
869
870   for(i = 0; i< l_start; i++){
871     if(str[i] != start[i]) return 0;
872   }
873
874   return 1;
875 }
876
877 #ifdef SIMGRID_TEST
878 #include "xbt/str.h"
879
880 #define mytest(name, input, expected) \
881   xbt_test_add(name); \
882   d=xbt_str_split_quoted(input); \
883   s=xbt_str_join(d,"XXX"); \
884   xbt_test_assert(!strcmp(s,expected),\
885                    "Input (%s) leads to (%s) instead of (%s)", \
886                    input,s,expected);\
887                    free(s); \
888                    xbt_dynar_free(&d);
889
890 XBT_TEST_SUITE("xbt_str", "String Handling");
891 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
892 {
893   xbt_dynar_t d;
894   char *s;
895
896   mytest("Empty", "", "");
897   mytest("Basic test", "toto tutu", "totoXXXtutu");
898   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u",
899          "totoXXXtutu");
900   mytest("Protected space", "toto\\ tutu", "toto tutu");
901   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
902   mytest("LTriming", "  toto tatu", "totoXXXtatu");
903   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
904   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
905   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
906   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
907   mytest("Backslashed quotes", "\\'toto tutu\\' tata",
908          "'totoXXXtutu'XXXtata");
909   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
910          "toto 'tutuXXXtata");
911
912 }
913
914 #define mytest_str(name, input, separator, expected) \
915   xbt_test_add(name); \
916   d=xbt_str_split_str(input, separator); \
917   s=xbt_str_join(d,"XXX"); \
918   xbt_test_assert(!strcmp(s,expected),\
919                    "Input (%s) leads to (%s) instead of (%s)", \
920                    input,s,expected);\
921                    free(s); \
922                    xbt_dynar_free(&d);
923
924 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
925 {
926   xbt_dynar_t d;
927   char *s;
928
929   mytest_str("Empty string and separator", "", "", "");
930   mytest_str("Empty string", "", "##", "");
931   mytest_str("Empty separator", "toto", "", "toto");
932   mytest_str("String with no separator in it", "toto", "##", "toto");
933   mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
934 }
935
936 /* Last args are format string and parameters for xbt_test_add */
937 #define mytest_diff(s1, s2, diff, ...)                                  \
938   do {                                                                  \
939     char *mytest_diff_res;                                              \
940     xbt_test_add(__VA_ARGS__);                                          \
941     mytest_diff_res = xbt_str_diff(s1, s2);                             \
942     xbt_test_assert(!strcmp(mytest_diff_res, diff),                     \
943                     "Wrong output:\n--- got:\n%s\n--- expected:\n%s\n---", \
944                     mytest_diff_res, diff);                             \
945     free(mytest_diff_res);                                              \
946   } while (0)
947
948 XBT_TEST_UNIT("xbt_str_diff", test_diff, "test the function xbt_str_diff")
949 {
950   unsigned i;
951
952   /* Trivial cases */
953   mytest_diff("a", "a", "  a", "1 word, no difference");
954   mytest_diff("a", "A", "- a\n+ A", "1 word, different");
955   mytest_diff("a\n", "a\n", "  a", "1 line, no difference");
956   mytest_diff("a\n", "A\n", "- a\n+ A", "1 line, different");
957
958   /* Empty strings */
959   mytest_diff("", "", "", "empty strings");
960   mytest_diff("", "a", "+ a", "1 word, added");
961   mytest_diff("a", "", "- a", "1 word, removed");
962   mytest_diff("", "a\n", "+ a", "1 line, added");
963   mytest_diff("a\n", "", "- a", "1 line, removed");
964   mytest_diff("", "a\nb\nc\n", "+ a\n+ b\n+ c", "4 lines, all added");
965   mytest_diff("a\nb\nc\n", "", "- a\n- b\n- c", "4 lines, all removed");
966
967   /* Empty lines */
968   mytest_diff("\n", "\n", "  ", "empty lines");
969   mytest_diff("", "\n", "+ ", "empty line, added");
970   mytest_diff("\n", "", "- ", "empty line, removed");
971
972   mytest_diff("a", "\na", "+ \n  a", "empty line added before word");
973   mytest_diff("a", "a\n\n", "  a\n+ ", "empty line added after word");
974   mytest_diff("\na", "a", "- \n  a", "empty line removed before word");
975   mytest_diff("a\n\n", "a", "  a\n- ", "empty line removed after word");
976
977   mytest_diff("a\n", "\na\n", "+ \n  a", "empty line added before line");
978   mytest_diff("a\n", "a\n\n", "  a\n+ ", "empty line added after line");
979   mytest_diff("\na\n", "a\n", "- \n  a", "empty line removed before line");
980   mytest_diff("a\n\n", "a\n", "  a\n- ", "empty line removed after line");
981
982   mytest_diff("a\nb\nc\nd\n", "\na\nb\nc\nd\n", "+ \n  a\n  b\n  c\n  d",
983               "empty line added before 4 lines");
984   mytest_diff("a\nb\nc\nd\n", "a\nb\nc\nd\n\n", "  a\n  b\n  c\n  d\n+ ",
985               "empty line added after 4 lines");
986   mytest_diff("\na\nb\nc\nd\n", "a\nb\nc\nd\n", "- \n  a\n  b\n  c\n  d",
987               "empty line removed before 4 lines");
988   mytest_diff("a\nb\nc\nd\n\n", "a\nb\nc\nd\n", "  a\n  b\n  c\n  d\n- ",
989               "empty line removed after 4 lines");
990
991   /* Missing newline at the end of one of the strings */
992   mytest_diff("a\n", "a", "  a", "1 line, 1 word, no difference");
993   mytest_diff("a", "a\n", "  a", "1 word, 1 line, no difference");
994   mytest_diff("a\n", "A", "- a\n+ A", "1 line, 1 word, different");
995   mytest_diff("a", "A\n", "- a\n+ A", "1 word, 1 line, different");
996
997   mytest_diff("a\nb\nc\nd", "a\nb\nc\nd\n", "  a\n  b\n  c\n  d",
998               "4 lines, no newline on first");
999   mytest_diff("a\nb\nc\nd\n", "a\nb\nc\nd", "  a\n  b\n  c\n  d",
1000               "4 lines, no newline on second");
1001
1002   /* Four lines, all combinations of differences */
1003   for (i = 0 ; i < (1U << 4) ; i++) {
1004     char d2[4 + 1];
1005     char s2[4 * 2 + 1];
1006     char res[4 * 8 + 1];
1007     char *pd = d2;
1008     char *ps = s2;
1009     char *pr = res;
1010     unsigned j = 0;
1011     while (j < 4) {
1012       unsigned k;
1013       for (/* j */ ; j < 4 && !(i & (1U << j)) ; j++) {
1014         *pd++ = "abcd"[j];
1015         ps += sprintf(ps, "%c\n", "abcd"[j]);
1016         pr += sprintf(pr, "  %c\n", "abcd"[j]);
1017       }
1018       for (k = j ; k < 4 && (i & (1U << k)) ; k++) {
1019         *pd++ = "ABCD"[k];
1020         ps += sprintf(ps, "%c\n", "ABCD"[k]);
1021         pr += sprintf(pr, "- %c\n", "abcd"[k]);
1022       }
1023       for (/* j */ ; j < k ; j++) {
1024         pr += sprintf(pr, "+ %c\n", "ABCD"[j]);
1025       }
1026     }
1027     *pd = '\0';
1028     *--pr = '\0';               /* strip last '\n' from expected result */
1029     mytest_diff("a\nb\nc\nd\n", s2, res,
1030                 "compare (abcd) with changed (%s)", d2);
1031   }
1032
1033   /* Subsets of four lines, do not test for empty subset */
1034   for (i = 1 ; i < (1U << 4) ; i++) {
1035     char d2[4 + 1];
1036     char s2[4 * 2 + 1];
1037     char res[4 * 8 + 1];
1038     char *pd = d2;
1039     char *ps = s2;
1040     char *pr = res;
1041     unsigned j = 0;
1042     while (j < 4) {
1043       for (/* j */ ; j < 4 && (i & (1U << j)) ; j++) {
1044         *pd++ = "abcd"[j];
1045         ps += sprintf(ps, "%c\n", "abcd"[j]);
1046         pr += sprintf(pr, "  %c\n", "abcd"[j]);
1047       }
1048       for (/* j */; j < 4 && !(i & (1U << j)) ; j++) {
1049         pr += sprintf(pr, "- %c\n", "abcd"[j]);
1050       }
1051     }
1052     *pd = '\0';
1053     *--pr = '\0';               /* strip last '\n' from expected result */
1054     mytest_diff("a\nb\nc\nd\n", s2, res,
1055                 "compare (abcd) with subset (%s)", d2);
1056
1057     for (pr = res ; *pr != '\0' ; pr++)
1058       if (*pr == '-')
1059         *pr = '+';
1060     mytest_diff(s2, "a\nb\nc\nd\n", res,
1061                 "compare subset (%s) with (abcd)", d2);
1062   }
1063 }
1064
1065 #endif                          /* SIMGRID_TEST */