Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Minor optimization.
[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-2007 Malek Cherier, Martin Quinson.                   */
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 Splits a string into a dynar of strings 
176  * 
177  * @param s: the string to split
178  * @param sep: a string of all chars to consider as separator.
179  *
180  * By default (with sep=NULL), these characters are used as separator: 
181  *      
182  *      - " "           (ASCII 32       (0x20)) space. 
183  *      - "\t"          (ASCII 9        (0x09)) tab. 
184  *      - "\n"          (ASCII 10       (0x0A)) line feed. 
185  *      - "\r"          (ASCII 13       (0x0D)) carriage return. 
186  *      - "\0"          (ASCII 0        (0x00)) NULL. 
187  *      - "\x0B"        (ASCII 11       (0x0B)) vertical tab. 
188  */
189
190 xbt_dynar_t xbt_str_split(const char *s, const char *sep) {
191   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), xbt_free_ref);
192   const char *p, *q;
193   int done;
194   const char* sep_dflt = " \t\n\r\x0B";
195   char is_sep[256] = {1,0};
196
197   /* check what are the separators */
198   memset(is_sep,0,sizeof(is_sep));
199   if (!sep) {
200     while (*sep_dflt)
201       is_sep[(unsigned char) *sep_dflt++] = 1;
202   } else {
203     while (*sep)
204       is_sep[(unsigned char) *sep++] = 1;
205   }
206   is_sep[0] = 1; /* End of string is also separator */
207    
208   /* Do the job */
209   p=q=s; 
210   done=0;
211
212   if (s[0] == '\0')
213     return res;
214
215   while (!done) {
216     char *topush;
217     while (!is_sep[(unsigned char)*q]) {
218       q++;
219     }
220     if (*q == '\0')
221       done = 1;
222
223     topush=xbt_malloc(q-p+1);
224     memcpy(topush,p,q-p);
225     topush[q - p] = '\0';
226     xbt_dynar_push(res,&topush);
227     p = ++q;
228   }
229
230   return res;
231 }
232
233 /**
234  * \brief This functions splits a string after using another string as separator
235  * For example A!!B!!C splitted after !! will return the dynar {A,B,C}
236  * \return An array of dynars containing the string tokens
237 */
238 xbt_dynar_t xbt_str_split_str(const char *s, const char *sep) {
239   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), xbt_free_ref);
240   int done;
241   const char *p, *q;
242  
243   p = q = s;
244   done = 0;
245  
246   if (s[0] == '\0') 
247     return res;
248   if (sep[0] == '\0') {
249     s = xbt_strdup(s);
250     xbt_dynar_push(res, &s);
251     return res;
252   }
253
254   while (!done) {
255     char *to_push;
256     int v = 0;
257     //get the start of the first occurence of the substring
258     q = strstr(p, sep);
259     //if substring was not found add the entire string
260     if (NULL == q) {
261       v = strlen(p);
262       to_push = malloc(v + 1);
263       memcpy(to_push, p, v);
264       to_push[v] = '\0';
265       xbt_dynar_push(res, &to_push);
266       done = 1;
267     }
268     else {
269       //get the appearance
270       to_push = malloc(q - p + 1);
271       memcpy(to_push, p, q - p);
272       //add string terminator
273       to_push[q - p] = '\0';
274           xbt_dynar_push(res, &to_push);
275       p = q +strlen(sep);
276     }
277   }
278   return res;
279 }
280
281 /** @brief Splits a string into a dynar of strings, taking quotes into account
282  * 
283  * It basically does the same argument separation than the shell, where white 
284  * spaces can be escaped and where arguments are never splitted within a 
285  * quote group.
286  * Several subsequent spaces are ignored (unless within quotes, of course).
287  *
288  */
289
290 xbt_dynar_t xbt_str_split_quoted(const char *s) {
291   xbt_dynar_t res = xbt_dynar_new(sizeof(char*), xbt_free_ref);
292   char *str; /* we have to copy the string before, to handle backslashes */
293   char *beg, *end; /* pointers around the parsed chunk */
294   int in_simple_quote=0, in_double_quote=0;
295   int done = 0;
296   int ctn = 0; /* Got something in this block */
297
298   if (s[0] == '\0')
299     return res;
300   beg = str = xbt_strdup(s);
301    
302   /* trim leading spaces */
303   xbt_str_ltrim(beg," ");
304   end=beg;
305      
306   while (!done) {
307     
308        
309     switch (*end) {
310     case '\\':
311       ctn = 1;
312       /* Protected char; move it closer */
313       memmove(end,end+1,strlen(end)); 
314       if (*end=='\0')
315         THROW0(arg_error,0,"String ends with \\");
316       end++; /* Pass the protected char */
317       break;
318
319     case '\'':
320       ctn = 1;
321       if (!in_double_quote) { 
322         in_simple_quote = !in_simple_quote;
323         memmove(end,end+1,strlen(end));
324       } else {         
325         /* simple quote protected by double ones */
326         end++;
327       }
328       break;
329     case '"':
330       ctn = 1;
331       if (!in_simple_quote) { 
332         in_double_quote = !in_double_quote;
333         memmove(end,end+1,strlen(end));
334       } else {         
335         /* double quote protected by simple ones */
336         end++;
337       }   
338       break;
339
340     case ' ':
341     case '\t':
342     case '\n':
343     case '\0':
344       if (*end == '\0' && (in_simple_quote || in_double_quote)) {
345         THROW2(arg_error,0,
346                "End of string found while searching for %c in %s",
347                (in_simple_quote?'\'':'"'),
348                s);
349       }
350       if (in_simple_quote || in_double_quote) {
351         end++;
352       } else {  
353         if (ctn) {
354           /* Found a separator. Push the string if contains something */
355           char *topush=xbt_malloc(end-beg+1);
356           memcpy(topush,beg,end-beg);
357           topush[end - beg] = '\0';
358           xbt_dynar_push(res,&topush);
359         }
360         ctn= 0;
361
362         if (*end == '\0') {
363           done = 1;
364           break;
365         }
366         
367         beg=++end;
368         xbt_str_ltrim(beg," ");
369         end=beg;
370       }   
371       break;
372       
373     default:
374       ctn = 1;
375       end++;
376     }       
377   }
378   free(str);
379   return res;
380 }
381
382 #ifdef SIMGRID_TEST
383 #include "xbt/str.h"
384
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*),xbt_free_ref);
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 }