Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix merge conflict
[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 #define DJB2_HASH_FUNCTION
10 //#define FNV_HASH_FUNCTION
11
12 #include "portable.h"
13 #include "xbt/misc.h"
14 #include "xbt/sysdep.h"
15 #include "xbt/str.h"            /* headers of these functions */
16 #include "xbt/strbuff.h"
17 #include "xbt/matrix.h"         /* for the diff */
18
19 /**  @brief Strip whitespace (or other characters) from the end of a string.
20  *
21  * Strips the whitespaces from the end of s.
22  * By default (when char_list=NULL), these characters get stripped:
23  *
24  *      - " "           (ASCII 32       (0x20)) space.
25  *      - "\t"          (ASCII 9        (0x09)) tab.
26  *      - "\n"          (ASCII 10       (0x0A)) line feed.
27  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
28  *      - "\0"          (ASCII 0        (0x00)) NULL.
29  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
30  *
31  * @param s The string to strip. Modified in place.
32  * @param char_list A string which contains the characters you want to strip.
33  *
34  */
35 void xbt_str_rtrim(char *s, const char *char_list)
36 {
37   char *cur = s;
38   const char *__char_list = " \t\n\r\x0B";
39   char white_char[256] = { 1, 0 };
40
41   if (!s)
42     return;
43
44   if (!char_list) {
45     while (*__char_list) {
46       white_char[(unsigned char) *__char_list++] = 1;
47     }
48   } else {
49     while (*char_list) {
50       white_char[(unsigned char) *char_list++] = 1;
51     }
52   }
53
54   while (*cur)
55     ++cur;
56
57   while ((cur >= s) && white_char[(unsigned char) *cur])
58     --cur;
59
60   *++cur = '\0';
61 }
62
63 /**  @brief Strip whitespace (or other characters) from the beginning of a string.
64  *
65  * Strips the whitespaces from the begining of s.
66  * By default (when char_list=NULL), these characters get stripped:
67  *
68  *      - " "           (ASCII 32       (0x20)) space.
69  *      - "\t"          (ASCII 9        (0x09)) tab.
70  *      - "\n"          (ASCII 10       (0x0A)) line feed.
71  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
72  *      - "\0"          (ASCII 0        (0x00)) NULL.
73  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
74  *
75  * @param s The string to strip. Modified in place.
76  * @param char_list A string which contains the characters you want to strip.
77  *
78  */
79 void xbt_str_ltrim(char *s, const char *char_list)
80 {
81   char *cur = s;
82   const char *__char_list = " \t\n\r\x0B";
83   char white_char[256] = { 1, 0 };
84
85   if (!s)
86     return;
87
88   if (!char_list) {
89     while (*__char_list) {
90       white_char[(unsigned char) *__char_list++] = 1;
91     }
92   } else {
93     while (*char_list) {
94       white_char[(unsigned char) *char_list++] = 1;
95     }
96   }
97
98   while (*cur && white_char[(unsigned char) *cur])
99     ++cur;
100
101   memmove(s, cur, strlen(cur) + 1);
102 }
103
104 /**  @brief Strip whitespace (or other characters) from the end and the begining of a string.
105  *
106  * Strips the whitespaces from both the beginning and the end of s.
107  * By default (when char_list=NULL), these characters get stripped:
108  *
109  *      - " "           (ASCII 32       (0x20)) space.
110  *      - "\t"          (ASCII 9        (0x09)) tab.
111  *      - "\n"          (ASCII 10       (0x0A)) line feed.
112  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
113  *      - "\0"          (ASCII 0        (0x00)) NULL.
114  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
115  *
116  * @param s The string to strip.
117  * @param char_list A string which contains the characters you want to strip.
118  *
119  */
120 void xbt_str_trim(char *s, const char *char_list)
121 {
122
123   if (!s)
124     return;
125
126   xbt_str_rtrim(s, char_list);
127   xbt_str_ltrim(s, char_list);
128 }
129
130 /**  @brief Replace double whitespaces (but no other characters) from the string.
131  *
132  * The function modifies the string so that each time that several spaces appear,
133  * they are replaced by a single space. It will only do so for spaces (ASCII 32, 0x20).
134  *
135  * @param s The string to strip. Modified in place.
136  *
137  */
138 void xbt_str_strip_spaces(char *s)
139 {
140   char *p = s;
141   int e = 0;
142
143   if (!s)
144     return;
145
146   while (1) {
147     if (!*p)
148       goto end;
149
150     if (*p != ' ')
151       break;
152
153     p++;
154   }
155
156   e = 1;
157
158   do {
159     if (e)
160       *s++ = *p;
161
162     if (!*++p)
163       goto end;
164
165     if (e ^ (*p != ' '))
166       if ((e = !e))
167         *s++ = ' ';
168   } while (1);
169
170 end:
171   *s = '\0';
172 }
173
174 /** @brief Substitutes a char for another in a string
175  *
176  * @param str the string to modify
177  * @param from char to search
178  * @param to char to put instead
179  * @param occurence number of changes to do (=0 means all)
180  */
181 void xbt_str_subst(char *str, char from, char to, int occurence)
182 {
183   char *p = str;
184   while (*p != '\0') {
185     if (*p == from) {
186       *p = to;
187       if (occurence == 1)
188         return;
189       occurence--;
190     }
191     p++;
192   }
193 }
194
195 /** @brief Replaces a set of variables by their values
196  *
197  * @param str The input of the replacement process
198  * @param patterns The changes to apply
199  * @return The string modified
200  *
201  * Both '$toto' and '${toto}' are valid (and the two writing are equivalent).
202  *
203  * If the variable name contains spaces, use the brace version (ie, ${toto tutu})
204  *
205  * You can provide a default value to use if the variable is not set in the dict by using
206  * '${var:=default}' or '${var:-default}'. These two forms are equivalent, even if they
207  * shouldn't to respect the shell standard (:= form should set the value in the dict,
208  * but does not) (BUG).
209  */
210
211 char *xbt_str_varsubst(const char *str, xbt_dict_t patterns)
212 {
213   xbt_strbuff_t buff = xbt_strbuff_new_from(str);
214   char *res;
215   xbt_strbuff_varsubst(buff, patterns);
216   res = buff->data;
217   xbt_strbuff_free_container(buff);
218   return res;
219 }
220
221
222 /** @brief Splits a string into a dynar of strings
223  *
224  * @param s: the string to split
225  * @param sep: a string of all chars to consider as separator.
226  *
227  * By default (with sep=NULL), these characters are used as separator:
228  *
229  *      - " "           (ASCII 32       (0x20)) space.
230  *      - "\t"          (ASCII 9        (0x09)) tab.
231  *      - "\n"          (ASCII 10       (0x0A)) line feed.
232  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
233  *      - "\0"          (ASCII 0        (0x00)) NULL.
234  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
235  */
236
237 xbt_dynar_t xbt_str_split(const char *s, const char *sep)
238 {
239   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
240   const char *p, *q;
241   int done;
242   const char *sep_dflt = " \t\n\r\x0B";
243   char is_sep[256] = { 1, 0 };
244
245   /* check what are the separators */
246   memset(is_sep, 0, sizeof(is_sep));
247   if (!sep) {
248     while (*sep_dflt)
249       is_sep[(unsigned char) *sep_dflt++] = 1;
250   } else {
251     while (*sep)
252       is_sep[(unsigned char) *sep++] = 1;
253   }
254   is_sep[0] = 1;                /* End of string is also separator */
255
256   /* Do the job */
257   p = q = s;
258   done = 0;
259
260   if (s[0] == '\0')
261     return res;
262
263   while (!done) {
264     char *topush;
265     while (!is_sep[(unsigned char) *q]) {
266       q++;
267     }
268     if (*q == '\0')
269       done = 1;
270
271     topush = xbt_malloc(q - p + 1);
272     memcpy(topush, p, q - p);
273     topush[q - p] = '\0';
274     xbt_dynar_push(res, &topush);
275     p = ++q;
276   }
277
278   return res;
279 }
280
281 /**
282  * \brief This functions splits a string after using another string as separator
283  * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
284  * \return An array of dynars containing the string tokens
285  */
286 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep)
287 {
288   xbt_dynar_t res = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
289   int done;
290   const char *p, *q;
291
292   p = q = s;
293   done = 0;
294
295   if (s[0] == '\0')
296     return res;
297   if (sep[0] == '\0') {
298     s = xbt_strdup(s);
299     xbt_dynar_push(res, &s);
300     return res;
301   }
302
303   while (!done) {
304     char *to_push;
305     int v = 0;
306     //get the start of the first occurence of the substring
307     q = strstr(p, sep);
308     //if substring was not found add the entire string
309     if (NULL == q) {
310       v = strlen(p);
311       to_push = malloc(v + 1);
312       memcpy(to_push, p, v);
313       to_push[v] = '\0';
314       xbt_dynar_push(res, &to_push);
315       done = 1;
316     } else {
317       //get the appearance
318       to_push = malloc(q - p + 1);
319       memcpy(to_push, p, q - p);
320       //add string terminator
321       to_push[q - p] = '\0';
322       xbt_dynar_push(res, &to_push);
323       p = q + strlen(sep);
324     }
325   }
326   return res;
327 }
328
329 /** @brief Just like @ref xbt_str_split_quoted (Splits a string into a dynar of strings), but without memory allocation
330  *
331  * The string passed as argument must be writable (not const)
332  * The elements of the dynar are just parts of the string passed as argument.
333  *
334  * To free the structure constructed by this function, free the first element and free the dynar:
335  *
336  * free(xbt_dynar_get_ptr(dynar,0));
337  * xbt_dynar_free(&dynar);
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 responsability 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 #if defined(SIMGRID_NEED_GETLINE) || defined(DOXYGEN)
524 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
525  *
526  * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
527  *
528  * getline() reads an entire line from stream, storing the address of the buffer
529  * containing the text into *buf.  The buffer is null-terminated and includes
530  * the newline character, if one was found.
531  *
532  * If *buf is NULL, then getline() will allocate a buffer for storing the line,
533  * which should be freed by the user program.  Alternatively, before calling getline(),
534  * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size.  If the buffer
535  * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n
536  * as necessary.  In either case, on a successful call, *buf and *n will be updated to
537  * reflect the buffer address and allocated size respectively.
538  */
539 long getline(char **buf, size_t * n, FILE * stream)
540 {
541
542   size_t i;
543   int ch;
544
545   if (!*buf) {
546     *buf = xbt_malloc(512);
547     *n = 512;
548   }
549
550   if (feof(stream))
551     return (ssize_t) - 1;
552
553   for (i = 0; (ch = fgetc(stream)) != EOF; i++) {
554
555     if (i >= (*n) + 1)
556       *buf = xbt_realloc(*buf, *n += 512);
557
558     (*buf)[i] = ch;
559
560     if ((*buf)[i] == '\n') {
561       i++;
562       (*buf)[i] = '\0';
563       break;
564     }
565   }
566
567   if (i == *n)
568     *buf = xbt_realloc(*buf, *n += 1);
569
570   (*buf)[i] = '\0';
571
572   return (ssize_t) i;
573 }
574
575 #endif                          /* HAVE_GETLINE */
576
577 /*
578  * Diff related functions
579  *
580  * Implementation of the algorithm described in "An O(NP) Sequence Comparison
581  * Algorithm", by Sun Wu, Udi Manber, Gene Myers, and Webb Miller (Information
582  * Processing Letters 35(6):317-323, 1990), with the linear-space
583  * divide-and-conquer strategy described in "An O(ND) Difference Algorithm and
584  * Its Variations", by Eugene W. Myers (Algorithmica 1:251-266, 1986).
585  */
586
587 struct subsequence {
588     int x, y;                   /* starting coordinates */
589     int len;                    /* length */
590 };
591
592 static XBT_INLINE
593 void diff_snake(const char *vec_a[], int a0, int len_a,
594                 const char *vec_b[], int b0, int len_b,
595                 struct subsequence *seqs, int *fp, int k, int limit)
596 {
597   int record_seq;
598   int x, y;
599   int fp_left = fp[k - 1] + 1;
600   int fp_right = fp[k + 1];
601   if (fp_left > fp_right) {
602     x = fp_left;
603     record_seq = k - 1;
604   } else {
605     x = fp_right;
606     record_seq = k + 1;
607   }
608   y = x - k;
609   if (x + y <= limit) {
610     seqs[k].x = x;
611     seqs[k].y = y;
612     record_seq = k;
613   } else {
614     seqs[k] = seqs[record_seq];
615   }
616   while (x < len_a && y < len_b && !strcmp(vec_a[a0 + x], vec_b[b0 + y]))
617     ++x, ++y;
618   fp[k] = x;
619   if (record_seq == k)
620     seqs[k].len = x - seqs[k].x;
621 }
622
623 /* Returns the length of a shortest edit script, and a common
624  * subsequence from the middle.
625  */
626 static int diff_middle_subsequence(const char *vec_a[], int a0,  int len_a,
627                                    const char *vec_b[], int b0,  int len_b,
628                                    struct subsequence *subseq,
629                                    struct subsequence *seqs, int *fp)
630 {
631   const int delta = len_a - len_b;
632   const int limit = (len_a + len_b) / 2;
633   int kmin;
634   int kmax;
635   int k;
636   int p = -1;
637
638   if (delta >= 0) {
639     kmin = 0;
640     kmax = delta;
641   } else {
642     kmin = delta;
643     kmax = 0;
644   }
645   for (k = kmin; k <= kmax; k++)
646     fp[k] = -1;
647   do {
648     p++;
649     fp[kmin - p - 1] = fp[kmax + p + 1] = -1;
650     for (k = kmax + p; k > delta; k--)
651       diff_snake(vec_a, a0, len_a, vec_b, b0, len_b, seqs, fp, k, limit);
652     for (k = kmin - p; k <= delta; k++)
653       diff_snake(vec_a, a0, len_a, vec_b, b0, len_b, seqs, fp, k, limit);
654   } while (fp[delta] != len_a);
655
656   subseq->x = a0 + seqs[delta].x;
657   subseq->y = b0 + seqs[delta].y;
658   subseq->len = seqs[delta].len;
659   return abs(delta) + 2 * p;;
660 }
661
662 /* Finds a longest common subsequence.
663  * Returns its length.
664  */
665 static int diff_compute_lcs(const char *vec_a[], int a0, int len_a,
666                             const char *vec_b[], int b0, int len_b,
667                             xbt_dynar_t common_sequence,
668                             struct subsequence *seqs, int *fp)
669 {
670   if (len_a > 0 && len_b > 0) {
671     struct subsequence subseq;
672     int ses_len = diff_middle_subsequence(vec_a, a0, len_a, vec_b, b0, len_b,
673                                           &subseq, seqs, fp);
674     int lcs_len = (len_a + len_b - ses_len) / 2;
675     if (lcs_len == 0) {
676       return 0;
677     } else if (ses_len > 1) {
678       int lcs_len1 = subseq.len;
679       if (lcs_len1 < lcs_len)
680         lcs_len1 += diff_compute_lcs(vec_a, a0, subseq.x - a0,
681                                      vec_b, b0, subseq.y - b0,
682                                      common_sequence, seqs, fp);
683       if (subseq.len > 0)
684         xbt_dynar_push(common_sequence, &subseq);
685       if (lcs_len1 < lcs_len) {
686         int u = subseq.x + subseq.len;
687         int v = subseq.y + subseq.len;
688         diff_compute_lcs(vec_a, u, a0 + len_a - u, vec_b, v, b0 + len_b - v,
689                          common_sequence, seqs, fp);
690       }
691     } else {
692       int len = MIN(len_a, len_b) - subseq.len;
693       if (subseq.x == a0 && subseq.y == b0) {
694         if (subseq.len > 0)
695           xbt_dynar_push(common_sequence, &subseq);
696         if (len > 0) {
697           struct subsequence subseq0 = {a0 + len_a - len,
698                                         b0 + len_b - len, len};
699           xbt_dynar_push(common_sequence, &subseq0);
700         }
701       } else {
702         if (len > 0) {
703           struct subsequence subseq0 = {a0, b0, len};
704           xbt_dynar_push(common_sequence, &subseq0);
705         }
706         if (subseq.len > 0)
707           xbt_dynar_push(common_sequence, &subseq);
708       }
709     }
710     return lcs_len;
711   } else {
712     return 0;
713   }
714 }
715
716 static int diff_member(const char *s, const char *vec[], int from, int to)
717 {
718   for ( ; from < to ; from++)
719     if (!strcmp(s, vec[from]))
720       return 1;
721   return 0;
722 }
723
724 /* Extract common prefix.
725  */
726 static void diff_easy_prefix(const char *vec_a[], int *a0_p, int *len_a_p,
727                              const char *vec_b[], int *b0_p, int *len_b_p,
728                              xbt_dynar_t common_sequence)
729 {
730   int a0 = *a0_p;
731   int b0 = *b0_p;
732   int len_a = *len_a_p;
733   int len_b = *len_b_p;
734
735   while (len_a > 0 && len_b > 0) {
736     struct subsequence subseq = {a0, b0, 0};
737     while (len_a > 0 && len_b > 0 && !strcmp(vec_a[a0], vec_b[b0])) {
738       a0++, len_a--;
739       b0++, len_b--;
740       subseq.len++;
741     }
742     if (subseq.len > 0)
743       xbt_dynar_push(common_sequence, &subseq);
744     if (len_a > 0 && len_b > 0 &&
745         !diff_member(vec_a[a0], vec_b, b0 + 1, b0 + len_b)) {
746       a0++, len_a--;
747     } else {
748       break;
749     }
750   }
751
752   *a0_p = a0;
753   *b0_p = b0;
754   *len_a_p = len_a;
755   *len_b_p = len_b;
756 }
757
758 /* Extract common suffix.
759  */
760 static void diff_easy_suffix(const char *vec_a[], int *a0_p, int *len_a_p,
761                              const char *vec_b[], int *b0_p, int *len_b_p,
762                              xbt_dynar_t common_suffix)
763 {
764   int a0 = *a0_p;
765   int b0 = *b0_p;
766   int len_a = *len_a_p;
767   int len_b = *len_b_p;
768
769   while (len_a > 0 && len_b > 0){
770     struct subsequence subseq;
771     subseq.len = 0;
772     while (len_a > 0 && len_b > 0 &&
773            !strcmp(vec_a[a0 + len_a - 1], vec_b[b0 + len_b - 1])) {
774       len_a--;
775       len_b--;
776       subseq.len++;
777     }
778     if (subseq.len > 0) {
779       subseq.x = a0 + len_a;
780       subseq.y = b0 + len_b;
781       xbt_dynar_push(common_suffix, &subseq);
782     }
783     if (len_a > 0 && len_b > 0 &&
784         !diff_member(vec_b[b0 + len_b - 1], vec_a, a0, a0 + len_a - 1)) {
785       len_b--;
786     } else {
787       break;
788     }
789   }
790
791   *a0_p = a0;
792   *b0_p = b0;
793   *len_a_p = len_a;
794   *len_b_p = len_b;
795 }
796
797 /** @brief Compute the unified diff of two strings */
798 char *xbt_str_diff(const char *a, const char *b)
799 {
800   xbt_dynar_t da = xbt_str_split(a, "\n");
801   xbt_dynar_t db = xbt_str_split(b, "\n");
802   xbt_dynar_t common_sequence, common_suffix;
803   size_t len;
804   const char **vec_a, **vec_b;
805   int a0, b0;
806   int len_a, len_b;
807   int max;
808   int *fp_base, *fp;
809   struct subsequence *seqs_base, *seqs;
810   struct subsequence subseq;
811   xbt_dynar_t diff;
812   char *res;
813   int x, y;
814   unsigned s;
815
816   /* Clean empty lines at the end of da and db */
817   len = strlen(a);
818   if (len > 0 && a[len - 1] == '\n')
819     xbt_dynar_pop(da, NULL);
820   len = strlen(b);
821   if (len > 0 && b[len - 1] == '\n')
822     xbt_dynar_pop(db, NULL);
823
824   /* Various initializations */
825   /* Assume that dynar's content is contiguous */
826   a0 = 0;
827   len_a = xbt_dynar_length(da);
828   vec_a = len_a ? xbt_dynar_get_ptr(da, 0) : NULL;
829   b0 = 0;
830   len_b = xbt_dynar_length(db);
831   vec_b = len_b ? xbt_dynar_get_ptr(db, 0) : NULL;
832   max = MAX(len_a, len_b) + 1;
833   fp_base = xbt_new(int, 2 * max + 1);
834   fp = fp_base + max;           /* indexes in [-max..max] */
835   seqs_base = xbt_new(struct subsequence, 2 * max + 1);
836   seqs = seqs_base + max;       /* indexes in [-max..max] */
837   common_sequence = xbt_dynar_new(sizeof(struct subsequence), NULL);
838   common_suffix = xbt_dynar_new(sizeof(struct subsequence), NULL);
839
840   /* Add a sentinel a the end of the sequence */
841   subseq.x = len_a;
842   subseq.y = len_b;
843   subseq.len = 0;
844   xbt_dynar_push(common_suffix, &subseq);
845
846   /* Compute the Longest Common Subsequence */
847   diff_easy_prefix(vec_a, &a0, &len_a, vec_b, &b0, &len_b, common_sequence);
848   diff_easy_suffix(vec_a, &a0, &len_a, vec_b, &b0, &len_b, common_suffix);
849   diff_compute_lcs(vec_a, a0, len_a, vec_b, b0, len_b, common_sequence, seqs, fp);
850   while (!xbt_dynar_is_empty(common_suffix)) {
851     xbt_dynar_pop(common_suffix, &subseq);
852     xbt_dynar_push(common_sequence, &subseq);
853   }
854
855   /* Build a Shortest Edit Script, and the final result */
856   diff = xbt_dynar_new(sizeof(char *), &xbt_free_ref);
857   x = 0;
858   y = 0;
859   xbt_dynar_foreach(common_sequence, s, subseq) {
860     while (x < subseq.x) {
861       char *topush = bprintf("- %s", vec_a[x++]);
862       xbt_dynar_push_as(diff, char*, topush);
863     }
864     while (y < subseq.y) {
865       char *topush = bprintf("+ %s", vec_b[y++]);
866       xbt_dynar_push_as(diff, char*, topush);
867     }
868     while (x < subseq.x + subseq.len) {
869       char *topush = bprintf("  %s", vec_a[x++]);
870       xbt_dynar_push_as(diff, char*, topush);
871       y++;
872     }
873   }
874   res = xbt_str_join(diff, "\n");
875
876   xbt_free(fp_base);
877   xbt_free(seqs_base);
878   xbt_dynar_free(&db);
879   xbt_dynar_free(&da);
880   xbt_dynar_free(&common_sequence);
881   xbt_dynar_free(&common_suffix);
882   xbt_dynar_free(&diff);
883
884   return res;
885 }
886
887
888 /** @brief creates a new string containing what can be read on a fd
889  *
890  */
891 char *xbt_str_from_file(FILE * file)
892 {
893   xbt_strbuff_t buff = xbt_strbuff_new();
894   char *res;
895   char bread[1024];
896   memset(bread, 0, 1024);
897
898   while (!feof(file)) {
899     int got = fread(bread, 1, 1023, file);
900     bread[got] = '\0';
901     xbt_strbuff_append(buff, bread);
902   }
903
904   res = buff->data;
905   xbt_strbuff_free_container(buff);
906   return res;
907 }
908
909 /**
910  * @brief Returns the hash code of a string.
911  */
912 XBT_INLINE unsigned int xbt_dict_hash_ext(const char *str,
913                                                  int str_len)
914 {
915
916 #ifdef DJB2_HASH_FUNCTION
917   /* fast implementation of djb2 algorithm */
918   int c;
919   register unsigned int hash = 5381;
920
921   while (str_len--) {
922     c = *str++;
923     hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
924   }
925 # elif defined(FNV_HASH_FUNCTION)
926   register unsigned int hash = 0x811c9dc5;
927   unsigned char *bp = (unsigned char *) str;    /* start of buffer */
928   unsigned char *be = bp + str_len;     /* beyond end of buffer */
929
930   while (bp < be) {
931     /* multiply by the 32 bit FNV magic prime mod 2^32 */
932     hash +=
933         (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) +
934         (hash << 24);
935
936     /* xor the bottom with the current octet */
937     hash ^= (unsigned int) *bp++;
938   }
939
940 # else
941   register unsigned int hash = 0;
942
943   while (str_len--) {
944     hash += (*str) * (*str);
945     str++;
946   }
947 #endif
948
949   return hash;
950 }
951
952 /**
953  * @brief Returns the hash code of a string.
954  */
955 XBT_INLINE unsigned int xbt_dict_hash(const char *str)
956 {
957 #ifdef DJB2_HASH_FUNCTION
958   /* fast implementation of djb2 algorithm */
959   int c;
960   register unsigned int hash = 5381;
961
962   while ((c = *str++)) {
963     hash = ((hash << 5) + hash) + c;    /* hash * 33 + c */
964   }
965
966 # elif defined(FNV_HASH_FUNCTION)
967   register unsigned int hash = 0x811c9dc5;
968
969   while (*str) {
970     /* multiply by the 32 bit FNV magic prime mod 2^32 */
971     hash +=
972         (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) +
973         (hash << 24);
974
975     /* xor the bottom with the current byte */
976     hash ^= (unsigned int) *str++;
977   }
978
979 # else
980   register unsigned int hash = 0;
981
982   while (*str) {
983     hash += (*str) * (*str);
984     str++;
985   }
986 #endif
987   return hash;
988 }
989
990 #ifdef SIMGRID_TEST
991 #include "xbt/str.h"
992
993 #define mytest(name, input, expected) \
994   xbt_test_add(name); \
995   d=xbt_str_split_quoted(input); \
996   s=xbt_str_join(d,"XXX"); \
997   xbt_test_assert(!strcmp(s,expected),\
998                    "Input (%s) leads to (%s) instead of (%s)", \
999                    input,s,expected);\
1000                    free(s); \
1001                    xbt_dynar_free(&d);
1002
1003 XBT_TEST_SUITE("xbt_str", "String Handling");
1004 XBT_TEST_UNIT("xbt_str_split_quoted", test_split_quoted, "test the function xbt_str_split_quoted")
1005 {
1006   xbt_dynar_t d;
1007   char *s;
1008
1009   mytest("Empty", "", "");
1010   mytest("Basic test", "toto tutu", "totoXXXtutu");
1011   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u",
1012          "totoXXXtutu");
1013   mytest("Protected space", "toto\\ tutu", "toto tutu");
1014   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
1015   mytest("LTriming", "  toto tatu", "totoXXXtatu");
1016   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
1017   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
1018   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
1019   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
1020   mytest("Backslashed quotes", "\\'toto tutu\\' tata",
1021          "'totoXXXtutu'XXXtata");
1022   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata",
1023          "toto 'tutuXXXtata");
1024
1025 }
1026
1027 #define mytest_str(name, input, separator, expected) \
1028   xbt_test_add(name); \
1029   d=xbt_str_split_str(input, separator); \
1030   s=xbt_str_join(d,"XXX"); \
1031   xbt_test_assert(!strcmp(s,expected),\
1032                    "Input (%s) leads to (%s) instead of (%s)", \
1033                    input,s,expected);\
1034                    free(s); \
1035                    xbt_dynar_free(&d);
1036
1037 XBT_TEST_UNIT("xbt_str_split_str", test_split_str, "test the function xbt_str_split_str")
1038 {
1039   xbt_dynar_t d;
1040   char *s;
1041
1042   mytest_str("Empty string and separator", "", "", "");
1043   mytest_str("Empty string", "", "##", "");
1044   mytest_str("Empty separator", "toto", "", "toto");
1045   mytest_str("String with no separator in it", "toto", "##", "toto");
1046   mytest_str("Basic test", "toto##tutu", "##", "totoXXXtutu");
1047 }
1048
1049 /* Last args are format string and parameters for xbt_test_add */
1050 #define mytest_diff(s1, s2, diff, ...)                                  \
1051   do {                                                                  \
1052     char *mytest_diff_res;                                              \
1053     xbt_test_add(__VA_ARGS__);                                          \
1054     mytest_diff_res = xbt_str_diff(s1, s2);                             \
1055     xbt_test_assert(!strcmp(mytest_diff_res, diff),                     \
1056                     "Wrong output:\n--- got:\n%s\n--- expected:\n%s\n---", \
1057                     mytest_diff_res, diff);                             \
1058     free(mytest_diff_res);                                              \
1059   } while (0)
1060
1061 XBT_TEST_UNIT("xbt_str_diff", test_diff, "test the function xbt_str_diff")
1062 {
1063   unsigned i;
1064
1065   /* Trivial cases */
1066   mytest_diff("a", "a", "  a", "1 word, no difference");
1067   mytest_diff("a", "A", "- a\n+ A", "1 word, different");
1068   mytest_diff("a\n", "a\n", "  a", "1 line, no difference");
1069   mytest_diff("a\n", "A\n", "- a\n+ A", "1 line, different");
1070
1071   /* Empty strings */
1072   mytest_diff("", "", "", "empty strings");
1073   mytest_diff("", "a", "+ a", "1 word, added");
1074   mytest_diff("a", "", "- a", "1 word, removed");
1075   mytest_diff("", "a\n", "+ a", "1 line, added");
1076   mytest_diff("a\n", "", "- a", "1 line, removed");
1077   mytest_diff("", "a\nb\nc\n", "+ a\n+ b\n+ c", "4 lines, all added");
1078   mytest_diff("a\nb\nc\n", "", "- a\n- b\n- c", "4 lines, all removed");
1079
1080   /* Empty lines */
1081   mytest_diff("\n", "\n", "  ", "empty lines");
1082   mytest_diff("", "\n", "+ ", "empty line, added");
1083   mytest_diff("\n", "", "- ", "empty line, removed");
1084
1085   mytest_diff("a", "\na", "+ \n  a", "empty line added before word");
1086   mytest_diff("a", "a\n\n", "  a\n+ ", "empty line added after word");
1087   mytest_diff("\na", "a", "- \n  a", "empty line removed before word");
1088   mytest_diff("a\n\n", "a", "  a\n- ", "empty line removed after word");
1089
1090   mytest_diff("a\n", "\na\n", "+ \n  a", "empty line added before line");
1091   mytest_diff("a\n", "a\n\n", "  a\n+ ", "empty line added after line");
1092   mytest_diff("\na\n", "a\n", "- \n  a", "empty line removed before line");
1093   mytest_diff("a\n\n", "a\n", "  a\n- ", "empty line removed after line");
1094
1095   mytest_diff("a\nb\nc\nd\n", "\na\nb\nc\nd\n", "+ \n  a\n  b\n  c\n  d",
1096               "empty line added before 4 lines");
1097   mytest_diff("a\nb\nc\nd\n", "a\nb\nc\nd\n\n", "  a\n  b\n  c\n  d\n+ ",
1098               "empty line added after 4 lines");
1099   mytest_diff("\na\nb\nc\nd\n", "a\nb\nc\nd\n", "- \n  a\n  b\n  c\n  d",
1100               "empty line removed before 4 lines");
1101   mytest_diff("a\nb\nc\nd\n\n", "a\nb\nc\nd\n", "  a\n  b\n  c\n  d\n- ",
1102               "empty line removed after 4 lines");
1103
1104   /* Missing newline at the end of one of the strings */
1105   mytest_diff("a\n", "a", "  a", "1 line, 1 word, no difference");
1106   mytest_diff("a", "a\n", "  a", "1 word, 1 line, no difference");
1107   mytest_diff("a\n", "A", "- a\n+ A", "1 line, 1 word, different");
1108   mytest_diff("a", "A\n", "- a\n+ A", "1 word, 1 line, different");
1109
1110   mytest_diff("a\nb\nc\nd", "a\nb\nc\nd\n", "  a\n  b\n  c\n  d",
1111               "4 lines, no newline on first");
1112   mytest_diff("a\nb\nc\nd\n", "a\nb\nc\nd", "  a\n  b\n  c\n  d",
1113               "4 lines, no newline on second");
1114
1115   /* Four lines, all combinations of differences */
1116   for (i = 0 ; i < (1U << 4) ; i++) {
1117     char d2[4 + 1];
1118     char s2[4 * 2 + 1];
1119     char res[4 * 8 + 1];
1120     char *pd = d2;
1121     char *ps = s2;
1122     char *pr = res;
1123     unsigned j = 0;
1124     while (j < 4) {
1125       unsigned k;
1126       for (/* j */ ; j < 4 && !(i & (1U << j)) ; j++) {
1127         *pd++ = "abcd"[j];
1128         ps += sprintf(ps, "%c\n", "abcd"[j]);
1129         pr += sprintf(pr, "  %c\n", "abcd"[j]);
1130       }
1131       for (k = j ; k < 4 && (i & (1U << k)) ; k++) {
1132         *pd++ = "ABCD"[k];
1133         ps += sprintf(ps, "%c\n", "ABCD"[k]);
1134         pr += sprintf(pr, "- %c\n", "abcd"[k]);
1135       }
1136       for (/* j */ ; j < k ; j++) {
1137         pr += sprintf(pr, "+ %c\n", "ABCD"[j]);
1138       }
1139     }
1140     *pd = '\0';
1141     *--pr = '\0';               /* strip last '\n' from expected result */
1142     mytest_diff("a\nb\nc\nd\n", s2, res,
1143                 "compare (abcd) with changed (%s)", d2);
1144   }
1145
1146   /* Subsets of four lines, do not test for empty subset */
1147   for (i = 1 ; i < (1U << 4) ; i++) {
1148     char d2[4 + 1];
1149     char s2[4 * 2 + 1];
1150     char res[4 * 8 + 1];
1151     char *pd = d2;
1152     char *ps = s2;
1153     char *pr = res;
1154     unsigned j = 0;
1155     while (j < 4) {
1156       for (/* j */ ; j < 4 && (i & (1U << j)) ; j++) {
1157         *pd++ = "abcd"[j];
1158         ps += sprintf(ps, "%c\n", "abcd"[j]);
1159         pr += sprintf(pr, "  %c\n", "abcd"[j]);
1160       }
1161       for (/* j */; j < 4 && !(i & (1U << j)) ; j++) {
1162         pr += sprintf(pr, "- %c\n", "abcd"[j]);
1163       }
1164     }
1165     *pd = '\0';
1166     *--pr = '\0';               /* strip last '\n' from expected result */
1167     mytest_diff("a\nb\nc\nd\n", s2, res,
1168                 "compare (abcd) with subset (%s)", d2);
1169
1170     for (pr = res ; *pr != '\0' ; pr++)
1171       if (*pr == '-')
1172         *pr = '+';
1173     mytest_diff(s2, "a\nb\nc\nd\n", res,
1174                 "compare subset (%s) with (abcd)", d2);
1175   }
1176 }
1177
1178 #endif                          /* SIMGRID_TEST */