Logo AND Algorithmique Numérique Distribuée

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