Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
document xbt_str
[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));
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 Join a set of strings as a single string */
237
238 char *xbt_str_join(xbt_dynar_t dyn, const char*sep) {
239   int len=2;
240   int cpt;
241   char *cursor;
242   char *res,*p;
243   /* compute the length */
244   xbt_dynar_foreach(dyn,cpt,cursor) {
245     len+=strlen(cursor);
246   }
247   len+=strlen(sep)*(xbt_dynar_length(dyn));
248   /* Do the job */
249   res = xbt_malloc(len);
250   p=res;
251   xbt_dynar_foreach(dyn,cpt,cursor) {
252     p+=sprintf(p,"%s%s",cursor,sep);    
253   }
254   return res;
255 }
256    
257 #if !defined(HAVE_GETLINE) || defined(DOXYGEN)
258 /** @brief Get a single line from the stream (reimplementation of the GNU getline)
259  * 
260  * This is a redefinition of the GNU getline function, used on platforms where it does not exists.
261  * 
262  * getline() reads an entire line from stream, storing the address of the buffer 
263  * containing the text into *buf.  The buffer is null-terminated and includes 
264  * the newline character, if one was found.
265  * 
266  * If *buf is NULL, then getline() will allocate a buffer for storing the line, 
267  * which should be freed by the user program.  Alternatively, before calling getline(), 
268  * *buf can contain a pointer to a malloc()-allocated buffer *n bytes in size.  If the buffer 
269  * is not large enough to hold the line, getline() resizes it with realloc(), updating *buf and *n 
270  * as necessary.  In either case, on a successful call, *buf and *n will be updated to 
271  * reflect the buffer address and allocated size respectively.
272  */
273 long getline(char **buf, size_t *n, FILE *stream) {
274    
275    int i, ch;
276    
277    if (!*buf) {
278      *buf = xbt_malloc(512);
279      *n = 512;
280    }
281    
282    if (feof(stream))
283      return (ssize_t)-1;
284    
285    for (i=0; (ch = fgetc(stream)) != EOF; i++)  {
286         
287       if (i >= (*n) + 1)
288         *buf = xbt_realloc(*buf, *n += 512);
289         
290       (*buf)[i] = ch;
291         
292       if ((*buf)[i] == '\n')  {
293          i++;
294          (*buf)[i] = '\0';
295          break;
296       }      
297    }
298       
299    if (i == *n) 
300      *buf = xbt_realloc(*buf, *n += 1);
301    
302    (*buf)[i] = '\0';
303
304    return (ssize_t)i;
305 }
306
307 #endif /* HAVE_GETLINE */
308
309 /*
310  * Diff related functions 
311  */
312 static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db) {
313   xbt_matrix_t C = xbt_matrix_new(xbt_dynar_length(da),xbt_dynar_length(db),
314                                   sizeof(int),NULL); 
315   int i,j;
316   /* Compute the LCS */
317   /*
318     C = array(0..m, 0..n)
319     for i := 0..m
320        C[i,0] = 0
321     for j := 1..n
322        C[0,j] = 0
323     for i := 1..m
324         for j := 1..n
325             if X[i] = Y[j]
326                 C[i,j] := C[i-1,j-1] + 1
327             else:
328                 C[i,j] := max(C[i,j-1], C[i-1,j])
329     return C[m,n]
330           */
331   for (i=0; i<xbt_dynar_length(da); i++) 
332     *((int*) xbt_matrix_get_ptr(C,i,0) ) = 0;
333
334   for (j=0; j<xbt_dynar_length(db); j++) 
335     *((int*) xbt_matrix_get_ptr(C,0,j) ) = 0;
336
337   for (i=1; i<xbt_dynar_length(da); i++) 
338     for (j=1; j<xbt_dynar_length(db); j++) {
339
340       if (!strcmp(xbt_dynar_get_as(da,i,char*), xbt_dynar_get_as(db,j,char*)))
341         *((int*) xbt_matrix_get_ptr(C,i,j) ) = xbt_matrix_get_as(C,i-1,j-1,int) + 1;
342       else
343         *((int*) xbt_matrix_get_ptr(C,i,j) ) = max(xbt_matrix_get_as(C,i  ,j-1,int),
344                                                    xbt_matrix_get_as(C,i-1,j,int));
345     }
346   return C;
347 }
348
349 static void diff_build_diff(xbt_dynar_t res,
350                             xbt_matrix_t C,
351                             xbt_dynar_t da, xbt_dynar_t db,
352                             int i,int j) {
353   char *topush;
354   /* Construct the diff 
355   function printDiff(C[0..m,0..n], X[1..m], Y[1..n], i, j)
356     if i > 0 and j > 0 and X[i] = Y[j]
357         printDiff(C, X, Y, i-1, j-1)
358         print "  " + X[i]
359     else
360         if j > 0 and (i = 0 or C[i,j-1] >= C[i-1,j])
361             printDiff(C, X, Y, i, j-1)
362             print "+ " + Y[j]
363         else if i > 0 and (j = 0 or C[i,j-1] < C[i-1,j])
364             printDiff(C, X, Y, i-1, j)
365             print "- " + X[i]
366   */
367
368   if (i>=0 && j >= 0 && !strcmp(xbt_dynar_get_as(da,i,char*),
369                                 xbt_dynar_get_as(db,j,char*))) {
370     diff_build_diff(res,C,da,db,i-1,j-1);
371     topush = bprintf("  %s",xbt_dynar_get_as(da,i,char*));
372     xbt_dynar_push(res, &topush);
373   } else if (j>=0 && 
374              (i<=0 || xbt_matrix_get_as(C,i,j-1,int) >= xbt_matrix_get_as(C,i-1,j,int))) {
375     diff_build_diff(res,C,da,db,i,j-1);
376     topush = bprintf("+ %s",xbt_dynar_get_as(db,j,char*));
377     xbt_dynar_push(res,&topush);
378   } else if (i>=0 && 
379              (j<=0 || xbt_matrix_get_as(C,i,j-1,int) < xbt_matrix_get_as(C,i-1,j,int))) {
380     diff_build_diff(res,C,da,db,i-1,j);
381     topush = bprintf("- %s",xbt_dynar_get_as(da,i,char*));
382     xbt_dynar_push(res,&topush);        
383   } else if (i<=0 && j<=0) {
384     return;
385   } else {
386     THROW2(arg_error,0,"Invalid values: i=%d, j=%d",i,j);
387   }
388    
389 }
390
391 /** @brief Compute the unified diff of two strings */
392 char *xbt_str_diff(char *a, char *b) {
393   xbt_dynar_t da = xbt_str_split(a, "\n");
394   xbt_dynar_t db = xbt_str_split(b, "\n");
395
396   xbt_matrix_t C = diff_build_LCS(da,db);
397   xbt_dynar_t diff = xbt_dynar_new(sizeof(char*),free_string);
398   char *res=NULL;
399   
400   diff_build_diff(diff, C, da,db, xbt_dynar_length(da)-1, xbt_dynar_length(db)-1);
401   /* Clean empty lines at the end */
402   while (xbt_dynar_length(diff) > 0) {
403      char *str;
404      xbt_dynar_pop(diff,&str);
405      if (str[0]=='\0' || !strcmp(str,"  ")) {
406         free(str);
407      } else {
408         xbt_dynar_push(diff,&str);
409         break;
410      }     
411   }   
412   res = xbt_str_join(diff, "\n");
413
414   xbt_dynar_free(&da);
415   xbt_dynar_free(&db);
416   xbt_dynar_free(&diff);
417   xbt_matrix_free(C);
418   
419   return res;
420 }