1 /*****************************************************************
2 * SQUID - a library of functions for biological sequence analysis
3 * Copyright (C) 1992-2002 Washington University School of Medicine
5 * This source code is freely distributed under the terms of the
6 * GNU General Public License. See the files COPYRIGHT and LICENSE
8 *****************************************************************/
12 * my library of extra string functions. Some for portability
15 * RCS $Id: sre_string.c 217 2011-03-19 10:27:10Z andreas $ (Original squid RCS Id: sre_string.c,v 1.11 2001/06/07 16:59:37 eddy Exp)
27 * Purpose: Implementation of the common (but non-ANSI) function
28 * strdup(). Robust against being passed a NULL pointer.
35 if (s == NULL) return NULL;
36 if ((new = (char *) malloc (strlen(s) +1)) == NULL) return NULL;
41 /* Function: StringChop()
42 * Date: SRE, Wed Oct 29 12:10:02 1997 [TWA 721]
44 * Purpose: Chop trailing whitespace off of a string.
51 i = strlen(s) - 1; /* set i at last char in string */
52 while (i >= 0 && isspace((int) s[i])) i--; /* i now at last non-whitespace char, or -1 */
57 Strinsert(char *s1, /* string to insert a char into */
58 char c, /* char to insert */
59 int pos) /* position in s1 to insert c at */
64 for (s = s1 + pos; c; s++)
66 /* swap current char for inserted one */
67 oldc = *s; /* pick up current */
68 *s = c; /* put down inserted one */
69 c = oldc; /* old becomes next to insert */
78 Strdelete(char *s1, /* string to delete a char from */
79 int pos) /* position of char to delete 0..n-1 */
83 for (s = s1 + pos; *s; s++)
92 for (; *s != '\0'; s++)
93 *s = sre_tolower((int) *s);
99 for (; *s != '\0'; s++)
100 *s = sre_toupper((int) *s);
105 sre_malloc(char *file, int line, size_t size)
109 SQD_DPRINTF3(("MALLOC: %d bytes (file %s line %d)\n", size, file, line));
110 if ((ptr = malloc (size)) == NULL)
111 Die("malloc of %ld bytes failed: file %s line %d", size, file, line);
116 sre_realloc(char *file, int line, void *p, size_t size)
120 if ((ptr = realloc(p, size)) == NULL)
121 Die("realloc of %ld bytes failed: file %s line %d", size, file, line);
127 /* Function: Free2DArray(), Free3DArray()
128 * Date: SRE, Tue Jun 1 14:47:14 1999 [St. Louis]
130 * Purpose: Convenience functions for free'ing 2D
131 * and 3D pointer arrays. Tolerates any of the
132 * pointers being NULL, to allow "sparse"
135 * Args: p - array to be freed
136 * dim1 - n for first dimension
137 * dim2 - n for second dimension
139 * e.g. a 2d array is indexed p[0..dim1-1][]
140 * a 3D array is indexed p[0..dim1-1][0..dim2-1][]
144 * Diagnostics: (void)
148 Free2DArray(void **p, int dim1)
153 for (i = 0; i < dim1; i++)
154 if (p[i] != NULL) free(p[i]);
159 Free3DArray(void ***p, int dim1, int dim2)
164 for (i = 0; i < dim1; i++)
166 for (j = 0; j < dim2; j++)
167 if (p[i][j] != NULL) free(p[i][j]);
175 /* Function: RandomSequence()
177 * Purpose: Generate an iid symbol sequence according
178 * to some alphabet, alphabet_size, probability
179 * distribution, and length. Return the
182 * Args: alphabet - e.g. "ACGT"
183 * p - probability distribution [0..n-1]
184 * n - number of symbols in alphabet
185 * len - length of generated sequence
187 * Return: ptr to random sequence, or NULL on failure.
190 RandomSequence(char *alphabet, float *p, int n, int len)
195 s = (char *) MallocOrDie (sizeof(char) * (len+1));
196 for (x = 0; x < len; x++)
197 s[x] = alphabet[FChoose(p,n)];
202 /* Function: sre_fgets()
203 * Date: SRE, Thu May 13 10:56:28 1999 [St. Louis]
205 * Purpose: Dynamic allocation version of fgets(),
206 * capable of reading unlimited line lengths.
208 * Args: buf - ptr to a string (may be reallocated)
209 * n - ptr to current allocated length of buf,
211 * fp - open file ptr for reading
213 * Before the first call to sre_fgets(),
214 * buf should be initialized to NULL and n to 0.
215 * They're a linked pair, so don't muck with the
216 * allocation of buf or the value of n while
217 * you're still doing sre_fgets() calls with them.
219 * Returns: ptr to the buffer on success.
220 * NULL on EOF (buf isn't to be used in this case)
221 * sre_fgets() *always* results in an allocation
224 * The reason to have it return a ptr to buf
225 * is that it makes wrapper macros easy; see
226 * MSAFileGetLine() for an example.
228 * Example: char *buf;
232 * fp = fopen("my_file", "r");
235 * while (sre_fgets(&buf, &n, fp) != NULL)
241 sre_fgets(char **buf, int *n, FILE *fp)
249 *buf = MallocOrDie(sizeof(char) * 128);
253 /* Simple case 1. We're sitting at EOF, or there's an error.
254 * fgets() returns NULL, so we return NULL.
256 if (fgets(*buf, *n, fp) == NULL) return NULL;
258 /* Simple case 2. fgets() got a string, and it reached EOF.
259 * return success status, so caller can use
260 * the last line; on the next call we'll
261 * return the 0 for the EOF.
263 if (feof(fp)) return *buf;
265 /* Simple case 3. We got a complete string, with \n,
266 * and don't need to extend the buffer.
269 if ((*buf)[len-1] == '\n') return *buf;
271 /* The case we're waiting for. We have an incomplete string,
272 * and we have to extend the buffer one or more times. Make
273 * sure we overwrite the previous fgets's \0 (hence +(n-1)
274 * in first step, rather than 128, and reads of 129, not 128).
279 *buf = ReallocOrDie(*buf, sizeof(char) * (*n));
281 if (fgets(s, 129, fp) == NULL) return *buf;
283 if (s[len-1] == '\n') return *buf;
289 /* Function: sre_strcat()
290 * Date: SRE, Thu May 13 09:36:32 1999 [St. Louis]
292 * Purpose: Dynamic memory version of strcat().
293 * appends src to the string that dest points to,
294 * extending allocation for dest if necessary.
296 * One timing experiment (100 successive appends of
297 * 1-255 char) shows sre_strcat() has about a 20%
298 * overhead relative to strcat(). However, if optional
299 * length info is passed, sre_strcat() is about 30%
300 * faster than strcat().
302 * Args: dest - ptr to string (char **), '\0' terminated
303 * ldest - length of dest, if known; or -1 if length unknown.
304 * src - string to append to dest, '\0' terminated
305 * lsrc - length of src, if known; or -1 if length unknown.
307 * dest may be NULL, in which case this is
308 * the equivalent of dest = Strdup(src).
310 * src may also be NULL, in which case
311 * dest is unmodified (but why would you want to pass
314 * if both dest and src are NULL, dest is
315 * unmodified; it stays NULL.
317 * the length parameters are optional. If a -1
318 * is passed, sre_strcat() will call strlen() to
319 * determine the length itself. Passing length
320 * info saves the strlen() calls and can speed things
321 * up if lots of successive appends need to be done.
323 * Returns: new length of dest (>=0 on success);
324 * dest is (probably) reallocated, and modified
325 * to a longer string, '\0' terminated.
328 sre_strcat(char **dest, int ldest, char *src, int lsrc)
332 if (ldest < 0) len1 = ((*dest == NULL) ? 0 : strlen(*dest));
335 if (lsrc < 0) len2 = (( src == NULL) ? 0 : strlen(src));
338 if (len2 == 0) return len1;
340 if (*dest == NULL) *dest = MallocOrDie(sizeof(char) * (len2+1));
341 else *dest = ReallocOrDie(*dest, sizeof(char) * (len1+len2+1));
343 memcpy((*dest)+len1, src, len2+1);
347 /* Function: sre_strtok()
348 * Date: SRE, Wed May 19 16:30:20 1999 [St. Louis]
350 * Purpose: Thread-safe version of strtok().
352 * Returns ptr to next token in a string: skips
353 * until it reaches a character that is not in the delim
354 * string, and sets beginning of token. Skips to
355 * next delim character (or '\0') to set the end; replaces that
356 * character with '\0'.
357 * If there's still more string left, sets s to point to next
358 * character after the '\0' that was written, so successive
359 * calls extract tokens in succession. If there was no string
360 * left, s points at the terminal '\0'.
362 * If no token is found, returns NULL.
364 * Also returns the length of the token, which
365 * may save us a strlen() call in some applications.
368 * *s can't be a constant string, since we write to it.
374 * char buf[50] = "This is a sentence.";
377 * tok = sre_strtok(&s, " ", &len);
378 * tok is "This"; s is "is a sentence."; len is 4.
379 * tok = sre_strtok(&s, " ", &len);
380 * tok is "is"; s is " a sentence."; len is 2.
381 * tok = sre_strtok(&s, " ", &len);
382 * tok is "a"; s is "sentence."; len is 1.
383 * tok = sre_strtok(&s, " ", &len);
384 * tok is "sentence."; s is "\0"; len is 9.
385 * tok = sre_strtok(&s, " ", &len);
386 * tok is NULL; s is "\0", len is undefined.
388 * Args: s - a tmp, modifiable ptr to string
389 * delim - characters that delimits tokens
390 * len - RETURN: length of token; pass NULL if not wanted
392 * Returns: ptr to next token, or NULL if there aren't any.
395 sre_strtok(char **s, char *delim, int *len)
401 begin += strspn(begin, delim);
402 if (! *begin) return NULL;
404 n = strcspn(begin, delim);
406 if (*end == '\0') { *s = end;}
412 if (len != NULL) *len = n;
418 /* Function: sre_strdup()
419 * Date: SRE, Wed May 19 17:57:28 1999 [St. Louis]
421 * Purpose: A version of the common but non-ANSI strdup()
422 * function. Can pass len, if known, to save a
425 * Args: s - string to duplicate
426 * n - length of string, if known; -1 if unknown.
428 * Returns: allocated copy of string.
432 sre_strdup(char *s, int n)
436 if (s == NULL) return NULL;
437 if (n < 0) n = strlen(s);
438 new = MallocOrDie (sizeof(char) * (n+1));
444 /* Function: sre_strncpy()
445 * Date: SRE, Tue Jun 22 10:10:46 1999 [Sanger Centre]
447 * Purpose: a strncpy() that makes sure it adds a trailing \0.
449 * Args: s1 - string to copy to (allocated n+1 or larger)
450 * s2 - string to copy from
451 * n - number of chars to copy
454 * Done only for consistency with strncpy(). Not clear
455 * why it's useful for a strncpy() to return s1.
458 sre_strncpy(char *s1, char *s2, int n)
465 /* Function: IsBlankline()
466 * Date: SRE, Fri Jun 18 14:36:08 1999 [St. Louis]
468 * Purpose: Returns TRUE if string consists solely of whitespace.
470 * Args: s - string to check
475 for (; *s != '\0'; s++)
476 if (! isspace(*s)) return FALSE;
483 /* A timing test for sre_strcat()
484 * cc -O2 -g sre_string.c sre_ctype.c sqerror.c sre_math.c hsregex.c -lm
485 * 15.200u - 5.360u = 9.84u if sre_strcat() with no length info passed
486 * 13.660u - 5.360u = 8.30u if strcat(), with a single malloc().
487 * 11.370u - 5.360u = 6.01u if sre_strcat() with length info passed.
491 float p[4] = {0.25, 0.25, 0.25, 0.25};
504 /* s1 = malloc(sizeof(char) * (255*nappends+1));
510 for (i = 0; i < nappends; i++)
512 buflen = CHOOSE(255) + 1;
513 s2 = RandomSequence("ACGT", p, 4, buflen);
516 if ((len = sre_strcat(&s1, len, s2, buflen)) < 0) exit(1);