Logo AND Algorithmique Numérique Distribuée

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