Logo AND Algorithmique Numérique Distribuée

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