Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
edd062b38f1a15d4e2f3708fa210ce33f040e2e8
[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 /**
237  * \brief This functions splits a string after using another string as separator
238  * For example A##B##C splitted after ## will return the dynar {A,B,C}
239  * \return An array of dynars containing the string tokens
240 */
241 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep) {
242   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), free_string);
243   int done;
244   const char *p, *q;
245  
246   p = q = s;
247   done = 0;
248  
249   if (s[0] == '\0') 
250     return res;
251   if (sep[0] == '\0') {
252     xbt_dynar_push(res, &s);
253     return res;
254   }
255
256   while (!done) {
257     char *to_push;
258     int v = 0;
259     //get the start of the first occurence of the substring
260     q = strstr(p, sep);
261     //if substring was not found add the entire string
262     if (NULL == q) {
263       v = strlen(p);
264       to_push = malloc(v + 1);
265       memcpy(to_push, p, v);
266       to_push[v] = '\0';
267       xbt_dynar_push(res, &to_push);
268       done = 1;
269     }
270     else {
271       //get the appearance
272       to_push = malloc(q - p + 1);
273       memcpy(to_push, p, q - p);
274       //add string terminator
275       to_push[q - p] = '\0';
276           xbt_dynar_push(res, &to_push);
277       p = q +strlen(sep);
278     }
279   }
280   return res;
281 }
282
283 /** @brief Splits a string into a dynar of strings, taking quotes into account
284  * 
285  * It basically does the same argument separation than the shell, where white 
286  * spaces can be escaped and where arguments are never splitted within a 
287  * quote group.
288  * Several subsequent spaces are ignored (unless within quotes, of course).
289  *
290  */
291
292 xbt_dynar_t xbt_str_split_quoted(const char *s) {
293   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), free_string);
294   char *str; /* we have to copy the string before, to handle backslashes */
295   char *beg, *end; /* pointers around the parsed chunk */
296   int in_simple_quote=0, in_double_quote=0;
297   int done = 0;
298   int ctn = 0; /* Got something in this block */
299
300   if (s[0] == '\0')
301     return res;
302   beg = str = xbt_strdup(s);
303    
304   /* trim leading spaces */
305   xbt_str_ltrim(beg," ");
306   end=beg;
307      
308   while (!done) {
309     
310        
311     switch (*end) {
312     case '\\':
313       ctn = 1;
314       /* Protected char; move it closer */
315       memmove(end,end+1,strlen(end)); 
316       if (*end=='\0')
317         THROW0(arg_error,0,"String ends with \\");
318       end++; /* Pass the protected char */
319       break;
320
321     case '\'':
322       ctn = 1;
323       if (!in_double_quote) { 
324         in_simple_quote = !in_simple_quote;
325         memmove(end,end+1,strlen(end));
326       } else {         
327         /* simple quote protected by double ones */
328         end++;
329       }
330       break;
331     case '"':
332       ctn = 1;
333       if (!in_simple_quote) { 
334         in_double_quote = !in_double_quote;
335         memmove(end,end+1,strlen(end));
336       } else {         
337         /* double quote protected by simple ones */
338         end++;
339       }   
340       break;
341
342     case ' ':
343     case '\t':
344     case '\n':
345     case '\0':
346       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
347         THROW2(arg_error,0,
348                "End of string found while searching for %c in %s",
349                (in_simple_quote?'\'':'"'),
350                s);
351       }
352       if (in_simple_quote || in_double_quote) {
353         end++;
354       } else {  
355         if (ctn) {
356           /* Found a separator. Push the string if contains something */
357           char *topush=xbt_malloc(end-beg+1);
358           memcpy(topush,beg,end-beg);
359           topush[end - beg] = '\0';
360           xbt_dynar_push(res,&topush);
361         }
362         ctn= 0;
363
364         if (*end == '\0') {
365           done = 1;
366           break;
367         }
368         
369         beg=++end;
370         xbt_str_ltrim(beg," ");
371         end=beg;
372       }   
373       break;
374       
375     default:
376       ctn = 1;
377       end++;
378     }       
379   }
380   free(str);
381   return res;
382 }
383
384 #ifdef SIMGRID_TEST
385 #define mytest(name, input, expected) \
386   xbt_test_add0(name); \
387   d=xbt_str_split_quoted(input); \
388   s=xbt_str_join(d,"XXX"); \
389   xbt_test_assert3(!strcmp(s,expected),\
390                    "Input (%s) leads to (%s) instead of (%s)", \
391                    input,s,expected);\
392   free(s); \
393   xbt_dynar_free(&d);
394
395 XBT_TEST_SUITE("xbt_str","String Handling");
396 XBT_TEST_UNIT("xbt_str_split_quoted",test_split_quoted, "test the function xbt_str_split_quoted") {
397   xbt_dynar_t d;
398   char *s;
399
400   mytest("Empty", "", "");
401   mytest("Basic test", "toto tutu", "totoXXXtutu");
402   mytest("Useless backslashes", "\\t\\o\\t\\o \\t\\u\\t\\u", "totoXXXtutu");
403   mytest("Protected space", "toto\\ tutu", "toto tutu");
404   mytest("Several spaces", "toto   tutu", "totoXXXtutu");
405   mytest("LTriming", "  toto tatu", "totoXXXtatu");
406   mytest("Triming", "  toto   tutu  ", "totoXXXtutu");
407   mytest("Single quotes", "'toto tutu' tata", "toto tutuXXXtata");
408   mytest("Double quotes", "\"toto tutu\" tata", "toto tutuXXXtata");
409   mytest("Mixed quotes", "\"toto' 'tutu\" tata", "toto' 'tutuXXXtata");
410   mytest("Backslashed quotes", "\\'toto tutu\\' tata", "'totoXXXtutu'XXXtata");
411   mytest("Backslashed quotes + quotes", "'toto \\'tutu' tata", "toto 'tutuXXXtata");
412
413 }
414
415 #define mytest_str(name, input, separator, expected) \
416   xbt_test_add0(name); \
417   d=xbt_str_split_str(input, separator); \
418   s=xbt_str_join(d,"XXX"); \
419   xbt_test_assert3(!strcmp(s,expected),\
420                    "Input (%s) leads to (%s) instead of (%s)", \
421                    input,s,expected);\
422   free(s); \
423   xbt_dynar_free(&d);
424
425 XBT_TEST_UNIT("xbt_str_split_str",test_split_str, "test the function xbt_str_split_str") {
426   xbt_dynar_t d;
427   char *s;
428
429   mytest_str("Empty string and separator", "", "", "");
430   mytest_str("Empty string", "", "##", "");
431   mytest_str("Empty separator", "toto", "", "toto");
432   mytest_str("String with no separator in it", "toto", "##", "toto");
433   mytest_str("Basic test", "toto##tutu",  "##", "totoXXXtutu");
434 }
435 #endif /* SIMGRID_TEST */
436    
437 /** @brief Join a set of strings as a single string */
438
439 char *xbt_str_join(xbt_dynar_t dyn, const char*sep) {
440   int len=1,dyn_len=xbt_dynar_length(dyn);
441   unsigned int cpt;
442   char *cursor;
443   char *res,*p;
444   
445   if (!dyn_len)
446     return xbt_strdup("");
447
448   /* compute the length */
449   xbt_dynar_foreach(dyn,cpt,cursor) {
450     len+=strlen(cursor);
451   }
452   len+=strlen(sep)*dyn_len;
453   /* Do the job */
454   res = xbt_malloc(len);
455   p=res;
456   xbt_dynar_foreach(dyn,cpt,cursor) {
457     if ((int)cpt<dyn_len-1)
458       p+=sprintf(p,"%s%s",cursor,sep);    
459     else
460       p+=sprintf(p,"%s",cursor);    
461   }
462   return res;
463 }
464    
465 #if !defined(HAVE_GETLINE) || defined(DOXYGEN)
466 /* prototype here, just in case */
467 long getline(char **buf, size_t *n, FILE *stream);
468
469 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
470  * 
471  * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
472  * 
473  * getline() reads an entire line from stream, storing the address of the buffer 
474  * containing the text into *buf.  The buffer is null-terminated and includes 
475  * the newline character, if one was found.
476  * 
477  * If *buf is NULL, then getline() will allocate a buffer for storing the line, 
478  * which should be freed by the user program.  Alternatively, before calling getline(), 
479  * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size.  If the buffer 
480  * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n 
481  * as necessary.  In either case, on a successful call, *buf and *n will be updated to 
482  * reflect the buffer address and allocated size respectively.
483  */
484 long getline(char **buf, size_t *n, FILE *stream) {
485    
486    size_t i;
487    int ch;
488    
489    if (!*buf) {
490      *buf = xbt_malloc(512);
491      *n = 512;
492    }
493    
494    if (feof(stream))
495      return (ssize_t)-1;
496    
497    for (i=0; (ch = fgetc(stream)) != EOF; i++)  {
498         
499       if (i >= (*n) + 1)
500         *buf = xbt_realloc(*buf, *n += 512);
501         
502       (*buf)[i] = ch;
503         
504       if ((*buf)[i] == '\n')  {
505          i++;
506          (*buf)[i] = '\0';
507          break;
508       }      
509    }
510       
511    if (i == *n) 
512      *buf = xbt_realloc(*buf, *n += 1);
513    
514    (*buf)[i] = '\0';
515
516    return (ssize_t)i;
517 }
518
519 #endif /* HAVE_GETLINE */
520
521 /*
522  * Diff related functions 
523  */
524 static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db) {
525   xbt_matrix_t C = xbt_matrix_new(xbt_dynar_length(da),xbt_dynar_length(db),
526                                   sizeof(int),NULL); 
527   unsigned long i,j;
528
529   /* Compute the LCS */
530   /*
531     C = array(0..m, 0..n)
532     for i := 0..m
533        C[i,0] = 0
534     for j := 1..n
535        C[0,j] = 0
536     for i := 1..m
537         for j := 1..n
538             if X[i] = Y[j]
539                 C[i,j] := C[i-1,j-1] + 1
540             else:
541                 C[i,j] := max(C[i,j-1], C[i-1,j])
542     return C[m,n]
543           */
544   if (xbt_dynar_length(db) != 0)
545     for (i=0; i<xbt_dynar_length(da); i++) 
546       *((int*) xbt_matrix_get_ptr(C,i,0) ) = 0;
547
548   if (xbt_dynar_length(da) != 0)
549     for (j=0; j<xbt_dynar_length(db); j++) 
550       *((int*) xbt_matrix_get_ptr(C,0,j) ) = 0;
551
552   for (i=1; i<xbt_dynar_length(da); i++) 
553     for (j=1; j<xbt_dynar_length(db); j++) {
554
555       if (!strcmp(xbt_dynar_get_as(da,i,char*), xbt_dynar_get_as(db,j,char*)))
556         *((int*) xbt_matrix_get_ptr(C,i,j) ) = xbt_matrix_get_as(C,i-1,j-1,int) + 1;
557       else
558         *((int*) xbt_matrix_get_ptr(C,i,j) ) = max(xbt_matrix_get_as(C,i  ,j-1,int),
559                                                    xbt_matrix_get_as(C,i-1,j,int));
560     }
561   return C;
562 }
563
564 static void diff_build_diff(xbt_dynar_t res,
565                             xbt_matrix_t C,
566                             xbt_dynar_t da, xbt_dynar_t db,
567                             int i,int j) {
568   char *topush;
569   /* Construct the diff 
570   function printDiff(C[0..m,0..n], X[1..m], Y[1..n], i, j)
571     if i > 0 and j > 0 and X[i] = Y[j]
572         printDiff(C, X, Y, i-1, j-1)
573         print "  " + X[i]
574     else
575         if j > 0 and (i = 0 or C[i,j-1] >= C[i-1,j])
576             printDiff(C, X, Y, i, j-1)
577             print "+ " + Y[j]
578         else if i > 0 and (j = 0 or C[i,j-1] < C[i-1,j])
579             printDiff(C, X, Y, i-1, j)
580             print "- " + X[i]
581   */
582
583   if (i>=0 && j >= 0 && !strcmp(xbt_dynar_get_as(da,i,char*),
584                                 xbt_dynar_get_as(db,j,char*))) {
585     diff_build_diff(res,C,da,db,i-1,j-1);
586     topush = bprintf("  %s",xbt_dynar_get_as(da,i,char*));
587     xbt_dynar_push(res, &topush);
588   } else if (j>=0 && 
589              (i<=0 ||j==0|| xbt_matrix_get_as(C,i,j-1,int) >= xbt_matrix_get_as(C,i-1,j,int))) {
590     diff_build_diff(res,C,da,db,i,j-1);
591     topush = bprintf("+ %s",xbt_dynar_get_as(db,j,char*));
592     xbt_dynar_push(res,&topush);
593   } else if (i>=0 && 
594              (j<=0 || xbt_matrix_get_as(C,i,j-1,int) < xbt_matrix_get_as(C,i-1,j,int))) {
595     diff_build_diff(res,C,da,db,i-1,j);
596     topush = bprintf("- %s",xbt_dynar_get_as(da,i,char*));
597     xbt_dynar_push(res,&topush);        
598   } else if (i<=0 && j<=0) {
599     return;
600   } else {
601     THROW2(arg_error,0,"Invalid values: i=%d, j=%d",i,j);
602   }
603    
604 }
605
606 /** @brief Compute the unified diff of two strings */
607 char *xbt_str_diff(char *a, char *b) {
608   xbt_dynar_t da = xbt_str_split(a, "\n");
609   xbt_dynar_t db = xbt_str_split(b, "\n");
610
611   xbt_matrix_t C = diff_build_LCS(da,db);
612   xbt_dynar_t diff = xbt_dynar_new(sizeof(char*),free_string);
613   char *res=NULL;
614   
615   diff_build_diff(diff, C, da,db, xbt_dynar_length(da)-1, xbt_dynar_length(db)-1);
616   /* Clean empty lines at the end */
617   while (xbt_dynar_length(diff) > 0) {
618      char *str;
619      xbt_dynar_pop(diff,&str);
620      if (str[0]=='\0' || !strcmp(str,"  ")) {
621         free(str);
622      } else {
623         xbt_dynar_push(diff,&str);
624         break;
625      }     
626   }   
627   res = xbt_str_join(diff, "\n");
628
629   xbt_dynar_free(&da);
630   xbt_dynar_free(&db);
631   xbt_dynar_free(&diff);
632   xbt_matrix_free(C);
633   
634   return res;
635 }