Logo AND Algorithmique Numérique Distribuée

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