Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
New function to substitute a char to another in a string:
[simgrid.git] / src / xbt / xbt_str.c
1 /* $Id$ */
2
3 /* xbt_str.c - various helping functions to deal with strings               */
4
5 /* Copyright (C) 2005-2008 The SimGrid Team.                                */
6 /* All rights reserved.                                                     */
7
8 /* This program is free software; you can redistribute it and/or modify it
9  * under the terms of the license (GNU LGPL) which comes with this package.
10  */
11
12 #include "xbt/misc.h"
13 #include "xbt/sysdep.h"
14 #include "xbt/str.h" /* headers of these functions */
15 #include "portable.h"
16 #include "xbt/matrix.h" /* for the diff */
17
18 /**  @brief Strip whitespace (or other characters) from the end of a string.
19  *
20  * Strips the whitespaces from the end of s.
21  * By default (when char_list=NULL), these characters get stripped:
22  *
23  *      - " "           (ASCII 32       (0x20)) space.
24  *      - "\t"          (ASCII 9        (0x09)) tab.
25  *      - "\n"          (ASCII 10       (0x0A)) line feed.
26  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
27  *      - "\0"          (ASCII 0        (0x00)) NULL.
28  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
29  *
30  * @param s The string to strip. Modified in place.
31  * @param char_list A string which contains the characters you want to strip.
32  *
33  */
34 void
35 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
80 xbt_str_ltrim( char* s, const char* char_list)
81 {
82   char* cur = s;
83   const char* __char_list = " \t\n\r\x0B";
84   char white_char[256] = {1,0};
85
86   if(!s)
87     return;
88
89   if(!char_list){
90     while(*__char_list) {
91       white_char[(unsigned char)*__char_list++] = 1;
92     }
93   }else{
94     while(*char_list) {
95       white_char[(unsigned char)*char_list++] = 1;
96     }
97   }
98
99   while(*cur && white_char[(unsigned char)*cur])
100     ++cur;
101
102   memmove(s,cur, strlen(cur)+1);
103 }
104
105 /**  @brief Strip whitespace (or other characters) from the end and the begining of a string.
106  *
107  * Strips the whitespaces from both the beginning and the end of s.
108  * By default (when char_list=NULL), these characters get stripped:
109  *
110  *      - " "           (ASCII 32       (0x20)) space.
111  *      - "\t"          (ASCII 9        (0x09)) tab.
112  *      - "\n"          (ASCII 10       (0x0A)) line feed.
113  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
114  *      - "\0"          (ASCII 0        (0x00)) NULL.
115  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
116  *
117  * @param s The string to strip.
118  * @param char_list A string which contains the characters you want to strip.
119  *
120  */
121 void
122 xbt_str_trim(char* s, const char* char_list ){
123
124   if(!s)
125     return;
126
127   xbt_str_rtrim(s,char_list);
128   xbt_str_ltrim(s,char_list);
129 }
130
131 /**  @brief Replace double whitespaces (but no other characters) from the string.
132  *
133  * The function modifies the string so that each time that several spaces appear,
134  * they are replaced by a single space. It will only do so for spaces (ASCII 32, 0x20).
135  *
136  * @param s The string to strip. Modified in place.
137  *
138  */
139 void
140 xbt_str_strip_spaces(char *s) {
141   char *p = s;
142   int   e = 0;
143
144   if (!s)
145     return;
146
147   while (1) {
148     if (!*p)
149       goto end;
150
151     if (*p != ' ')
152       break;
153
154     p++;
155   }
156
157   e = 1;
158
159   do {
160     if (e)
161       *s++ = *p;
162
163     if (!*++p)
164       goto end;
165
166     if (e ^ (*p!=' '))
167       if ((e = !e))
168         *s++ = ' ';
169   } while (1);
170
171   end:
172   *s = '\0';
173 }
174
175 /** @brief Substitutes a char for another in a string
176  *
177  * @param str the string to modify
178  * @param from char to search
179  * @param to char to put instead
180  * @param amount amount of changes to do (=0 means all)
181  */
182 void xbt_str_subst(char *str, char from, char to, int occurence) {
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 Splits a string into a dynar of strings
196  *
197  * @param s: the string to split
198  * @param sep: a string of all chars to consider as separator.
199  *
200  * By default (with sep=NULL), these characters are used as separator:
201  *
202  *      - " "           (ASCII 32       (0x20)) space.
203  *      - "\t"          (ASCII 9        (0x09)) tab.
204  *      - "\n"          (ASCII 10       (0x0A)) line feed.
205  *      - "\r"          (ASCII 13       (0x0D)) carriage return.
206  *      - "\0"          (ASCII 0        (0x00)) NULL.
207  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab.
208  */
209
210 xbt_dynar_t xbt_str_split(const char *s, const char *sep) {
211   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), xbt_free_ref);
212   const char *p, *q;
213   int done;
214   const char* sep_dflt = " \t\n\r\x0B";
215   char is_sep[256] = {1,0};
216
217   /* check what are the separators */
218   memset(is_sep,0,sizeof(is_sep));
219   if (!sep) {
220     while (*sep_dflt)
221       is_sep[(unsigned char) *sep_dflt++] = 1;
222   } else {
223     while (*sep)
224       is_sep[(unsigned char) *sep++] = 1;
225   }
226   is_sep[0] = 1; /* End of string is also separator */
227
228   /* Do the job */
229   p=q=s;
230   done=0;
231
232   if (s[0] == '\0')
233     return res;
234
235   while (!done) {
236     char *topush;
237     while (!is_sep[(unsigned char)*q]) {
238       q++;
239     }
240     if (*q == '\0')
241       done = 1;
242
243     topush=xbt_malloc(q-p+1);
244     memcpy(topush,p,q-p);
245     topush[q - p] = '\0';
246     xbt_dynar_push(res,&topush);
247     p = ++q;
248   }
249
250   return res;
251 }
252
253 /**
254  * \brief This functions splits a string after using another string as separator
255  * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
256  * \return An array of dynars containing the string tokens
257  */
258 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep) {
259   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), xbt_free_ref);
260   int done;
261   const char *p, *q;
262
263   p = q = s;
264   done = 0;
265
266   if (s[0] == '\0')
267     return res;
268   if (sep[0] == '\0') {
269     s = xbt_strdup(s);
270     xbt_dynar_push(res, &s);
271     return res;
272   }
273
274   while (!done) {
275     char *to_push;
276     int v = 0;
277     //get the start of the first occurence of the substring
278     q = strstr(p, sep);
279     //if substring was not found add the entire string
280     if (NULL == q) {
281       v = strlen(p);
282       to_push = malloc(v + 1);
283       memcpy(to_push, p, v);
284       to_push[v] = '\0';
285       xbt_dynar_push(res, &to_push);
286       done = 1;
287     }
288     else {
289       //get the appearance
290       to_push = malloc(q - p + 1);
291       memcpy(to_push, p, q - p);
292       //add string terminator
293       to_push[q - p] = '\0';
294       xbt_dynar_push(res, &to_push);
295       p = q +strlen(sep);
296     }
297   }
298   return res;
299 }
300
301 /** @brief Splits a string into a dynar of strings, taking quotes into account
302  *
303  * It basically does the same argument separation than the shell, where white
304  * spaces can be escaped and where arguments are never splitted within a
305  * quote group.
306  * Several subsequent spaces are ignored (unless within quotes, of course).
307  *
308  */
309
310 xbt_dynar_t xbt_str_split_quoted(const char *s) {
311   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), xbt_free_ref);
312   char *str_to_free; /* we have to copy the string before, to handle backslashes */
313   char *beg, *end; /* pointers around the parsed chunk */
314   int in_simple_quote=0, in_double_quote=0;
315   int done = 0;
316   int ctn = 0; /* Got something in this block */
317
318   if (s[0] == '\0')
319     return res;
320   beg = str_to_free = xbt_strdup(s);
321
322   /* trim leading spaces */
323   xbt_str_ltrim(beg," ");
324   end=beg;
325
326   while (!done) {
327
328
329     switch (*end) {
330       case '\\':
331         ctn = 1;
332         /* Protected char; move it closer */
333         memmove(end,end+1,strlen(end));
334         if (*end=='\0')
335           THROW0(arg_error,0,"String ends with \\");
336         end++; /* Pass the protected char */
337         break;
338
339       case '\'':
340         ctn = 1;
341         if (!in_double_quote) {
342           in_simple_quote = !in_simple_quote;
343           memmove(end,end+1,strlen(end));
344         } else {
345           /* simple quote protected by double ones */
346           end++;
347         }
348         break;
349       case '"':
350         ctn = 1;
351         if (!in_simple_quote) {
352           in_double_quote = !in_double_quote;
353           memmove(end,end+1,strlen(end));
354         } else {
355           /* double quote protected by simple ones */
356           end++;
357         }
358         break;
359
360       case ' ':
361       case '\t':
362       case '\n':
363       case '\0':
364         if (*end == '\0' && (in_simple_quote || in_double_quote)) {
365           THROW2(arg_error,0,
366                  "End of string found while searching for %c in %s",
367                  (in_simple_quote?'\'':'"'),
368                  s);
369         }
370         if (in_simple_quote || in_double_quote) {
371           end++;
372         } else {
373           if (ctn) {
374             /* Found a separator. Push the string if contains something */
375             char *topush=xbt_malloc(end-beg+1);
376             memcpy(topush,beg,end-beg);
377             topush[end - beg] = '\0';
378             xbt_dynar_push(res,&topush);
379           }
380           ctn= 0;
381
382           if (*end == '\0') {
383             done = 1;
384             break;
385           }
386
387           beg=++end;
388           xbt_str_ltrim(beg," ");
389           end=beg;
390         }
391         break;
392
393       default:
394         ctn = 1;
395         end++;
396     }
397   }
398   free(str_to_free);
399   return res;
400 }
401
402 #ifdef SIMGRID_TEST
403 #include "xbt/str.h"
404
405 #define mytest(name, input, expected) \
406   xbt_test_add0(name); \
407   d=xbt_str_split_quoted(input); \
408   s=xbt_str_join(d,"XXX"); \
409   xbt_test_assert3(!strcmp(s,expected),\
410                    "Input (%s) leads to (%s) instead of (%s)", \
411                    input,s,expected);\
412                    free(s); \
413                    xbt_dynar_free(&d);
414
415 XBT_TEST_SUITE("xbt_str","String Handling");
416 XBT_TEST_UNIT("xbt_str_split_quoted",test_split_quoted, "test the function xbt_str_split_quoted") {
417   xbt_dynar_t d;
418   char *s;
419
420   mytest("Empty", "", "");
421   mytest("Basic test", "toto tutu", "totoXXXtutu");
422   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
423   mytest("Protected space", "toto\\ tutu", "toto tutu");
424   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
425   mytest("LTriming", "  toto tatu", "totoXXXtatu");
426   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
427   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
428   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
429   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
430   mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
431   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
432
433 }
434
435 #define mytest_str(name, input, separator, expected) \
436   xbt_test_add0(name); \
437   d=xbt_str_split_str(input, separator); \
438   s=xbt_str_join(d,"XXX"); \
439   xbt_test_assert3(!strcmp(s,expected),\
440                    "Input (%s) leads to (%s) instead of (%s)", \
441                    input,s,expected);\
442                    free(s); \
443                    xbt_dynar_free(&d);
444
445 XBT_TEST_UNIT("xbt_str_split_str",test_split_str, "test the function xbt_str_split_str") {
446   xbt_dynar_t d;
447   char *s;
448
449   mytest_str("Empty string and separator", "", "", "");
450   mytest_str("Empty string", "", "##", "");
451   mytest_str("Empty separator", "toto", "", "toto");
452   mytest_str("String with no separator in it", "toto", "##", "toto");
453   mytest_str("Basic test", "toto##tutu",  "##", "totoXXXtutu");
454 }
455 #endif /* SIMGRID_TEST */
456
457 /** @brief Join a set of strings as a single string */
458
459 char *xbt_str_join(xbt_dynar_t dyn, const char*sep) {
460   int len=1,dyn_len=xbt_dynar_length(dyn);
461   unsigned int cpt;
462   char *cursor;
463   char *res,*p;
464
465   if (!dyn_len)
466     return xbt_strdup("");
467
468   /* compute the length */
469   xbt_dynar_foreach(dyn,cpt,cursor) {
470     len+=strlen(cursor);
471   }
472   len+=strlen(sep)*dyn_len;
473   /* Do the job */
474   res = xbt_malloc(len);
475   p=res;
476   xbt_dynar_foreach(dyn,cpt,cursor) {
477     if ((int)cpt<dyn_len-1)
478       p+=sprintf(p,"%s%s",cursor,sep);
479     else
480       p+=sprintf(p,"%s",cursor);
481   }
482   return res;
483 }
484
485 #if !defined(HAVE_GETLINE) || defined(DOXYGEN)
486 /* prototype here, just in case */
487 long getline(char **buf, size_t *n, FILE *stream);
488
489 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
490  *
491  * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
492  *
493  * getline() reads an entire line from stream, storing the address of the buffer
494  * containing the text into *buf.  The buffer is null-terminated and includes
495  * the newline character, if one was found.
496  *
497  * If *buf is NULL, then getline() will allocate a buffer for storing the line,
498  * which should be freed by the user program.  Alternatively, before calling getline(),
499  * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size.  If the buffer
500  * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n
501  * as necessary.  In either case, on a successful call, *buf and *n will be updated to
502  * reflect the buffer address and allocated size respectively.
503  */
504 long getline(char **buf, size_t *n, FILE *stream) {
505
506   size_t i;
507   int ch;
508
509   if (!*buf) {
510     *buf = xbt_malloc(512);
511     *n = 512;
512   }
513
514   if (feof(stream))
515     return (ssize_t)-1;
516
517   for (i=0; (ch = fgetc(stream)) != EOF; i++)  {
518
519     if (i >= (*n) + 1)
520       *buf = xbt_realloc(*buf, *n += 512);
521
522     (*buf)[i] = ch;
523
524     if ((*buf)[i] == '\n')  {
525       i++;
526       (*buf)[i] = '\0';
527       break;
528     }
529   }
530
531   if (i == *n)
532     *buf = xbt_realloc(*buf, *n += 1);
533
534   (*buf)[i] = '\0';
535
536   return (ssize_t)i;
537 }
538
539 #endif /* HAVE_GETLINE */
540
541 /*
542  * Diff related functions
543  */
544 static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db) {
545   xbt_matrix_t C = xbt_matrix_new(xbt_dynar_length(da),xbt_dynar_length(db),
546                                   sizeof(int),NULL);
547   unsigned long i,j;
548
549   /* Compute the LCS */
550   /*
551     C = array(0..m, 0..n)
552     for i := 0..m
553        C[i,0] = 0
554     for j := 1..n
555        C[0,j] = 0
556     for i := 1..m
557         for j := 1..n
558             if X[i] = Y[j]
559                 C[i,j] := C[i-1,j-1] + 1
560             else:
561                 C[i,j] := max(C[i,j-1], C[i-1,j])
562     return C[m,n]
563    */
564   if (xbt_dynar_length(db) != 0)
565     for (i=0; i<xbt_dynar_length(da); i++)
566       *((int*) xbt_matrix_get_ptr(C,i,0) ) = 0;
567
568   if (xbt_dynar_length(da) != 0)
569     for (j=0; j<xbt_dynar_length(db); j++)
570       *((int*) xbt_matrix_get_ptr(C,0,j) ) = 0;
571
572   for (i=1; i<xbt_dynar_length(da); i++)
573     for (j=1; j<xbt_dynar_length(db); j++) {
574
575       if (!strcmp(xbt_dynar_get_as(da,i,char*), xbt_dynar_get_as(db,j,char*)))
576         *((int*) xbt_matrix_get_ptr(C,i,j) ) = xbt_matrix_get_as(C,i-1,j-1,int) + 1;
577       else
578         *((int*) xbt_matrix_get_ptr(C,i,j) ) = max(xbt_matrix_get_as(C,i  ,j-1,int),
579                                                    xbt_matrix_get_as(C,i-1,j,int));
580     }
581   return C;
582 }
583
584 static void diff_build_diff(xbt_dynar_t res,
585                             xbt_matrix_t C,
586                             xbt_dynar_t da, xbt_dynar_t db,
587                             int i,int j) {
588   char *topush;
589   /* Construct the diff
590   function printDiff(C[0..m,0..n], X[1..m], Y[1..n], i, j)
591     if i > 0 and j > 0 and X[i] = Y[j]
592         printDiff(C, X, Y, i-1, j-1)
593         print "  " + X[i]
594     else
595         if j > 0 and (i = 0 or C[i,j-1] >= C[i-1,j])
596             printDiff(C, X, Y, i, j-1)
597             print "+ " + Y[j]
598         else if i > 0 and (j = 0 or C[i,j-1] < C[i-1,j])
599             printDiff(C, X, Y, i-1, j)
600             print "- " + X[i]
601    */
602
603   if (i>=0 && j >= 0 && !strcmp(xbt_dynar_get_as(da,i,char*),
604                                 xbt_dynar_get_as(db,j,char*))) {
605     diff_build_diff(res,C,da,db,i-1,j-1);
606     topush = bprintf("  %s",xbt_dynar_get_as(da,i,char*));
607     xbt_dynar_push(res, &topush);
608   } else if (j>=0 &&
609       (i<=0 ||j==0|| xbt_matrix_get_as(C,i,j-1,int) >= xbt_matrix_get_as(C,i-1,j,int))) {
610     diff_build_diff(res,C,da,db,i,j-1);
611     topush = bprintf("+ %s",xbt_dynar_get_as(db,j,char*));
612     xbt_dynar_push(res,&topush);
613   } else if (i>=0 &&
614       (j<=0 || xbt_matrix_get_as(C,i,j-1,int) < xbt_matrix_get_as(C,i-1,j,int))) {
615     diff_build_diff(res,C,da,db,i-1,j);
616     topush = bprintf("- %s",xbt_dynar_get_as(da,i,char*));
617     xbt_dynar_push(res,&topush);
618   } else if (i<=0 && j<=0) {
619     return;
620   } else {
621     THROW2(arg_error,0,"Invalid values: i=%d, j=%d",i,j);
622   }
623
624 }
625
626 /** @brief Compute the unified diff of two strings */
627 char *xbt_str_diff(char *a, char *b) {
628   xbt_dynar_t da = xbt_str_split(a, "\n");
629   xbt_dynar_t db = xbt_str_split(b, "\n");
630
631   xbt_matrix_t C = diff_build_LCS(da,db);
632   xbt_dynar_t diff = xbt_dynar_new(sizeof(char*),xbt_free_ref);
633   char *res=NULL;
634
635   diff_build_diff(diff, C, da,db, xbt_dynar_length(da)-1, xbt_dynar_length(db)-1);
636   /* Clean empty lines at the end */
637   while (xbt_dynar_length(diff) > 0) {
638     char *str;
639     xbt_dynar_pop(diff,&str);
640     if (str[0]=='\0' || !strcmp(str,"  ")) {
641       free(str);
642     } else {
643       xbt_dynar_push(diff,&str);
644       break;
645     }
646   }
647   res = xbt_str_join(diff, "\n");
648
649   xbt_dynar_free(&da);
650   xbt_dynar_free(&db);
651   xbt_dynar_free(&diff);
652   xbt_matrix_free(C);
653
654   return res;
655 }
656