Code beautification with uncrustify
[alexxy/gromacs.git] / src / gromacs / gmxlib / string2.c
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  *                        VERSION 3.2.0
10  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12  * Copyright (c) 2001-2004, The GROMACS development team,
13  * check out http://www.gromacs.org for more information.
14
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version 2
18  * of the License, or (at your option) any later version.
19  *
20  * If you want to redistribute modifications, please consider that
21  * scientific software is very special. Version control is crucial -
22  * bugs must be traceable. We will be happy to consider code for
23  * inclusion in the official distribution, but derived work must not
24  * be called official GROMACS. Details are found in the README & COPYING
25  * files - if they are missing, get the official version at www.gromacs.org.
26  *
27  * To help us fund GROMACS development, we humbly ask that you cite
28  * the papers on the package - you can find them in the top README file.
29  *
30  * For more info, check our website at http://www.gromacs.org
31  *
32  * And Hey:
33  * GROningen Mixture of Alchemy and Childrens' Stories
34  */
35 /* This file is completely threadsafe - keep it that way! */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39 #include "gromacs/utility/gmx_header_config.h"
40
41 #ifdef GMX_CRAY_XT3
42 #undef HAVE_PWD_H
43 #endif
44
45 #include <stdio.h>
46 #include <ctype.h>
47 #include <stdlib.h>
48 #include <errno.h>
49 #include <sys/types.h>
50 #include <time.h>
51
52 #ifdef HAVE_SYS_TIME_H
53 #include <sys/time.h>
54 #endif
55
56 #ifdef HAVE_UNISTD_H
57 #include <unistd.h>
58 #endif
59
60 #ifdef HAVE_PWD_H
61 #include <pwd.h>
62 #endif
63 #include <time.h>
64 #include <assert.h>
65
66 #include "typedefs.h"
67 #include "smalloc.h"
68 #include "gmx_fatal.h"
69 #include "macros.h"
70 #include "string2.h"
71 #include "futil.h"
72
73 int continuing(char *s)
74 {
75     int sl;
76     assert(s);
77
78     rtrim(s);
79     sl = strlen(s);
80     if ((sl > 0) && (s[sl-1] == CONTINUE))
81     {
82         s[sl-1] = 0;
83         return TRUE;
84     }
85     else
86     {
87         return FALSE;
88     }
89 }
90
91
92
93 char *fgets2(char *line, int n, FILE *stream)
94 {
95     char *c;
96     if (fgets(line, n, stream) == NULL)
97     {
98         return NULL;
99     }
100     if ((c = strchr(line, '\n')) != NULL)
101     {
102         *c = '\0';
103     }
104     else
105     {
106         /* A line not ending in a newline can only occur at the end of a file,
107          * or because of n being too small.
108          * Since both cases occur very infrequently, we can check for EOF.
109          */
110         if (!gmx_eof(stream))
111         {
112             gmx_fatal(FARGS, "An input file contains a line longer than %d characters, while the buffer passed to fgets2 has size %d. The line starts with: '%20.20s'", n, n, line);
113         }
114     }
115     if ((c = strchr(line, '\r')) != NULL)
116     {
117         *c = '\0';
118     }
119
120     return line;
121 }
122
123 void strip_comment (char *line)
124 {
125     char *c;
126
127     if (!line)
128     {
129         return;
130     }
131
132     /* search for a comment mark and replace it by a zero */
133     if ((c = strchr(line, COMMENTSIGN)) != NULL)
134     {
135         (*c) = 0;
136     }
137 }
138
139 void upstring (char *str)
140 {
141     int i;
142
143     for (i = 0; (i < (int)strlen(str)); i++)
144     {
145         str[i] = toupper(str[i]);
146     }
147 }
148
149 void ltrim (char *str)
150 {
151     char *tr;
152     int   i, c;
153
154     if (NULL == str)
155     {
156         return;
157     }
158
159     c = 0;
160     while (('\0' != str[c]) && isspace(str[c]))
161     {
162         c++;
163     }
164     if (c > 0)
165     {
166         for (i = c; ('\0' != str[i]); i++)
167         {
168             str[i-c] = str[i];
169         }
170         str[i-c] = '\0';
171     }
172 }
173
174 void rtrim (char *str)
175 {
176     int nul;
177
178     if (NULL == str)
179     {
180         return;
181     }
182
183     nul = strlen(str)-1;
184     while ((nul > 0) && ((str[nul] == ' ') || (str[nul] == '\t')) )
185     {
186         str[nul] = '\0';
187         nul--;
188     }
189 }
190
191 void trim (char *str)
192 {
193     ltrim (str);
194     rtrim (str);
195 }
196
197 char *
198 gmx_ctime_r(const time_t *clock, char *buf, int n)
199 {
200     char tmpbuf[STRLEN];
201
202 #ifdef GMX_NATIVE_WINDOWS
203     /* Windows */
204     ctime_s( tmpbuf, STRLEN, clock );
205 #elif (defined(__sun))
206     /*Solaris*/
207     ctime_r(clock, tmpbuf, n);
208 #else
209     ctime_r(clock, tmpbuf);
210 #endif
211     strncpy(buf, tmpbuf, n-1);
212     buf[n-1] = '\0';
213
214     return buf;
215 }
216
217 void nice_header (FILE *out, const char *fn)
218 {
219     const char    *unk = "onbekend";
220     time_t         clock;
221     const char    *user = unk;
222     int            gh;
223 #ifdef HAVE_PWD_H
224     uid_t          uid;
225 #else
226     int            uid;
227 #endif
228     char           buf[256] = "";
229     char           timebuf[STRLEN];
230 #ifdef HAVE_PWD_H
231     struct passwd *pw;
232 #endif
233
234     /* Print a nice header above the file */
235     time(&clock);
236     fprintf (out, "%c\n", COMMENTSIGN);
237     fprintf (out, "%c\tFile '%s' was generated\n", COMMENTSIGN, fn ? fn : unk);
238
239 #ifdef HAVE_PWD_H
240     uid  = getuid();
241     pw   = getpwuid(uid);
242     gh   = gethostname(buf, 255);
243     user = pw->pw_name;
244 #else
245     uid = 0;
246     gh  = -1;
247 #endif
248
249     gmx_ctime_r(&clock, timebuf, STRLEN);
250     fprintf (out, "%c\tBy user: %s (%d)\n", COMMENTSIGN,
251              user ? user : unk, (int) uid);
252     fprintf(out, "%c\tOn host: %s\n", COMMENTSIGN, (gh == 0) ? buf : unk);
253
254     fprintf (out, "%c\tAt date: %s", COMMENTSIGN, timebuf);
255     fprintf (out, "%c\n", COMMENTSIGN);
256 }
257
258
259 int gmx_strcasecmp_min(const char *str1, const char *str2)
260 {
261     char ch1, ch2;
262
263     do
264     {
265         do
266         {
267             ch1 = toupper(*(str1++));
268         }
269         while ((ch1 == '-') || (ch1 == '_'));
270         do
271         {
272             ch2 = toupper(*(str2++));
273         }
274         while ((ch2 == '-') || (ch2 == '_'));
275
276         if (ch1 != ch2)
277         {
278             return (ch1-ch2);
279         }
280     }
281     while (ch1);
282     return 0;
283 }
284
285 int gmx_strncasecmp_min(const char *str1, const char *str2, int n)
286 {
287     char  ch1, ch2;
288     char *stri1, *stri2;
289
290     stri1 = (char *)str1;
291     stri2 = (char *)str2;
292     do
293     {
294         do
295         {
296             ch1 = toupper(*(str1++));
297         }
298         while ((ch1 == '-') || (ch1 == '_'));
299         do
300         {
301             ch2 = toupper(*(str2++));
302         }
303         while ((ch2 == '-') || (ch2 == '_'));
304
305         if (ch1 != ch2)
306         {
307             return (ch1-ch2);
308         }
309     }
310     while (ch1 && (str1-stri1 < n) && (str2-stri2 < n));
311     return 0;
312 }
313
314 int gmx_strcasecmp(const char *str1, const char *str2)
315 {
316     char ch1, ch2;
317
318     do
319     {
320         ch1 = toupper(*(str1++));
321         ch2 = toupper(*(str2++));
322         if (ch1 != ch2)
323         {
324             return (ch1-ch2);
325         }
326     }
327     while (ch1);
328     return 0;
329 }
330
331 int gmx_strncasecmp(const char *str1, const char *str2, int n)
332 {
333     char ch1, ch2;
334
335     if (n == 0)
336     {
337         return 0;
338     }
339
340     do
341     {
342         ch1 = toupper(*(str1++));
343         ch2 = toupper(*(str2++));
344         if (ch1 != ch2)
345         {
346             return (ch1-ch2);
347         }
348         n--;
349     }
350     while (ch1 && n);
351     return 0;
352 }
353
354 char *gmx_strdup(const char *src)
355 {
356     char *dest;
357
358     snew(dest, strlen(src)+1);
359     strcpy(dest, src);
360
361     return dest;
362 }
363
364 char *
365 gmx_strndup(const char *src, int n)
366 {
367     int   len;
368     char *dest;
369
370     len = strlen(src);
371     if (len > n)
372     {
373         len = n;
374     }
375     snew(dest, len+1);
376     strncpy(dest, src, len);
377     dest[len] = 0;
378     return dest;
379 }
380
381 /* Magic hash init number for Dan J. Bernsteins algorithm.
382  * Do NOT use any other value unless you really know what you are doing.
383  */
384 const unsigned int
385     gmx_string_hash_init = 5381;
386
387
388 unsigned int
389 gmx_string_hash_func(const char *s, unsigned int hash_init)
390 {
391     int c;
392
393     while ((c = toupper(*s++)) != '\0')
394     {
395         if (isalnum(c))
396         {
397             hash_init = ((hash_init << 5) + hash_init) ^ c;            /* (hash * 33) xor c */
398         }
399     }
400     return hash_init;
401 }
402
403 int
404 gmx_wcmatch(const char *pattern, const char *str)
405 {
406     while (*pattern)
407     {
408         if (*pattern == '*')
409         {
410             /* Skip multiple wildcards in a sequence */
411             while (*pattern == '*' || *pattern == '?')
412             {
413                 ++pattern;
414                 /* For ?, we need to check that there are characters left
415                  * in str. */
416                 if (*pattern == '?')
417                 {
418                     if (*str == 0)
419                     {
420                         return GMX_NO_WCMATCH;
421                     }
422                     else
423                     {
424                         ++str;
425                     }
426                 }
427             }
428             /* If the pattern ends after the star, we have a match */
429             if (*pattern == 0)
430             {
431                 return 0;
432             }
433             /* Match the rest against each possible suffix of str */
434             while (*str)
435             {
436                 /* Only do the recursive call if the first character
437                  * matches. We don't have to worry about wildcards here,
438                  * since we have processed them above. */
439                 if (*pattern == *str)
440                 {
441                     int rc;
442                     /* Match the suffix, and return if a match or an error */
443                     rc = gmx_wcmatch(pattern, str);
444                     if (rc != GMX_NO_WCMATCH)
445                     {
446                         return rc;
447                     }
448                 }
449                 ++str;
450             }
451             /* If no suffix of str matches, we don't have a match */
452             return GMX_NO_WCMATCH;
453         }
454         else if ((*pattern == '?' && *str != 0) || *pattern == *str)
455         {
456             ++str;
457         }
458         else
459         {
460             return GMX_NO_WCMATCH;
461         }
462         ++pattern;
463     }
464     /* When the pattern runs out, we have a match if the string has ended. */
465     return (*str == 0) ? 0 : GMX_NO_WCMATCH;
466 }
467
468 char *wrap_lines(const char *buf, int line_width, int indent, gmx_bool bIndentFirst)
469 {
470     char    *b2;
471     int      i, i0, i2, j, b2len, lspace = 0, l2space = 0;
472     gmx_bool bFirst, bFitsOnLine;
473
474     /* characters are copied from buf to b2 with possible spaces changed
475      * into newlines and extra space added for indentation.
476      * i indexes buf (source buffer) and i2 indexes b2 (destination buffer)
477      * i0 points to the beginning of the current line (in buf, source)
478      * lspace and l2space point to the last space on the current line
479      * bFirst is set to prevent indentation of first line
480      * bFitsOnLine says if the first space occurred before line_width, if
481      * that is not the case, we have a word longer than line_width which
482      * will also not fit on the next line, so we might as well keep it on
483      * the current line (where it also won't fit, but looks better)
484      */
485
486     b2    = NULL;
487     b2len = strlen(buf)+1+indent;
488     snew(b2, b2len);
489     i0 = i2 = 0;
490     if (bIndentFirst)
491     {
492         for (i2 = 0; (i2 < indent); i2++)
493         {
494             b2[i2] = ' ';
495         }
496     }
497     bFirst = TRUE;
498     do
499     {
500         l2space = -1;
501         /* find the last space before end of line */
502         for (i = i0; ((i-i0 < line_width) || (l2space == -1)) && (buf[i]); i++)
503         {
504             b2[i2++] = buf[i];
505             /* remember the position of a space */
506             if (buf[i] == ' ')
507             {
508                 lspace  = i;
509                 l2space = i2-1;
510             }
511             /* if we have a newline before the line is full, reset counters */
512             if (buf[i] == '\n' && buf[i+1])
513             {
514                 i0     = i+1;
515                 b2len += indent;
516                 srenew(b2, b2len);
517                 /* add indentation after the newline */
518                 for (j = 0; (j < indent); j++)
519                 {
520                     b2[i2++] = ' ';
521                 }
522             }
523         }
524         /* If we are at the last newline, copy it */
525         if (buf[i] == '\n' && !buf[i+1])
526         {
527             b2[i2++] = buf[i++];
528         }
529         /* if we're not at the end of the string */
530         if (buf[i])
531         {
532             /* check if one word does not fit on the line */
533             bFitsOnLine = (i-i0 <= line_width);
534             /* reset line counters to just after the space */
535             i0 = lspace+1;
536             i2 = l2space+1;
537             /* if the words fit on the line, and we're beyond the indentation part */
538             if ( (bFitsOnLine) && (l2space >= indent) )
539             {
540                 /* start a new line */
541                 b2[l2space] = '\n';
542                 /* and add indentation */
543                 if (indent)
544                 {
545                     if (bFirst)
546                     {
547                         line_width -= indent;
548                         bFirst      = FALSE;
549                     }
550                     b2len += indent;
551                     srenew(b2, b2len);
552                     for (j = 0; (j < indent); j++)
553                     {
554                         b2[i2++] = ' ';
555                     }
556                     /* no extra spaces after indent; */
557                     while (buf[i0] == ' ')
558                     {
559                         i0++;
560                     }
561                 }
562             }
563         }
564     }
565     while (buf[i]);
566     b2[i2] = '\0';
567
568     return b2;
569 }
570
571 char **split(char sep, const char *str)
572 {
573     char **ptr = NULL;
574     int    n, nn, nptr = 0;
575
576     if (str == NULL)
577     {
578         return NULL;
579     }
580     nn = strlen(str);
581     for (n = 0; (n < nn); n++)
582     {
583         if (str[n] == sep)
584         {
585             nptr++;
586         }
587     }
588     snew(ptr, nptr+2);
589     nptr = 0;
590     while (*str != '\0')
591     {
592         while ((*str != '\0') && (*str == sep))
593         {
594             str++;
595         }
596         if (*str != '\0')
597         {
598             snew(ptr[nptr], 1+strlen(str));
599             n = 0;
600             while ((*str != '\0') && (*str != sep))
601             {
602                 ptr[nptr][n] = *str;
603                 str++;
604                 n++;
605             }
606             ptr[nptr][n] = '\0';
607             nptr++;
608         }
609     }
610     ptr[nptr] = NULL;
611
612     return ptr;
613 }
614
615
616 gmx_large_int_t
617 str_to_large_int_t(const char *str, char **endptr)
618 {
619     int              sign = 1;
620     gmx_large_int_t  val  = 0;
621     char             ch;
622     const char      *p;
623
624     p = str;
625     if (p == NULL)
626     {
627         *endptr = NULL;
628         return 0;
629     }
630
631     /* Strip off initial white space */
632     while (isspace(*p))
633     {
634         p++;
635     }
636     /* Conform to ISO C99 - return original pointer if string does not contain a number */
637     if (*str == '\0')
638     {
639         *endptr = (char *)str;
640     }
641
642     if (*p == '-')
643     {
644         p++;
645         sign *= -1;
646     }
647
648     while ( ((ch = *p) != '\0') && isdigit(ch) )
649     {
650         /* Important to add sign here, so we dont overflow in final multiplication */
651         ch  = (ch-'0')*sign;
652         val = val*10 + ch;
653         if (ch != val%10)
654         {
655             /* Some sort of overflow has occured, set endptr to original string */
656             *endptr = (char *)str;
657             errno   = ERANGE;
658             return(0);
659         }
660         p++;
661     }
662
663     *endptr = (char *)p;
664
665     return val;
666 }
667
668 char *gmx_strsep(char **stringp, const char *delim)
669 {
670     char *ret;
671     int   len = strlen(delim);
672     int   i, j = 0;
673     int   found = 0;
674
675     if (!*stringp)
676     {
677         return NULL;
678     }
679     ret = *stringp;
680     do
681     {
682         if ( (*stringp)[j] == '\0')
683         {
684             found    = 1;
685             *stringp = NULL;
686             break;
687         }
688         for (i = 0; i < len; i++)
689         {
690             if ( (*stringp)[j] == delim[i])
691             {
692                 (*stringp)[j] = '\0';
693                 *stringp      = *stringp+j+1;
694                 found         = 1;
695                 break;
696             }
697         }
698         j++;
699     }
700     while (!found);
701
702     return ret;
703 }