Debian Codegraph @

easel/easel.c

raw symbols SCIP
1 /* Easel's foundation.
2 *
3 * Contents:
4 * 1. Exception and fatal error handling.
5 * 2. Memory allocation/deallocation conventions.
6 * 3. Standard banner for Easel miniapplications.
7 * 4. Improved replacements for some C library functions.
8 * 5. Portable drop-in replacements for nonstandard C functions.
9 * 6. Additional string functions, esl_str*()
10 * 7. File path/name manipulation, including tmpfiles.
11 * 8. Typed comparison functions.
12 * 9. Other miscellaneous functions.
13 * 10. Unit tests.
14 * 11. Test driver.
15 * 12. Examples.
16 */
17 #include <esl_config.h>
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdarg.h>
22 #include <errno.h>
23 #include <limits.h>
24 #include <string.h>
25 #include <math.h>
26 #include <ctype.h>
27
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #ifdef _POSIX_VERSION
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #endif
35
36 #ifdef HAVE_MPI
37 #include <mpi.h> /* MPI_Abort() may be used in esl_fatal() or other program killers */
38 #endif
39
40 #include "easel.h"
41 #include <syslog.h>
42
43 /*****************************************************************
44 * 1. Exception and fatal error handling.
45 *****************************************************************/
46 static esl_exception_handler_f esl_exception_handler = NULL;
47
48 /* Function: esl_fail()
49 * Synopsis: Handle a normal failure code/message before returning to caller.
50 *
51 * Purpose: A "failure" is a normal error that we want to handle
52 * without terminating the program; we're going to return
53 * control to the caller with a nonzero error code and
54 * (optionally) an informative error message formatted
55 * in <errbuf>.
56 *
57 * <esl_fail()> is called internally by the <ESL_FAIL()>
58 * and <ESL_XFAIL()> macros (see easel.h). The reason to
59 * have the failure macros call such a simple little
60 * function is to give us a convenient debugging
61 * breakpoint. For example, in a <_Validate()> routine that
62 * needs to do a normal return to a caller, you can set a
63 * breakpoint in <esl_fail()> to see exactly where the
64 * validation failed.
65 */
66 void
67 esl_fail(char *errbuf, const char *format, ...)
68 {
69 if (format)
70 {
71 va_list ap;
72 /* Check whether we are running as a daemon so we can do the
73 * right thing about logging instead of printing errors
74 */
75 if (getppid() != 1)
76 { // we aren't running as a daemon, so print the error normally
77 va_start(ap, format);
78 if (errbuf) vsnprintf(errbuf, eslERRBUFSIZE, format, ap);
79 va_end(ap);
80 }
81 else
82 {
83 va_start(ap, format);
84 vsyslog(LOG_ERR, format, ap);
85 va_end(ap);
86 }
87 }
88 }
89
90
91 /* Function: esl_exception()
92 * Synopsis: Throw an exception.
93 *
94 * Purpose: Throw an exception. An "exception" is defined by Easel
95 * as an internal error that shouldn't happen and/or is
96 * outside the user's control; as opposed to "failures", that
97 * are to be expected, and within user control, and
98 * therefore normal. By default, exceptions are fatal.
99 * A program that wishes to be more robust can register
100 * a non-fatal exception handler.
101 *
102 * Easel programs normally call one of the exception-handling
103 * wrappers <ESL_EXCEPTION()> or <ESL_XEXCEPTION()>, which
104 * handle the overhead of passing in <use_errno>, <sourcefile>,
105 * and <sourceline>. <esl_exception> is rarely called directly.
106 *
107 * If no custom exception handler has been registered, the
108 * default behavior is to print a brief message to <stderr>
109 * then <abort()>, resulting in a nonzero exit code from the
110 * program. Depending on what <errcode>, <sourcefile>,
111 * <sourceline>, and the <sprintf()>-formatted <format>
112 * are, this output looks like:
113 *
114 * Fatal exception (source file foo.c, line 42):
115 * Something wicked this way came.
116 *
117 * Additionally, in an MPI parallel program, the default fatal
118 * handler aborts all processes (with <MPI_Abort()>), not just
119 * the one that called <esl_exception()>.
120 *
121 * Args: errcode - Easel error code, such as eslEINVAL. See easel.h.
122 * use_errno - if TRUE, also use perror() to report POSIX errno message.
123 * sourcefile - Name of offending source file; normally __FILE__.
124 * sourceline - Name of offending source line; normally __LINE__.
125 * format - <sprintf()> formatted exception message, followed
126 * by any additional necessary arguments for that
127 * message.
128 *
129 * Returns: void.
130 *
131 * Throws: No abnormal error conditions. (Who watches the watchers?)
132 */
133 void
134 esl_exception(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, ...)
135 {
136 va_list argp;
137 #ifdef HAVE_MPI
138 int mpiflag;
139 #endif
140
141 if (esl_exception_handler != NULL)
142 { // If the custom exception handler tries to print to stderr/stdout, the error may get eaten if we're running as a daemon
143 // Not sure how to prevent that, since we can't control what custom handlers get written.
144 va_start(argp, format);
145 (*esl_exception_handler)(errcode, use_errno, sourcefile, sourceline, format, argp);
146 va_end(argp);
147 return;
148 }
149 else
150 {
151 /* Check whether we are running as a daemon so we can do the right thing about logging instead of printing errors */
152 if (getppid() != 1)
153 { // we're not running as a daemon, so print the error normally
154 fprintf(stderr, "Fatal exception (source file %s, line %d):\n", sourcefile, sourceline);
155 va_start(argp, format);
156 vfprintf(stderr, format, argp);
157 va_end(argp);
158 fprintf(stderr, "\n");
159 if (use_errno && errno) perror("system error");
160 fflush(stderr);
161 }
162 else
163 {
164 va_start(argp, format);
165 vsyslog(LOG_ERR, format, argp);
166 va_end(argp);
167 }
168
169 #ifdef HAVE_MPI
170 MPI_Initialized(&mpiflag); /* we're assuming we can do this, even in a corrupted, dying process...? */
171 if (mpiflag) MPI_Abort(MPI_COMM_WORLD, 1);
172 #endif
173 abort();
174 }
175 }
176
177 /* Function: esl_exception_SetHandler()
178 * Synopsis: Register a different exception handling function.
179 *
180 * Purpose: Register a different exception handling function,
181 * <handler>. When an exception occurs, the handler
182 * receives at least four arguments: <errcode>, <sourcefile>,
183 * <sourceline>, and <format>.
184 *
185 * <errcode> is an Easel error code, such as
186 * <eslEINVAL>. See <easel.h> for a list of all codes.
187 *
188 * <use_errno> is TRUE for POSIX system call failures. The
189 * handler may then use POSIX <errno> to format/print an
190 * additional message, using <perror()> or <strerror_r()>.
191 *
192 * <sourcefile> is the name of the Easel source code file
193 * in which the exception occurred, and <sourceline> is
194 * the line number.
195 *
196 * <format> is a <vprintf()>-formatted string, followed by
197 * a <va_list> containing any additional arguments that
198 * formatted message needs. Your custom exception handler
199 * will probably use <vfprintf()> or <vsnprintf()> to format
200 * its error message.
201 *
202 * Args: handler - ptr to your custom exception handler.
203 *
204 * Returns: void.
205 *
206 * Throws: (no abnormal error conditions)
207 */
208 void
209 esl_exception_SetHandler(void (*handler)(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, va_list argp))
210 {
211 esl_exception_handler = handler;
212 }
213
214
215 /* Function: esl_exception_ResetDefaultHandler()
216 * Synopsis: Restore default exception handling.
217 *
218 * Purpose: Restore default exception handling, which is to print
219 * a simple error message to <stderr> then <abort()> (see
220 * <esl_exception()>.
221 *
222 * An example where this might be useful is in a program
223 * that only temporarily wants to catch one or more types
224 * of normally fatal exceptions.
225 *
226 * If the default handler is already in effect, this
227 * call has no effect (is a no-op).
228 *
229 * Args: (void)
230 *
231 * Returns: (void)
232 *
233 * Throws: (no abnormal error conditions)
234 */
235 void
236 esl_exception_ResetDefaultHandler(void)
237 {
238 esl_exception_handler = NULL;
239 }
240
241
242 /* Function: esl_nonfatal_handler()
243 * Synopsis: A trivial example of a nonfatal exception handler.
244 *
245 * Purpose: This serves two purposes. First, it is the simplest
246 * example of a nondefault exception handler. Second, this
247 * is used in test harnesses, when they have
248 * <eslTEST_THROWING> turned on to test that thrown errors
249 * are handled properly when a nonfatal error handler is
250 * registered by the application.
251 *
252 * Args: errcode - Easel error code, such as eslEINVAL. See easel.h.
253 * use_errno - TRUE on POSIX system call failures; use <errno>
254 * sourcefile - Name of offending source file; normally __FILE__.
255 * sourceline - Name of offending source line; normally __LINE__.
256 * format - <sprintf()> formatted exception message.
257 * argp - <va_list> containing any additional necessary arguments for
258 * the <format> message.
259 *
260 * Returns: void.
261 *
262 * Throws: (no abnormal error conditions)
263 */
264 void
265 esl_nonfatal_handler(int errcode, int use_errno, char *sourcefile, int sourceline, char *format, va_list argp)
266 {
267 return;
268 }
269
270
271 /* Function: esl_fatal()
272 * Synopsis: Kill a program immediately, for a "violation".
273 *
274 * Purpose: Kill a program for a "violation". In general this should only be used
275 * in development or testing code, not in production
276 * code. The main use of <esl_fatal()> is in unit tests.
277 * Another use is in assertions used in dev code.
278 *
279 * The only other case (and the only case that should be allowed in
280 * production code) is in a true "function" (a function that returns
281 * its answer, rather than an Easel error code), where Easel error
282 * conventions can't be used (because it can't return an error code),
283 * AND the error is guaranteed to be a coding error. For an example,
284 * see <esl_opt_IsOn()>, which triggers a violation if the code
285 * checks for an option that isn't in the code.
286 *
287 * In an MPI-parallel program, the entire job is
288 * terminated; all processes are aborted (<MPI_Abort()>,
289 * not just the one that called <esl_fatal()>.
290 *
291 * If caller is feeling lazy and just wants to terminate
292 * without any informative message, use <abort()>.
293 *
294 * Args: format - <sprintf()> formatted exception message, followed
295 * by any additional necessary arguments for that
296 * message.
297 *
298 * Returns: (void)
299 *
300 * Throws: (no abnormal error conditions)
301 */
302 void
303 esl_fatal(const char *format, ...)
304 {
305 va_list argp;
306 #ifdef HAVE_MPI
307 int mpiflag;
308 #endif
309 /* Check whether we are running as a daemon so we can do the right thing about logging instead of printing errors */
310 if (getppid() != 1)
311 { // we're not running as a daemon, so print the error normally
312 va_start(argp, format);
313 vfprintf(stderr, format, argp);
314 va_end(argp);
315 fprintf(stderr, "\n");
316 fflush(stderr);
317 }
318 else
319 {
320 va_start(argp, format);
321 vsyslog(LOG_ERR, format, argp);
322 va_end(argp);
323 }
324
325 #ifdef HAVE_MPI
326 MPI_Initialized(&mpiflag);
327 if (mpiflag) MPI_Abort(MPI_COMM_WORLD, 1);
328 #endif
329 exit(1);
330 }
331 /*---------------- end, error handling conventions --------------*/
332
333
334
335
336 /*****************************************************************
337 * 2. Memory allocation/deallocation conventions.
338 *****************************************************************/
339
340 /* Function: esl_resize()
341 * Synopsis: Implement idiomatic resize-by-doubling + redline allocation rules.
342 * Incept: SRE, Sun 21 Feb 2021
343 *
344 * Purpose: Return a recommended allocation size, given minimum required allocation
345 * size <n>, current allocation size <a>, and "redline" <r>. Implements
346 * Easel's idiom for growing an allocation exponentially, while trying
347 * to keep it capped at a maximum redline.
348 *
349 * Let's call the return value <b>: $b \geq n$, i.e. the returned <b> is
350 * always sufficient to fit <n>.
351 *
352 * - If $n >= r$, the requested allocation is above redline, so return
353 * $b=n$ exactly. This includes when we need to grow the allocation
354 * ($a < n$), and cases where the current allocation would suffice
355 * ($a >= n$) but we can shrink it back toward the redline somewhat.
356 *
357 * - If $n \leq a$ then the current allocation suffices. If $a \leq r$,
358 * return $b=a$ (signifying "don't reallocate"). If $a > r$, the
359 * current allocation is excessive (we know $n < r$) so pull it
360 * back to redline, returning $b=r$.
361 *
362 * - If $n > a$ then increase the current allocation by doubling, until
363 * it suffices. Cap it at the redline if necessary and don't allow
364 * doubling to overflow an integer. Now $b \leq r$ and $n \leq b <
365 * 2n$.
366 *
367 * If the caller wants to allow both growing and shrinking (for example,
368 * supporting an object that has a <Resize()> but not a <Reuse()>), the idiom
369 * is:
370 *
371 * ```
372 * if ( ( newalloc = esl_resize(n, obj->nalloc, obj->redline)) != a) {
373 * ESL_REALLOC(obj, ...);
374 * obj->nalloc = newalloc;
375 * }
376 * ```
377 *
378 * If the caller only wants <Resize()> to grow, not shrink (because there's
379 * a <Reuse()> to handle shrinking):
380 *
381 * ```
382 * if (n > obj->nalloc) {
383 * newalloc = esl_resize(n, obj->nalloc, obj->redline);
384 * ESL_REALLOC(obj, ...);
385 * obj->nalloc = newalloc;
386 * }
387 * ```
388 *
389 * If the caller is a <Reuse()> that's only responsible for shrinking
390 * allocations back to redline, pass $n=0$, so the allocation will only
391 * change if $a>r$:
392 *
393 * ```
394 * if (( newalloc = esl_resize(0, obj->nalloc, obj->redline)) != a) {
395 * ESL_REALLOC(obj, ...);
396 * obj->nalloc = newalloc;
397 * }
398 * ```
399 *
400 * Growing allocations exponentially (by doubling) minimizes the number of
401 * expensive reallocation calls we have to make, when we're expecting to
402 * reuse/reallocate a space a lot... either because we're growing it
403 * dynamically (perhaps one unit at a time, like a list), or because we're
404 * dynamically resizing it for each task in an iteration over different
405 * tasks.
406 *
407 * The "redline" tries to cap or at least minimize allocation size when it
408 * would exceed <r>. We're often in a situation where the allocations we
409 * need for an iterated set of tasks have a long-tailed distribution -
410 * sequence lengths, for example. We may only need to occasionally make
411 * excursions into very large allocations. Thus, it's advantageous to just
412 * make a transient exceptional allocation of exactly enough size. In
413 * Easel's idioms, the next <_Reuse()> or <_Resize()> call pulls an
414 * exceptional allocation size back down to the redline.
415 *
416 * The redline is only useful in the iterated-set-of-different-sized-tasks
417 * use case. It's not useful in the grow-one-unit-each-step use case (over
418 * redline, you'd start inefficiently making a reallocation at each step).
419 * If you're in the grow-one-unit-each-step use case, you want to set the
420 * redline to <INT_MAX>; or for convenience, if you pass <r=0>, this will
421 * also turn the redline off (by setting it to INT_MAX internally).
422 *
423 * The <n> argument is _inclusive_ of any constant additional allocation
424 * that the caller needs for edge effects - for example, if caller has
425 * <s=2> sentinels at positions 0 and m+1 of an array of elements 1..m, it
426 * passes <n=m+s> as the argument to esl_resize.
427 *
428 * Args: n : requested allocation size (n >= 0)
429 * a : current allocation size (a >= 0)
430 * r : redline limit (r >= 0; 0 means don't use a redline)
431 *
432 * Returns: b, the suggested new allocation (b >= n and b >= 1)
433 */
434 int
435 esl_resize(int n, int a, int r)
436 {
437 const int overflow_limit = INT_MAX / 2;
438
439 ESL_DASSERT1(( n >= 0 && a >= 0 && r >= 0));
440
441 if (r == 0) r = INT_MAX; // r=0 allows caller to conveniently turn redline off
442 if (a == 0) a = 1; // 0*=2 isn't going to go anywhere now is it?
443
444 if (n >= r) return n; // this could be n < a (shrink), n=a (stay), or n > a (grow)
445
446 if (n <= a) { // current allocation a suffices...
447 if (a <= r) return a; // ... and is below redline, so fine
448 else return r; // ... but a>r, and r suffices, so shrink back to redline r
449 }
450
451 while (a < n && a <= overflow_limit) a *= 2;
452 if (a < n) return r; // Doublings of <a> didn't suffice, because n >= (INT_MAX/2) +1. We know r > n here; use r.
453 else if (a > r) return r; // Cap the allocation at the redline. (Again, we already know r > n here.)
454
455 return a; // a has been successfully increased by doubling.
456 }
457
458 /* Function: esl_free()
459 * Synopsis: free(), while allowing ptr to be NULL.
460 * Incept: SRE, Fri Nov 3 17:12:01 2017
461 *
462 * Purpose: Easel uses a convention of initializing ptrs to be NULL
463 * before allocating them. When cleaning up after errors, a
464 * routine can check for non-NULL ptrs to know what to
465 * free(). Easel code is slightly cleaner if we have a
466 * free() that no-ops on NULL ptrs.
467 *
468 * OBSOLETE. C99 free() allows NULL already.
469 */
470 void
471 esl_free(void *p)
472 {
473 if (p) free(p);
474 }
475
476 /* Function: esl_Free2D()
477 *
478 * Purpose: Free a 2D pointer array <p>, where first dimension is
479 * <dim1>. (That is, the array is <p[0..dim1-1][]>.)
480 * Tolerates any of the pointers being NULL, to allow
481 * sparse arrays.
482 *
483 * Returns: void.
484 *
485 * DEPRECATED. Replace with esl_arr2_Destroy()
486 */
487 void
488 esl_Free2D(void **p, int dim1)
489 {
490 int i;
491 if (p != NULL) {
492 for (i = 0; i < dim1; i++)
493 if (p[i] != NULL) free(p[i]);
494 free(p);
495 }
496 return;
497 }
498
499 /* Function: esl_Free3D()
500 *
501 * Purpose: Free a 3D pointer array <p>, where first and second
502 * dimensions are <dim1>,<dim2>. (That is, the array is
503 * <p[0..dim1-1][0..dim2-1][]>.) Tolerates any of the
504 * pointers being NULL, to allow sparse arrays.
505 *
506 * Returns: void.
507 *
508 * DEPRECATED. Replace with esl_arr3_Destroy()
509 */
510 void
511 esl_Free3D(void ***p, int dim1, int dim2)
512 {
513 int i, j;
514
515 if (p != NULL) {
516 for (i = 0; i < dim1; i++)
517 if (p[i] != NULL) {
518 for (j = 0; j < dim2; j++)
519 if (p[i][j] != NULL) free(p[i][j]);
520 free(p[i]);
521 }
522 free(p);
523 }
524 }
525 /*------------- end, memory allocation conventions --------------*/
526
527
528
529 /*****************************************************************
530 * 3. Standard banner for Easel miniapplications.
531 *****************************************************************/
532
533 /* Function: esl_banner()
534 * Synopsis: print standard Easel application output header
535 *
536 * Purpose: Print the standard Easel command line application banner
537 * to <fp>, constructing it from <progname> (the name of the
538 * program) and a short one-line description <banner>.
539 * For example,
540 * <esl_banner(stdout, "compstruct", "compare RNA structures");>
541 * might result in:
542 *
543 * \begin{cchunk}
544 * # compstruct :: compare RNA structures
545 * # Easel 0.1 (February 2005)
546 * # Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus
547 * # Freely licensed under the Janelia Software License.
548 * # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
549 * \end{cchunk}
550 *
551 * <progname> would typically be an application's
552 * <argv[0]>, rather than a fixed string. This allows the
553 * program to be renamed, or called under different names
554 * via symlinks. Any path in the <progname> is discarded;
555 * for instance, if <progname> is "/usr/local/bin/esl-compstruct",
556 * "esl-compstruct" is used as the program name.
557 *
558 * Note:
559 * Needs to pick up preprocessor #define's from easel.h,
560 * as set by ./configure:
561 *
562 * symbol example
563 * ------ ----------------
564 * EASEL_VERSION "0.1"
565 * EASEL_DATE "May 2007"
566 * EASEL_COPYRIGHT "Copyright (C) 2004-2007 HHMI Janelia Farm Research Campus"
567 * EASEL_LICENSE "Freely licensed under the Janelia Software License."
568 *
569 * Returns: <eslOK> on success.
570 *
571 * Throws: <eslEMEM> on allocation error.
572 * <eslEWRITE> on write error.
573 */
574 int
575 esl_banner(FILE *fp, const char *progname, char *banner)
576 {
577 char *appname = NULL;
578 int status;
579
580 if ((status = esl_FileTail(progname, FALSE, &appname)) != eslOK) return status;
581
582 if (fprintf(fp, "# %s :: %s\n", appname, banner) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
583 if (fprintf(fp, "# Easel %s (%s)\n", EASEL_VERSION, EASEL_DATE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
584 if (fprintf(fp, "# %s\n", EASEL_COPYRIGHT) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
585 if (fprintf(fp, "# %s\n", EASEL_LICENSE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
586 if (fprintf(fp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
587
588 if (appname) free(appname);
589 return eslOK;
590
591 ERROR:
592 if (appname) free(appname);
593 return status;
594 }
595
596
597 /* Function: esl_usage()
598 * Synopsis: print standard Easel application usage help line
599 *
600 * Purpose: Given a usage string <usage> and the name of the program
601 * <progname>, output a standardized usage/help
602 * message. <usage> is minimally a one line synopsis like
603 * "[options] <filename>", but it may extend to multiple
604 * lines to explain the command line arguments in more
605 * detail. It should not describe the options; that's the
606 * job of the getopts module, and its <esl_opt_DisplayHelp()>
607 * function.
608 *
609 * This is used by the Easel miniapps, and may be useful in
610 * other applications as well.
611 *
612 * As in <esl_banner()>, the <progname> is typically passed
613 * as <argv[0]>, and any path prefix is ignored.
614 *
615 * For example, if <argv[0]> is </usr/local/bin/esl-compstruct>,
616 * then
617 *
618 * \begin{cchunk}
619 * esl_usage(stdout, argv[0], "[options] <trusted file> <test file>">
620 * \end{cchunk}
621 *
622 * produces
623 *
624 * \begin{cchunk}
625 * Usage: esl-compstruct [options] <trusted file> <test file>
626 * \end{cchunk}
627 *
628 * Returns: <eslOK> on success.
629 *
630 * Throws: <eslEMEM> on allocation failure.
631 * <eslEWRITE> on write failure.
632 */
633 int
634 esl_usage(FILE *fp, const char *progname, char *usage)
635 {
636 char *appname = NULL;
637 int status;
638
639 if ( (status = esl_FileTail(progname, FALSE, &appname)) != eslOK) return status;
640
641 if (fprintf(fp, "Usage: %s %s\n", appname, usage) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
642
643 if (appname) free(appname);
644 return eslOK;
645
646 ERROR:
647 if (appname) free(appname);
648 return status;
649 }
650
651
652 /* Function: esl_dataheader()
653 * Synopsis: Standard #-prefixed header lines for output data table
654 *
655 * Purpose: Print column headers for a space-delimited, fixed-column-width
656 * data table to <fp>.
657 *
658 * Takes a variable number of argument pairs. Each pair is
659 * <width, label>. The absolute value of <width> is the max
660 * width of the column. <label> is the column label.
661 *
662 * If <width> is negative, left justify the label. (This is
663 * supposed to mirror the %-8s vs %8s of a printf format.)
664 *
665 * Caller marks the end of the argument list
666 * with a 0 sentinel.
667 *
668 * Example: <esl_dataheader(stdout, 8, "name", 3, "A", -4, "B", 0)>
669 * gives three columns:
670 *
671 * \begin{cchunk}
672 * # name A B
673 * #------- --- ----
674 * \end{cchunk}
675 *
676 * The <width> arguments match the widths given in
677 * <fprintf()>'s or whatever generates the data rows.
678 * Because the first header line is prefixed by \verb+#+, the
679 * first column's width argument is inclusive of these two
680 * extra chars, and therefore the first column label must
681 * have no more than its <width>-2 chars. For all other
682 * column labels, a label's length cannot exceed its
683 * <width>.
684 *
685 * Up to 1024 columns are allowed. (The only reason there's
686 * a limit is because you're going to forget to add the 0
687 * sentinel, and we don't want to risk a <while(1)> infinite
688 * loop.)
689 *
690 * Args: <fp> : output stream
691 * [<width>, <label]... : width, label pairs
692 * 0 : sentinel for end of argument list
693 *
694 * Returns: <eslOK> on success.
695 *
696 * Throws: <eslEINVAL> if a label is too wide for its width, or if
697 * the number of columns exceeds the max limit.
698 * <eslEWRITE> if a write to <fp> fails, which can happen
699 * if a disk fills up, for example.
700 */
701 int
702 esl_dataheader(FILE *fp, ...)
703 {
704 va_list ap, ap2;
705 int width, len;
706 char *s;
707 int col = 0;
708 int maxcols = 1024; // limit, to avoid scary while(1) alternative
709 int leftjustify;
710 int status;
711
712 va_start(ap, fp);
713 va_copy(ap2, ap);
714 if ( fputc('#', fp) == EOF) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
715 for (col = 0; col < maxcols; col++)
716 {
717 width = va_arg(ap, int);
718 if (width == 0) break;
719 if (width < 0) { leftjustify = TRUE; width = -width; }
720 else { leftjustify = FALSE; }
721 if (col == 0) width -= 2; // First column header -2 char for the "# " prefix
722
723 s = va_arg(ap, char *);
724 len = strlen(s);
725 if (len > width) {
726 if (col == 0) ESL_XEXCEPTION(eslEINVAL, "esl_dataheader(): first arg (%s) too wide for %d-char column ('# ' leader took 2 chars)", s, width);
727 else ESL_XEXCEPTION(eslEINVAL, "esl_dataheader(): arg %d (%s) too wide for %d-char column", col, s, width);
728 }
729
730 if (leftjustify) { if ( fprintf(fp, " %-*s", width, s) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); }
731 else { if ( fprintf(fp, " %*s", width, s) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); }
732 }
733 if (col == maxcols) ESL_XEXCEPTION( eslEINVAL, "esl_dataheader(): too many args");
734 if ( fputc('\n', fp) == EOF) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
735
736 maxcols = col;
737 for (col = 0; col < maxcols; col++)
738 {
739 width = va_arg(ap2, int);
740 if (width < 0) width = -width;
741 if (col == 0) width -= 1;
742 (void) va_arg(ap2, char *);
743
744 if (col == 0) { if ( fputc('#', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
745 else { if ( fputc(' ', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed"); }
746 while (width--)
747 if ( fputc('-', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
748 }
749 if (fputc('\n', fp) == EOF) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
750
751 va_end(ap);
752 va_end(ap2);
753 return eslOK;
754
755 ERROR:
756 va_end(ap);
757 va_end(ap2);
758 return status;
759 }
760
761
762 /*-------------------- end, standard miniapp banner --------------------------*/
763
764
765
766
767 /******************************************************************************
768 * 4. Replacements for C library functions
769 * fgets() -> esl_fgets() fgets() with dynamic allocation
770 * printf() -> esl_printf() printf() wrapped in our exception handling
771 * strdup() -> esl_strdup() strdup() is not ANSI
772 * strcat() -> esl_strcat() strcat() with dynamic allocation
773 * strtok() -> esl_strtok() threadsafe strtok()
774 * sprintf() -> esl_sprintf() sprintf() with dynamic allocation
775 * strcmp() -> esl_strcmp() strcmp() tolerant of NULL strings
776 *****************************************************************************/
777
778 /* Function: esl_fgets()
779 *
780 * Purpose: Dynamic allocation version of fgets(),
781 * capable of reading almost unlimited line lengths.
782 *
783 * Args: buf - ptr to a string (may be reallocated)
784 * n - ptr to current allocated length of buf,
785 * (may be changed)
786 * fp - open file ptr for reading
787 *
788 * Before the first call to esl_fgets(),
789 * initialize buf to NULL and n to 0.
790 * They're a linked pair, so don't muck with the
791 * allocation of buf or the value of n while
792 * you're still doing esl_fgets() calls with them.
793 *
794 * Returns: <eslOK> on success.
795 * Returns <eslEOF> on normal end-of-file.
796 *
797 * When <eslOK>:
798 * <*buf> points to a <NUL>-terminated line from the file.
799 * <*n> contains the current allocated length for <*buf>.
800 *
801 * Caller must free <*buf> eventually.
802 *
803 * Throws: <eslEMEM> on an allocation failure.
804 *
805 * Example: char *buf = NULL;
806 * int n = 0;
807 * FILE *fp = fopen("my_file", "r");
808 *
809 * while (esl_fgets(&buf, &n, fp) == eslOK)
810 * {
811 * do stuff with buf;
812 * }
813 * if (buf != NULL) free(buf);
814 */
815 int
816 esl_fgets(char **buf, int *n, FILE *fp)
817 {
818 int status;
819 char *s;
820 int len;
821 int pos;
822
823 if (*n == 0)
824 {
825 ESL_ALLOC(*buf, sizeof(char) * 128);
826 *n = 128;
827 }
828
829 /* Simple case 1. We're sitting at EOF, or there's an error.
830 * fgets() returns NULL, so we return EOF.
831 */
832 if (fgets(*buf, *n, fp) == NULL) return eslEOF;
833
834 /* Simple case 2. fgets() got a string, and it reached EOF doing it.
835 * return success status, so caller can use
836 * the last line; on the next call we'll
837 * return the 0 for the EOF.
838 */
839 if (feof(fp)) return eslOK;
840
841 /* Simple case 3. We got a complete string, with \n,
842 * and don't need to extend the buffer.
843 */
844 len = strlen(*buf);
845 if ((*buf)[len-1] == '\n') return eslOK;
846
847 /* The case we're waiting for. We have an incomplete string,
848 * and we have to extend the buffer one or more times. Make
849 * sure we overwrite the previous fgets's \0 (hence +(n-1)
850 * in first step, rather than 128, and reads of 129, not 128).
851 */
852 pos = (*n)-1;
853 while (1) {
854 ESL_REALLOC(*buf, sizeof(char) * (*n+128));
855 *n += 128;
856 s = *buf + pos;
857 if (fgets(s, 129, fp) == NULL) return eslOK;
858 len = strlen(s);
859 if (s[len-1] == '\n') return eslOK;
860 pos += 128;
861 }
862 /*NOTREACHED*/
863 return eslOK;
864
865 ERROR:
866 if (*buf != NULL) free(*buf);
867 *buf = NULL;
868 *n = 0;
869 return status;
870 }
871
872
873 /* Function: esl_fprintf()
874 * Synopsis: fprintf() wrapped in our exception handling
875 * Incept: SRE, Thu Jun 14 09:43:59 2018
876 *
877 * Purpose: <fprintf()> wrapped in Easel exception handling. See
878 * <esl_printf()> for rationale.
879 *
880 * Returns: <eslOK> on success.
881 *
882 * Throws: <eslEWRITE> on failure.
883 */
884 int
885 esl_fprintf(FILE *fp, const char *format, ...)
886 {
887 if (fp && format)
888 {
889 va_list argp;
890 va_start(argp, format);
891 if ( vfprintf(fp, format, argp) < 0 ) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
892 va_end(argp);
893 }
894 return eslOK;
895 }
896
897
898
899 /* Function: esl_printf()
900 * Synopsis: printf() wrapped in our exception handling
901 * Incept: SRE, Thu Jun 14 09:17:17 2018
902 *
903 * Purpose: <printf()> wrapped in Easel exception handling.
904 *
905 * Rarely and insidiously, <printf()> can fail -- for
906 * example, when output is redirected to a file and a disk
907 * fills up. Every <printf()> needs to guard against this,
908 * else output could silently fail. It seems slightly
909 * cleaner to use Easel's idiomatic:
910 *
911 * ```
912 * if ((status = esl_printf(...)) != eslOK) return status; // no cleanup
913 * if ((status = esl_printf(...)) != eslOK) goto ERROR; // with cleanup
914 * ```
915 *
916 * as opposed to having to invoke
917 * <ESL_EXCEPTION_SYS(eslEWRITE, "write failed")> each
918 * time.
919 *
920 * Returns: <eslOK> on success.
921 *
922 * Throws: <eslEWRITE> on failure.
923 */
924 int
925 esl_printf(const char *format, ...)
926 {
927 if (format)
928 {
929 va_list argp;
930 va_start(argp, format);
931 if ( vprintf(format, argp) < 0 ) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
932 va_end(argp);
933 }
934 return eslOK;
935 }
936
937
938
939
940
941
942
943 /* Function: esl_strdup()
944 *
945 * Purpose: Makes a duplicate of string <s>, puts it in <ret_dup>.
946 * Caller can pass string length <n>, if it's known,
947 * to save a strlen() call; else pass -1 to have the string length
948 * determined.
949 *
950 * Tolerates <s> being <NULL>; in which case,
951 * returns <eslOK> with <*ret_dup> set to <NULL>.
952 *
953 * Args: s - string to duplicate (NUL-terminated)
954 * n - length of string, if known; -1 if unknown.
955 * ret_dup - RETURN: duplicate of <s>.
956 *
957 * Returns: <eslOK> on success, and <ret_dup> is valid.
958 *
959 * Throws: <eslEMEM> on allocation failure.
960 */
961 int
962 esl_strdup(const char *s, int64_t n, char **ret_dup)
963 {
964 int status;
965 char *new = NULL;
966
967 if (s == NULL) {*ret_dup = NULL; return eslOK; }
968 if (n < 0) n = strlen(s);
969
970 ESL_ALLOC(new, sizeof(char) * (n+1));
971 strcpy(new, s);
972
973 *ret_dup = new;
974 return eslOK;
975
976 ERROR:
977 if (new) free(new);
978 *ret_dup = NULL;
979 return status;
980 }
981
982
983 /* Function: esl_strcat()
984 *
985 * Purpose: Dynamic memory version of strcat().
986 * Appends <src> to the string that <dest> points to,
987 * extending allocation for dest if necessary. Caller
988 * can optionally provide the length of <*dest> in
989 * <ldest>, and the length of <src> in <lsrc>; if
990 * either of these is -1, <esl_strcat()> calls <strlen()>
991 * to determine the length. Providing length information,
992 * if known, accelerates the routine.
993 *
994 * <*dest> may be <NULL>, in which case this is equivalent
995 * to a <strdup()> of <src> (that is, <*dest> is allocated
996 * rather than reallocated).
997 *
998 * <src> may be <NULL>, in which case <dest> is unmodified.
999 *
1000 * Note: One timing experiment (100 successive appends of
1001 * 1-255 char) shows esl_strcat() has about a 20%
1002 * overhead relative to strcat(). If optional
1003 * length info is passed, esl_strcat() is about 30%
1004 * faster than strcat().
1005 *
1006 * Args: dest - ptr to string (char **), '\0' terminated
1007 * ldest - length of dest, if known; or -1 if length unknown.
1008 * src - string to append to dest, '\0' terminated
1009 * lsrc - length of src, if known; or -1 if length unknown.
1010 *
1011 * Returns: <eslOK> on success; <*dest> is (probably) reallocated,
1012 * modified, and nul-terminated.
1013 *
1014 * Throws: <eslEMEM> on allocation failure; initial state of <dest>
1015 * is unaffected.
1016 */
1017 int
1018 esl_strcat(char **dest, int64_t ldest, const char *src, int64_t lsrc)
1019 {
1020 int status;
1021 int64_t len1, len2;
1022
1023 if (ldest < 0) len1 = ((*dest == NULL) ? 0 : strlen(*dest));
1024 else len1 = ldest;
1025
1026 if (lsrc < 0) len2 = (( src == NULL) ? 0 : strlen(src));
1027 else len2 = lsrc;
1028
1029 if (len2 == 0) return eslOK;
1030
1031 ESL_REALLOC(*dest, sizeof(char) * (len1+len2+1));
1032
1033 memcpy((*dest)+len1, src, len2);
1034 (*dest)[len1+len2] = '\0';
1035 return eslOK;
1036
1037 ERROR:
1038 return status;
1039 }
1040
1041 /* Function: esl_strmapcat()
1042 * Synopsis: Version of esl_strcat that uses an inmap.
1043 *
1044 * Purpose: Append the contents of string or memory line <src>
1045 * of length <lsrc> to a string. The destination
1046 * string and its length are passed as pointers <*dest>
1047 * and <*ldest>, so the string can be reallocated
1048 * and the length updated. When appending, map each
1049 * character <src[i]> to a new character <inmap[src[i]]>
1050 * in the destination string. The destination string
1051 * <*dest> is NUL-terminated on return (even if it
1052 * wasn't to begin with).
1053 *
1054 * One reason to use the inmap is to enable parsers to
1055 * ignore some characters in an input string or buffer,
1056 * such as whitespace (mapped to <eslDSQ_IGNORED>). Of
1057 * course this means, unlike <esl_strcat()> the new length
1058 * isn't just <ldest+lsrc>, because we don't know how many
1059 * characters get appended until we've processed them
1060 * through the inmap -- that's why this function takes
1061 * <*ldest> by reference, whereas <esl_strcat()> takes it
1062 * by value.
1063 *
1064 * If <*dest> is a NUL-terminated string and the caller
1065 * doesn't know its length, <*ldest> may be passed as -1.
1066 * Providing the length saves a <strlen()> call. If <*dest>
1067 * is a memory line, providing <*ldest> is mandatory. Same
1068 * goes for <src> and <lsrc>.
1069 *
1070 * <*dest> may be <NULL>, in which case it is allocated
1071 * and considered to be an empty string to append to.
1072 * When <*dest> is <NULL> the input <*ldest> should be <0>
1073 * or <-1>.
1074 *
1075 * The caller must provide a <src> that it already knows
1076 * should be entirely appended to <*dest>, except for
1077 * perhaps some ignored characters. No characters may be
1078 * mapped to <eslDSQ_EOL> or <eslDSQ_EOD>. The reason for
1079 * this is that we're going to allocate <*dest> for
1080 * <*ldest+lsrc> chars. If <src> were a large memory buffer,
1081 * only a fraction of which needed to be appended (up to
1082 * an <eslDSQ_EOL> or <eslDSQ_EOD>), this reallocation would
1083 * be inefficient.
1084 *
1085 * Args: inmap - an Easel input map, inmap[0..127];
1086 * inmap[0] is special: set to the 'unknown' character to
1087 * replace invalid input chars.
1088 * *dest - destination string or memory to append to, passed by reference
1089 * *ldest - length of <*dest> (or -1), passed by reference
1090 * src - string or memory to inmap and append to <*dest>
1091 * lsrc - length of <src> to map and append (or -1).
1092 *
1093 * Returns: <eslOK> on success. Upon successful return, <*dest> is
1094 * reallocated and contains the new string (with from 0 to <lsrc>
1095 * appended characters), NUL-terminated.
1096 *
1097 * <eslEINVAL> if one or more characters in the input <src>
1098 * are mapped to <eslDSQ_ILLEGAL>. Appending nonetheless
1099 * proceeds to completion, with any illegal characters
1100 * represented as '?' in <*dest> and counted in <*ldest>.
1101 * This is a normal error, because the string <src> may be
1102 * user input. The caller may want to call some sort of
1103 * validation function on <src> if an <eslEINVAL> error is
1104 * returned, in order to report some helpful diagnostics to
1105 * the user.
1106 *
1107 * Throws: <eslEMEM> on allocation or reallocation failure.
1108 * <eslEINCONCEIVABLE> on internal coding error; for example,
1109 * if the inmap tries to map an input character to <eslDSQ_EOD>,
1110 * <eslDSQ_EOL>, or <eslDSQ_SENTINEL>. On exceptions, <*dest>
1111 * and <*ldest> should not be used by the caller except to
1112 * free <*dest>; their state may have been corrupted.
1113 *
1114 * Note: This deliberately mirrors <esl_abc_dsqcat()>, so
1115 * that sequence file parsers have comparable behavior whether
1116 * they're working with text-mode or digital-mode input.
1117 *
1118 * Might be useful to create a variant that also handles
1119 * eslDSQ_EOD (and eslDSQ_EOL?) and returns the number of
1120 * residues parsed. This'd allow a FASTA parser, for
1121 * instance, to use this method while reading buffer pages
1122 * rather than lines; it could define '>' as eslDSQ_EOD.
1123 */
1124 int
1125 esl_strmapcat(const ESL_DSQ *inmap, char **dest, int64_t *ldest, const char *src, esl_pos_t lsrc)
1126 {
1127 int status = eslOK;
1128
1129 if (*ldest < 0) *ldest = ( (*dest) ? strlen(*dest) : 0);
1130 if ( lsrc < 0) lsrc = ( (*src) ? strlen(src) : 0);
1131
1132 if (lsrc == 0) goto ERROR; /* that'll return eslOK, leaving *dest untouched, and *ldest its length. */
1133
1134 ESL_REALLOC(*dest, sizeof(char) * (*ldest + lsrc + 1)); /* includes case of a new alloc of *dest */
1135 return esl_strmapcat_noalloc(inmap, *dest, ldest, src, lsrc);
1136
1137 ERROR:
1138 return status;
1139 }
1140
1141 /* Function: esl_strmapcat_noalloc()
1142 * Synopsis: Version of esl_strmapcat() that does no reallocation.
1143 *
1144 * Purpose: Same as <esl_strmapcat()>, but with no reallocation. The
1145 * pointer to the destination string <dest> is passed by
1146 * value, not by reference, because it will not be changed.
1147 * Caller has allocated at least <*ldest + lsrc + 1> bytes
1148 * in <dest>. In this version, <*ldest> and <lsrc> are not
1149 * optional; caller must know the lengths of both the old
1150 * string and the new source.
1151 *
1152 * Note: (see note on esl_abc_dsqcat_noalloc() for rationale)
1153 */
1154 int
1155 esl_strmapcat_noalloc(const ESL_DSQ *inmap, char *dest, int64_t *ldest, const char *src, esl_pos_t lsrc)
1156 {
1157 int64_t xpos;
1158 esl_pos_t cpos;
1159 ESL_DSQ x;
1160 int status = eslOK;
1161
1162 for (xpos = *ldest, cpos = 0; cpos < lsrc; cpos++)
1163 {
1164 if (! isascii(src[cpos])) { dest[xpos++] = inmap[0]; status = eslEINVAL; continue; }
1165
1166 x = inmap[(int) src[cpos]];
1167 if (x <= 127) dest[xpos++] = x;
1168 else switch (x) {
1169 case eslDSQ_SENTINEL: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_SENTINEL"); break;
1170 case eslDSQ_ILLEGAL: dest[xpos++] = inmap[0]; status = eslEINVAL; break;
1171 case eslDSQ_IGNORED: break;
1172 case eslDSQ_EOL: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_EOL"); break;
1173 case eslDSQ_EOD: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_EOD"); break;
1174 default: ESL_EXCEPTION(eslEINCONCEIVABLE, "bad inmap, no such ESL_DSQ code"); break;
1175 }
1176 }
1177
1178 dest[xpos] = '\0';
1179 *ldest = xpos;
1180 return status;
1181 }
1182
1183
1184 /* Function: esl_strtok()
1185 * Synopsis: Threadsafe version of C's <strtok()>
1186 *
1187 * Purpose: Thread-safe version of <strtok()> for parsing next token in
1188 * a string.
1189 *
1190 * Increments <*s> while <**s> is a character in <delim>,
1191 * then stops; the first non-<delim> character defines the
1192 * beginning of a token. Increments <*s> until it reaches
1193 * the next delim character (or \verb+\0+); this defines the end
1194 * of the token, and this character is replaced with
1195 * \verb+\0+. <*s> is then reset to point to the next character
1196 * after the \verb+\0+ that was written, so successive calls can
1197 * extract tokens in succession. Sets <*ret_tok> to point at
1198 * the beginning of the token, and returns <eslOK>.
1199 *
1200 * If a token is not found -- if <*s> already points to
1201 * \verb+\0+, or to a string composed entirely of characters in
1202 * <delim> -- then returns <eslEOL>, with <*ret_tok> set to
1203 * <NULL>.
1204 *
1205 * <*s> cannot be a constant string, since we write \verb+\0+'s
1206 * to it; caller must be willing to have this string
1207 * modified. And since we walk <*s> through the string as we
1208 * parse, the caller wants to use a tmp pointer <*s>, not
1209 * the original string itself.
1210 *
1211 * Example:
1212 * char *tok;
1213 * char *s;
1214 * char buf[50] = "This is a sentence.";
1215 *
1216 * s = buf;
1217 * esl_strtok(&s, " ", &tok);
1218 * tok is "This"; s is "is a sentence."
1219 * esl_strtok(&s, " ", &tok);
1220 * tok is "is"; s is " a sentence.".
1221 * esl_strtok(&s, " ", &tok);
1222 * tok is "a"; s is "sentence.".
1223 * esl_strtok(&s, " ", &tok, &len);
1224 * tok is "sentence."; s is "\0".
1225 * esl_strtok(&s, " ", &tok, &len);
1226 * returned eslEOL; tok is NULL; s is "\0".
1227 *
1228 * Args: s - a tmp, modifiable ptr to a string
1229 * delim - characters that delimits tokens
1230 * ret_tok - RETURN: ptr to \0-terminated token
1231 *
1232 * Returns: <eslOK> on success, <*ret_tok> points to next token, and
1233 * <*s> points to next character following the token.
1234 *
1235 * Returns <eslEOL> on end of line; in which case <*s>
1236 * points to the terminal \verb+\0+ on the line, and <*ret_tok>
1237 * is <NULL>.
1238 */
1239 int
1240 esl_strtok(char **s, char *delim, char **ret_tok)
1241 {
1242 return esl_strtok_adv(s, delim, ret_tok, NULL, NULL);
1243 }
1244
1245
1246 /* Function: esl_strtok_adv()
1247 * Synopsis: More advanced interface to <esl_strtok()>
1248 *
1249 * Purpose: Same as <esl_strtok()>, except the caller may also
1250 * optionally retrieve the length of the token in <*opt_toklen>,
1251 * and the token-ending character that was replaced by \verb+\0+
1252 * in <*opt_endchar>.
1253 *
1254 * Args: s - a tmp, modifiable ptr to string
1255 * delim - characters that delimits tokens
1256 * ret_tok - RETURN: ptr to \0-terminated token string
1257 * opt_toklen - optRETURN: length of token; pass NULL if not wanted
1258 * opt_endchar - optRETURN: character that was replaced by <\0>.
1259 *
1260 * Returns: <eslOK> on success, <*ret_tok> points to next token, <*s>
1261 * points to next character following the token,
1262 * <*opt_toklen> is the <strlen()> length of the token in
1263 * characters (excluding its terminal \verb+\0+), and <*opt_endchar>
1264 * is the character that got replaced by \verb+\0+ to form the token.
1265 *
1266 * Returns <eslEOL> if no token is found (end of line); in
1267 * which case <*s> points to the terminal \verb+\0+ on the line,
1268 * <*ret_tok> is <NULL>, <*opt_toklen> is 0 and
1269 * <*opt_endchar> is \verb+\0+.
1270 */
1271 int
1272 esl_strtok_adv(char **s, char *delim, char **ret_tok, int *opt_toklen, char *opt_endchar)
1273 {
1274 char *end;
1275 char *tok = *s;
1276 char c = '\0';
1277 int n = 0;
1278 int status = eslEOL; /* unless proven otherwise */
1279
1280 /* contract checks */
1281 ESL_DASSERT1(( s != NULL ));
1282 ESL_DASSERT1(( delim != NULL ));
1283
1284 tok += strspn(tok, delim);
1285 if (! *tok) tok = NULL; /* if *tok = 0, EOL, no token left */
1286 else
1287 {
1288 n = strcspn(tok, delim);
1289 end = tok + n;
1290 if (*end == '\0') *s = end; /* a final token that extends to end of string */
1291 else
1292 {
1293 c = *end; /* internal token: terminate with \0 */
1294 *end = '\0';
1295 *s = end+1;
1296 }
1297 status = eslOK;
1298 }
1299
1300 *ret_tok = tok;
1301 if (opt_toklen != NULL) *opt_toklen = n;
1302 if (opt_endchar != NULL) *opt_endchar = c;
1303 return status;
1304 }
1305
1306
1307 /* Function: esl_sprintf()
1308 * Synopsis: Dynamic allocation version of sprintf().
1309 *
1310 * Purpose: Like ANSI C's <sprintf()>, except the string
1311 * result is dynamically allocated, and returned
1312 * through <*ret_s>.
1313 *
1314 * Caller is responsible for free'ing <*ret_s>.
1315 *
1316 * As a special case to facilitate some optional string
1317 * initializations, if <format> is <NULL>, <*ret_s> is set
1318 * to <NULL>.
1319 *
1320 * Returns: <eslOK> on success, and <*ret_s> is the resulting
1321 * string.
1322 *
1323 * Throws: <eslEMEM> on allocation failure.
1324 * <eslESYS> if a <*printf()> library call fails.
1325 */
1326 int
1327 esl_sprintf(char **ret_s, const char *format, ...)
1328 {
1329 va_list ap;
1330 int status;
1331
1332 va_start(ap, format);
1333 status = esl_vsprintf(ret_s, format, &ap);
1334 va_end(ap);
1335 return status;
1336 }
1337
1338 /* Function: esl_vsprintf()
1339 * Synopsis: Dynamic allocation version of vsprintf()
1340 *
1341 * Purpose: Like ANSI C's <vsprintf>, except the string
1342 * result is dynamically allocated, and returned
1343 * through <*ret_s>.
1344 *
1345 * Caller is responsible for free'ing <*ret_s>.
1346 *
1347 * As a special case to facilitate some optional string
1348 * initializations, if <format> is <NULL>, <*ret_s> is set
1349 * to <NULL>.
1350 *
1351 * Returns: <eslOK> on success, and <*ret_s> is the resulting
1352 * string.
1353 *
1354 * Throws: <eslEMEM> on allocation failure.
1355 * <eslESYS> if a <*printf()> library call fails.
1356 */
1357 int
1358 esl_vsprintf(char **ret_s, const char *format, va_list *ap)
1359 {
1360 char *s = NULL;
1361 va_list ap2;
1362 int n1, n2;
1363 int status;
1364
1365 if (format == NULL) { *ret_s = NULL; return eslOK; }
1366
1367 va_copy(ap2, *ap);
1368 n1 = strlen(format) * 2; /* initial guess at string size needed */
1369 ESL_ALLOC(s, sizeof(char) * (n1+1));
1370 if ((n2 = vsnprintf(s, n1+1, format, *ap)) >= n1)
1371 {
1372 ESL_REALLOC(s, sizeof(char) * (n2+1));
1373 if (vsnprintf(s, n2+1, format, ap2) == -1) ESL_XEXCEPTION(eslESYS, "vsnprintf() failed");
1374 }
1375 else if (n2 == -1) ESL_XEXCEPTION(eslESYS, "vsnprintf() failed");
1376
1377 va_end(ap2);
1378 *ret_s = s;
1379 return eslOK;
1380
1381 ERROR:
1382 if (s) free(s);
1383 va_end(ap2);
1384 *ret_s = NULL;
1385 return status;
1386 }
1387
1388
1389 /* Function: esl_strcmp()
1390 * Synopsis: a strcmp() that treats NULL as empty string.
1391 *
1392 * Purpose: A version of <strcmp()> that accepts <NULL>
1393 * strings. If both <s1> and <s2> are non-<NULL>
1394 * they are compared by <strcmp()>. If both are
1395 * <NULL>, return 0 (as if they are identical
1396 * strings). If only <s1> (or <s2>) is non-<NULL>,
1397 * return 1 (or -1), corresponding to ordering
1398 * any non-<NULL> string as greater than a <NULL>
1399 * string.
1400 *
1401 * (Easel routinely uses NULL to mean an unset optional
1402 * string, and often needs to compare two strings for
1403 * equality.)
1404 *
1405 * Returns: 0 if <s1 == s2>; 1 if <s1 > s2>; -1 if <s1 < s2>.
1406 */
1407 int
1408 esl_strcmp(const char *s1, const char *s2)
1409 {
1410 if (s1 && s2) return strcmp(s1, s2);
1411 else if (s1) return 1;
1412 else if (s2) return -1;
1413 else return 0;
1414 }
1415 /*--------- end, improved replacement ANSI C functions ----------*/
1416
1417
1418
1419 /*****************************************************************
1420 * 5. Portable drop-in replacements for non-standard C functions
1421 *****************************************************************/
1422
1423 #ifndef HAVE_STRCASECMP
1424 /* Function: esl_strcasecmp()
1425 *
1426 * Purpose: Compare strings <s1> and <s2>. Return -1 if
1427 * <s1> is alphabetically less than <s2>, 0 if they
1428 * match, and 1 if <s1> is alphabetically greater
1429 * than <s2>. All matching is case-insensitive.
1430 *
1431 * Args: s1 - string 1, \0 terminated
1432 * s2 - string 2, \0 terminated
1433 *
1434 * Returns: -1, 0, or 1, if <s1> is less than, equal, or
1435 * greater than <s2>, case-insensitively.
1436 *
1437 * Throws: (no abnormal error conditions)
1438 */
1439 int
1440 esl_strcasecmp(const char *s1, const char *s2)
1441 {
1442 int i, c1, c2;
1443
1444 for (i = 0; s1[i] != '\0' && s2[i] != '\0'; i++)
1445 {
1446 c1 = s1[i]; /* total paranoia. don't trust toupper() to */
1447 c2 = s2[i]; /* leave the original unmodified; make a copy. */
1448
1449 if (islower(c1)) c1 = toupper(c1);
1450 if (islower(c2)) c2 = toupper(c2);
1451
1452 if (c1 < c2) return -1;
1453 else if (c1 > c2) return 1;
1454 }
1455
1456 if (s1[i] != '\0') return 1; /* prefixes match, but s1 is longer */
1457 else if (s2[i] != '\0') return -1; /* prefixes match, s2 is longer */
1458
1459 return 0; /* else, a case-insensitive match. */
1460 }
1461 #endif /* ! HAVE_STRCASECMP */
1462
1463
1464 #ifndef HAVE_STRSEP
1465 /* Function: esl_strsep()
1466 * Synopsis: Separate strings.
1467 * Incept: Contributed by Sebastien Jaenick, July 2016.
1468 *
1469 * Purpose: Portable replacement for strsep(). Solaris, for example,
1470 * does not have it.
1471 *
1472 * Get next token from string *stringp, where tokens are
1473 * possibly-empty strings separated by characters from
1474 * delim.
1475 *
1476 * Writes NULs into the string at *stringp to end tokens.
1477 * delim need not remain constant from call to call. On
1478 * return, *stringp points past the last NUL written (if
1479 * there might be further tokens), or is NULL (if there are
1480 * definitely no more tokens).
1481 *
1482 * If *stringp is NULL, strsep returns NULL.
1483 *
1484 * Note:
1485 * Taken from FreeBSD, under BSD open source license:
1486 *
1487 * Copyright (c) 1990, 1993
1488 * The Regents of the University of California. All rights reserved.
1489 *
1490 * Redistribution and use in source and binary forms, with or without
1491 * modification, are permitted provided that the following conditions
1492 * are met:
1493 * 1. Redistributions of source code must retain the above copyright
1494 * notice, this list of conditions and the following disclaimer.
1495 * 2. Redistributions in binary form must reproduce the above copyright
1496 * notice, this list of conditions and the following disclaimer in the
1497 * documentation and/or other materials provided with the distribution.
1498 * 4. Neither the name of the University nor the names of its contributors
1499 * may be used to endorse or promote products derived from this software
1500 * without specific prior written permission.
1501 *
1502 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1503 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1504 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1505 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1506 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1507 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1508 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1509 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1510 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1511 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1512 * SUCH DAMAGE.
1513 */
1514 char *
1515 esl_strsep(char **stringp, const char *delim)
1516 {
1517 const char *spanp;
1518 char *s;
1519 int c, sc;
1520 char *tok;
1521
1522 if ((s = *stringp) == NULL)
1523 return NULL;
1524 for (tok = s;;) {
1525 c = *s++;
1526 spanp = delim;
1527 do {
1528 if ((sc = *spanp++) == c) {
1529 if (c == 0)
1530 s = NULL;
1531 else
1532 s[-1] = 0;
1533 *stringp = s;
1534 return tok;
1535 }
1536 } while (sc != 0);
1537 }
1538 /* NOTREACHED */
1539 }
1540 #endif
1541 /*------------- end, portable drop-in replacements --------------*/
1542
1543
1544 /*****************************************************************
1545 * 6. Additional string functions, esl_str*()
1546 *****************************************************************/
1547
1548 /* Function: esl_strchop()
1549 *
1550 * Purpose: Chops trailing whitespace off of a string <s> (or if <s>
1551 * is NULL, do nothing).
1552 * <n> is the length of the input string, if known; or pass <n=-1>
1553 * if length is unknown.
1554 *
1555 * Returns: <eslOK> on success.
1556 *
1557 * Throws: (no abnormal error conditions)
1558 *
1559 * Xref: from squid's StringChop().
1560 */
1561 int
1562 esl_strchop(char *s, int64_t n)
1563 {
1564 int i;
1565 if (s == NULL) return eslOK;
1566 if (n < 0) n = strlen(s);
1567 for (i = n-1; i>=0 && isspace((int) s[i]); i--);
1568 s[i+1] = '\0';
1569 return eslOK;
1570 }
1571
1572
1573 /* Function: esl_strdealign()
1574 * Synopsis: Dealign a string according to gaps in a reference aseq.
1575 *
1576 * Purpose: Dealign string <s> in place, by removing any characters
1577 * aligned to gaps in <aseq>. Gap characters are defined in the
1578 * string <gapstring>; for example, <-_.>. Optionally return the
1579 * unaligned length of <s> in characters in <*opt_rlen>.
1580 *
1581 * By providing a reference <aseq> to dealign against, this
1582 * function can dealign aligned annotation strings, such as
1583 * secondary structure or surface accessibility strings.
1584 * If <s> is the same as <aseq>, then the aligned sequence
1585 * itself is dealigned in place.
1586 *
1587 * To dealign both annotations and sequence, do the
1588 * sequence last, since you need it as the reference <aseq>
1589 * when doing the annotations.
1590 *
1591 * It is safe to pass a <NULL> <s> (an unset optional
1592 * annotation), in which case the function no-ops and
1593 * returns <eslOK>.
1594 *
1595 * Args: s - string to dealign
1596 * aseq - reference aligned sequence seq
1597 * gapchars - definition of gap characters ("-_." for example)
1598 * opt_rlen - optRETURN: number of residues in <s> after dealign
1599 *
1600 * Returns: <eslOK> on success.
1601 */
1602 int
1603 esl_strdealign(char *s, const char *aseq, const char *gapchars, int64_t *opt_rlen)
1604 {
1605 int64_t n = 0;
1606 int64_t apos;
1607
1608 if (s == NULL) return eslOK;
1609
1610 for (apos = 0; aseq[apos] != '\0'; apos++)
1611 if (strchr(gapchars, aseq[apos]) == NULL)
1612 s[n++] = s[apos];
1613 s[n] = '\0';
1614
1615 if (opt_rlen != NULL) *opt_rlen = n;
1616 return eslOK;
1617 }
1618
1619
1620 /* Function: esl_str_IsBlank()
1621 * Synopsis: Return TRUE if <s> is all whitespace; else FALSE.
1622 *
1623 * Purpose: Given a NUL-terminated string <s>; return <TRUE> if
1624 * string is entirely whitespace (as defined by <isspace()>),
1625 * and return FALSE if not.
1626 */
1627 int
1628 esl_str_IsBlank(char *s)
1629 {
1630 for (; *s; s++) if (!isspace(*s)) return FALSE;
1631 return TRUE;
1632 }
1633
1634 /* Function: esl_str_IsInteger()
1635 * Synopsis: Return TRUE if <s> represents an integer; else FALSE.
1636 *
1637 * Purpose: Given a NUL-terminated string <s>, return TRUE
1638 * if the complete string is convertible to a base-10 integer
1639 * by the rules of <strtol()> or <atoi()>.
1640 *
1641 * Leading and trailing whitespace is allowed, but otherwise
1642 * the entire string <s> must be convertable. (Unlike <strtol()>
1643 * itself, which will convert a prefix. ' 99 foo' converts
1644 * to 99, but <esl_str_IsInteger()> will return FALSE.
1645 *
1646 * If <s> is <NULL>, FALSE is returned.
1647 */
1648 int
1649 esl_str_IsInteger(char *s)
1650 {
1651 char *endp;
1652
1653 if (s == NULL) return FALSE; /* it's NULL */
1654 (void) strtol(s, &endp, 10); /* don't need result itself, discard to void */
1655 if (endp == s) return FALSE; /* strtol() can't convert it */
1656 for (s = endp; *s != '\0'; s++)
1657 if (! isspace(*s)) return FALSE; /* it has trailing nonconverted nonwhitespace */
1658 return TRUE;
1659 }
1660
1661 /* Function: esl_str_IsReal()
1662 * Synopsis: Return TRUE if string <s> represents a real number; else FALSE.
1663 *
1664 * Purpose: Given a NUL-terminated string <s>, return <TRUE>
1665 * if the string is completely convertible to a floating-point
1666 * real number by the rules of <strtod()> and <atof()>.
1667 * (Which allow for exponential forms, hexadecimal forms,
1668 * and case-insensitive INF, INFINITY, NAN, all w/ optional
1669 * leading +/- sign.)
1670 *
1671 * No trailing garbage is allowed, unlike <strtod()>. The
1672 * entire string must be convertible, allowing leading and
1673 * trailing whitespace is allowed. '99.0 foo' converts
1674 * to 99.0 with <strtod()> but is <FALSE> for
1675 * <esl_str_IsReal()>. ' 99.0 ' is <TRUE>.
1676 *
1677 * If <s> is <NULL>, return <FALSE>.
1678 */
1679 int
1680 esl_str_IsReal(char *s)
1681 {
1682 char *endp;
1683 double val;
1684
1685 if (! s) return FALSE; /* <s> is NULL */
1686 val = strtod(s, &endp);
1687 if (val == 0.0f && endp == s) return FALSE; /* strtod() can't convert it */
1688 for (s = endp; *s != '\0'; s++)
1689 if (! isspace(*s)) return FALSE; /* it has trailing nonconverted nonwhitespace */
1690 return TRUE;
1691 }
1692
1693
1694 /* Function: esl_str_GetMaxWidth()
1695 * Synopsis: Returns maximum strlen() in an array of strings.
1696 *
1697 * Purpose: Returns the length of the longest string in
1698 * an array of <n> strings <s[0..n-1]>. If <n=0>,
1699 * returns 0. Any <s[i]> that's <NULL> is counted
1700 * as zero length.
1701 */
1702 int64_t
1703 esl_str_GetMaxWidth(char **s, int n)
1704 {
1705 int64_t max = 0;
1706 int64_t len;
1707 int i;
1708
1709 for (i = 0; i < n; i++)
1710 if (s[i]) {
1711 len = strlen(s[i]);
1712 if (len > max) max = len;
1713 }
1714 return max;
1715 }
1716
1717
1718 /*-------------- end, additional string functions ---------------*/
1719
1720
1721
1722
1723 /*****************************************************************
1724 * 7. File path/name manipulation, including tmpfiles
1725 *****************************************************************/
1726
1727 /* Function: esl_FileExists()
1728 * Synopsis: Return TRUE if <filename> exists and is readable, else FALSE.
1729 *
1730 * Purpose: Returns TRUE if <filename> exists and is readable, else FALSE.
1731 *
1732 * Xref: squid's FileExists().
1733 */
1734 int
1735 esl_FileExists(const char *filename)
1736 {
1737 #ifdef _POSIX_VERSION
1738 struct stat fileinfo;
1739 if (stat(filename, &fileinfo) != 0) return FALSE;
1740 if (! (fileinfo.st_mode & S_IRUSR)) return FALSE;
1741 return TRUE;
1742 #else
1743 FILE *fp;
1744 if ((fp = fopen(filename, "r"))) { fclose(fp); return TRUE; }
1745 return FALSE;
1746 #endif
1747 }
1748
1749
1750 /* Function: esl_FileTail()
1751 * Synopsis: Extract filename, removing path prefix.
1752 *
1753 * Purpose: Given a full pathname <path>, extract the filename
1754 * without the directory path; return it via
1755 * <ret_filename>. <ret_filename> space is allocated
1756 * here, and must be free'd by the caller.
1757 * For example:
1758 * </foo/bar/baz.1> becomes <baz.1>;
1759 * <foo/bar> becomes <bar>;
1760 * <foo> becomes <foo>; and
1761 * </> becomes the empty string.
1762 *
1763 * If <nosuffix> is <TRUE>, the rightmost trailing ".foo" extension
1764 * is removed too. The suffix is defined as everything following
1765 * the rightmost period in the filename in <path>:
1766 * with <nosuffix> <TRUE>,
1767 * <foo.2/bar.idx> becomes <bar>,
1768 * <foo.2/bar> becomes <bar>, and
1769 * <foo.2/bar.1.3> becomes <bar.1>.
1770 *
1771 * Args: path - full pathname to process, "/foo/bar/baz.1"
1772 * nosuffix - TRUE to remove rightmost suffix from the filename
1773 * ret_file - RETURN: filename portion of the path.
1774 *
1775 * Returns: <eslOK> on success, and <ret_file> points to a newly
1776 * allocated string containing the filename.
1777 *
1778 * Throws: <eslEMEM> on allocation failure.
1779 */
1780 int
1781 esl_FileTail(const char *path, int nosuffix, char **ret_file)
1782 {
1783 int status;
1784 char *tail = NULL;
1785 char *lastslash;
1786 char *lastdot;
1787 /* remove directory prefix */
1788 lastslash = strrchr(path, eslDIRSLASH);
1789 ESL_ALLOC(tail, sizeof(char) * (strlen(path)+1)); /* a little overkill */
1790 if (lastslash == NULL) strcpy(tail, path);
1791 else strcpy(tail, lastslash+1);
1792 /* remove trailing suffix */
1793 if (nosuffix) {
1794 if ((lastdot = strrchr(tail, '.')) != NULL)
1795 *lastdot = '\0';
1796 }
1797 *ret_file = tail;
1798 return eslOK;
1799
1800 ERROR:
1801 if (tail != NULL) free(tail);
1802 *ret_file = NULL;
1803 return status;
1804 }
1805
1806 /* Function: esl_file_Extension()
1807 * Synopsis: Find suffix of a file name; set a memory line on it.
1808 *
1809 * Purpose: Given a path or file name <filename>, and ignoring the
1810 * last <n_ignore> characters, find the rightmost suffix;
1811 * return a pointer to its start in <*ret_sfx> (inclusive
1812 * of the ``.''), and its length in <*ret_n>. If no
1813 * suffix is found, return <eslFAIL> with <*ret_sfx = NULL>
1814 * and <ret_n = 0>.
1815 *
1816 * The <n_ignore> argument allows iterating through more
1817 * than one suffix.
1818 *
1819 * For example, if <filename> is ``./foo/bar/baz.xx.yyy''
1820 * and <n_ignore> is 0, <*ret_sfx> points to ``.yyy'' and
1821 * <*ret_n> is 4. If <n_ignore> is 4, then <*ret_sfx>
1822 * points to ``.xx'' and <ret_n> is 3. If <n_ignore> is 7
1823 * then status is <eslFAIL>.
1824 */
1825 int
1826 esl_file_Extension(char *filename, esl_pos_t n_ignore, char **ret_sfx, esl_pos_t *ret_n)
1827 {
1828 esl_pos_t n1 = strlen(filename) - n_ignore;
1829 esl_pos_t n2;
1830
1831 for (n2 = n1; n2 > 0 && filename[n2-1] != eslDIRSLASH && filename[n2-1] != '.'; n2--) ;
1832
1833 if (n2 <= 0 || filename[n2-1] == eslDIRSLASH)
1834 { *ret_sfx = NULL; *ret_n = 0; return eslFAIL; }
1835
1836 *ret_sfx = filename + n2 - 1;
1837 *ret_n = n1-n2+1;
1838 return eslOK;
1839 }
1840
1841
1842 /* Function: esl_FileConcat()
1843 *
1844 * Purpose: Concatenates directory path prefix <dir> and a filename
1845 * <file>, and returns the new full pathname through
1846 * <ret_path>. If <dir> does not already end in the
1847 * appropriate delimiter (e.g. / for UNIX), one is added.
1848 *
1849 * If <dir> is NULL, then <ret_path> is just the same as
1850 * <file>. Similarly, if <file> already appears to be a
1851 * full path (because its first character is a /), then
1852 * <dir> is ignored and <ret_path> is the same as
1853 * <file>. It wouldn't normally make sense for a caller to
1854 * call this function with such arguments.
1855 *
1856 * <file> may be a relative path. For example,
1857 * if <dir> is "/usr/local" and <file> is "lib/myapp/data",
1858 * <ret_path> will be "/usr/local/lib/myapp/data".
1859 *
1860 * Returns: <eslOK> on success, and puts the path
1861 * in <ret_path>; this string is allocated here,
1862 * and must be free'd by caller with <free()>.
1863 *
1864 * Throws: <eslEMEM> on allocation failure.
1865 * <eslEINVAL> on bad argument.
1866 * In either case, <ret_path> is returned NULL.
1867 *
1868 * Xref: squid's FileConcat().
1869 */
1870 int
1871 esl_FileConcat(const char *dir, const char *file, char **ret_path)
1872 {
1873 char *path = NULL;
1874 int nd, nf;
1875 int status;
1876
1877 if (ret_path != NULL) *ret_path = NULL;
1878 if (file == NULL) ESL_EXCEPTION(eslEINVAL, "null file");
1879
1880 nd = (dir != NULL)? strlen(dir) : 0;
1881 nf = strlen(file);
1882 ESL_ALLOC(path, sizeof(char) * (nd+nf+2));
1883
1884 if (dir == NULL) /* 1. silly caller didn't give a path */
1885 strcpy(path, file);
1886 else if (*file == eslDIRSLASH) /* 2. <file> is already a path? */
1887 strcpy(path, file);
1888 else if (dir[nd-1] == eslDIRSLASH) /* 3. <dir><file> (dir is / terminated) */
1889 snprintf(path, nd+nf+2, "%s%s", dir, file);
1890 else /* 4. <dir>/<file> (usual case) */
1891 snprintf(path, nd+nf+2, "%s%c%s", dir, eslDIRSLASH, file);
1892
1893 *ret_path = path;
1894 return eslOK;
1895
1896 ERROR:
1897 if (path != NULL) free(path);
1898 if (ret_path != NULL) *ret_path = NULL;
1899 return status;
1900 }
1901
1902
1903 /* Function: esl_FileNewSuffix()
1904 *
1905 * Purpose: Add a file suffix <sfx> to <filename>; or if <filename>
1906 * already has a suffix, replace it with <sfx>. A suffix is
1907 * usually 2-4 letters following a '.' character. Returns
1908 * an allocated string containing the result in <ret_newpath>.
1909 *
1910 * For example, if <filename> is "foo" and <sfx> is "ssi",
1911 * returns "foo.ssi". If <filename> is "foo.db" and <sfx>
1912 * is "idx", returns "foo.idx". You can remove a suffix
1913 * too; if <filename> is "foo.db", and <sfx> is "", the
1914 * result is "foo".
1915 *
1916 * Caller can either ask for <*ret_newpath> to be a new
1917 * allocation by passing <*ret_newpath = NULL>, or can
1918 * provide a ptr to a preallocated space.
1919 *
1920 * Returns: <eslOK> on success, and <ret_newpath> is set
1921 * string "<base_filename>.<sfx>". Caller is
1922 * responsible for free'ing this string, whether it
1923 * provided it as preallocated space or asked for a new
1924 * allocation.
1925 *
1926 * Throws: <eslEMEM> on allocation failure.
1927 *
1928 * Xref: squid's FileAddSuffix().
1929 */
1930 int
1931 esl_FileNewSuffix(const char *filename, const char *sfx, char **ret_newpath)
1932 {
1933 char *new = *ret_newpath; // caller either provides memory, or asks for allocation w/ <NULL>
1934 char *lastdot;
1935 int nf;
1936 int status;
1937
1938 lastdot = strrchr(filename, '.'); /* check for suffix to replace */
1939 if (lastdot != NULL &&
1940 strchr(lastdot, eslDIRSLASH) != NULL)
1941 lastdot = NULL; /*foo.1/filename case - don't be fooled.*/
1942 nf = (lastdot == NULL)? strlen(filename) : lastdot-filename;
1943
1944 if (! new) ESL_ALLOC(new, sizeof(char) * (nf+strlen(sfx)+2)); /* '.' too */
1945 strncpy(new, filename, nf);
1946 *(new+nf) = '.';
1947 strcpy(new+nf+1, sfx);
1948
1949 *ret_newpath = new;
1950 return eslOK;
1951
1952 ERROR:
1953 if (!(*ret_newpath) && new) free(new);
1954 return status;
1955 }
1956
1957
1958
1959 /* Function: esl_FileEnvOpen()
1960 *
1961 * Purpose: Looks for a file <fname> in a colon-separated list of
1962 * directories that is configured in an environment variable
1963 * <env>. The first occurrence of file <fname> in this directory
1964 * list is opened read-only. The open file ptr is returned
1965 * through <opt_fp>, and the full path name to the file
1966 * that was opened is returned through <opt_path>.
1967 * Caller can pass NULL in place of <opt_fp> or <opt_path>
1968 * if it is not interested in one or both of these.
1969 *
1970 * Does not look in the current directory unless "." is
1971 * explicitly in the directory list provided by <env>.
1972 *
1973 * Note: One reason to pass <opt_path> back to the caller is that
1974 * sometimes we're opening the first in a group of files
1975 * (for example, a database and its SSI index), and we want
1976 * to make sure that after we find the main file, the
1977 * caller can look for the auxiliary file(s) in exactly the
1978 * same directory.
1979 *
1980 * Examples: % setenv BLASTDB /nfs/databases/blast-db:/nfs/databases/nr/
1981 *
1982 * FILE *fp;
1983 * char *path;
1984 * int status;
1985 * status = esl_FileEnvOpen("swiss42", "BLASTDB", &fp, &path);
1986 *
1987 * Returns: <eslOK> on success, and provides <opt_fp> and <opt_path>;
1988 * <opt_fp> is opened here, and must be <fclose()>'d by caller;
1989 * <opt_path> is allocated here, and must be <free()>'d by caller.
1990 *
1991 * Returns <eslENOTFOUND> if the file not found in any directory,
1992 * or if <env> does not contain any directories to look in.
1993 *
1994 * Throws: <eslEMEM> on allocation error.
1995 *
1996 * Xref: squid's EnvFileOpen().
1997 */
1998 int
1999 esl_FileEnvOpen(const char *fname, const char *env, FILE **opt_fp, char **opt_path)
2000 {
2001 FILE *fp;
2002 char *dirlist; /* :-separated list of directories */
2003 char *s, *s2; /* ptrs into elems in env list */
2004 char *path = NULL;
2005 int np;
2006 int status;
2007
2008 fp = NULL;
2009 if (opt_fp != NULL) *opt_fp = NULL;
2010 if (opt_path != NULL) *opt_path = NULL;
2011
2012 if (env == NULL) return eslENOTFOUND;
2013 if ((s = getenv(env)) == NULL) return eslENOTFOUND;
2014 if (esl_strdup(s, -1, &dirlist) != eslOK) return eslEMEM;
2015
2016 np = strlen(fname) + strlen(s) + 2; /* upper bound on full path len */
2017 ESL_ALLOC(path, sizeof(char) * np);
2018
2019 s = dirlist;
2020 while (s != NULL)
2021 {
2022 if ((s2 = strchr(s, ':')) != NULL) { *s2 = '\0'; s2++;} /* ~=strtok() */
2023 snprintf(path, np, "%s%c%s", s, eslDIRSLASH, fname); /* // won't hurt */
2024 if ((fp = fopen(path, "r")) != NULL) break;
2025 s = s2;
2026 }
2027 if (fp == NULL) { free(path); free(dirlist); return eslENOTFOUND; }
2028
2029 if (opt_path != NULL) { *opt_path = path; } else free(path);
2030 if (opt_fp != NULL) { *opt_fp = fp; } else fclose(fp);
2031 free(dirlist);
2032 return eslOK;
2033
2034 ERROR:
2035 if (path != NULL) free(path);
2036 if (fp != NULL) fclose(fp);
2037 if (dirlist != NULL) free(dirlist);
2038 if (opt_path != NULL) *opt_path = NULL;
2039 if (opt_fp != NULL) *opt_fp = NULL;
2040 return status;
2041 }
2042
2043 /* Function: esl_tmpfile()
2044 *
2045 * Purpose: Open a secure temporary <FILE *> handle and return it in
2046 * <ret_fp>. The file is opened in read-write mode (<w+b>)
2047 * with permissions 0600, as an atomic operation using the
2048 * POSIX <mkstemp()> function.
2049 *
2050 * The <basename6X> argument is a modifiable string that must
2051 * end in "XXXXXX" (for example, "esltmpXXXXXX"). The
2052 * <basename6X> is used to construct a unique tmpfile name.
2053 *
2054 * Note that this string must be modifiable; do not declare
2055 * it <char *tmpfile = "esltmpXXXXXX";> nor <char tmpfile[]
2056 * = "esltmpXXXXXX";> because these will not work on some
2057 * compilers. Something like <char tmpfile[16] =
2058 * "esltmpXXXXXX";> that explicitly allocates storage will
2059 * suffice.
2060 *
2061 * The file is opened in a standard temporary file
2062 * directory. The path is obtained from the environment
2063 * variable <TMPDIR>; failing that, from the environment
2064 * variable <TMP>; and failing that, </tmp> is used. If the
2065 * process is running <setuid> or <setgid>, then the
2066 * environment variables are ignored, and the temp file is
2067 * always created in </tmp>.
2068 *
2069 * The created tmpfile is not persistent and is not visible
2070 * to a directory listing. The caller may <rewind()> the
2071 * <ret_fp> and do cycles of reading and/or writing, but
2072 * once the <ret_fp> is closed, the file disappears. The
2073 * caller does not need to <remove()> or <unlink()> it (and
2074 * in fact, cannot do so, because it does not know the
2075 * tmpfile's name).
2076 *
2077 * This function is a secure replacement for ANSI C
2078 * <tmpfile()>, which is said to be insecurely implemented on
2079 * some platforms.
2080 *
2081 * Returns: <eslOK> on success, and now <ret_fp> points to a new <FILE *>
2082 * stream for the opened tempfile.
2083 *
2084 * Throws: <eslESYS> if a system call (including the <mkstemp()> call)
2085 * fails, and and <ret_fp> is returned NULL. One possible
2086 * problem is if the temporary directory doesn't exist or
2087 * is not writable. This is considered to be a system
2088 * error, not a user error, so Easel handles it as an exception.
2089 *
2090 * Xref: STL11/85. Substantially copied from David Wheeler,
2091 * "Secure Programming for Linux and Unix HOWTO",
2092 * http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/introduction.html.
2093 * Copyright (C) 1999-2001 David A. Wheeler.
2094 * Licensed under the MIT license; see Appendix C of the HOWTO.
2095 * Thanks, David, for the clearest explanation of the issues
2096 * that I've seen.
2097 *
2098 * I also referred to H. Chen, D. Dean, and D. Wagner,
2099 * "Model checking one million lines of C code",
2100 * In: Network and Distributed System Security Symposium, pp 171-185,
2101 * San Diego, CA, February 2004;
2102 * http://www.cs.ucdavis.edu/~hchen/paper/ndss04.pdf.
2103 * Wheeler's implementation obeys Chen et al's "Property 5",
2104 * governing secure use of tempfiles.
2105 */
2106 int
2107 esl_tmpfile(char *basename6X, FILE **ret_fp)
2108 {
2109 char *tmpdir = NULL;
2110 char *path = NULL;
2111 FILE *fp = NULL;
2112 int fd;
2113 int status;
2114 mode_t old_mode;
2115
2116 /* Determine what tmp directory to use, and construct the
2117 * file name.
2118 */
2119 if (getuid() == geteuid() && getgid() == getegid())
2120 {
2121 tmpdir = getenv("TMPDIR");
2122 if (tmpdir == NULL) tmpdir = getenv("TMP");
2123 }
2124 if (tmpdir == NULL) tmpdir = "/tmp";
2125 if ((status = esl_FileConcat(tmpdir, basename6X, &path)) != eslOK) goto ERROR;
2126
2127 old_mode = umask(077);
2128 if ((fd = mkstemp(path)) < 0) ESL_XEXCEPTION(eslESYS, "mkstemp() failed.");
2129 umask(old_mode);
2130 if ((fp = fdopen(fd, "w+b")) == NULL) ESL_XEXCEPTION(eslESYS, "fdopen() failed.");
2131 if (unlink(path) < 0) ESL_XEXCEPTION(eslESYS, "unlink() failed.");
2132
2133 *ret_fp = fp;
2134 free(path);
2135 return eslOK;
2136
2137 ERROR:
2138 if (path != NULL) free(path);
2139 if (fp != NULL) fclose(fp);
2140 *ret_fp = NULL;
2141 return status;
2142 }
2143
2144 /* Function: esl_tmpfile_named()
2145 *
2146 * Purpose: Open a persistent temporary file relative to the current
2147 * working directory. The file name is constructed from the
2148 * <basename6X> argument, which must be a modifiable string
2149 * ending in the six characters "XXXXXX". These are
2150 * replaced by a unique character string by a call to POSIX
2151 * <mkstemp()>. For example, <basename6X> might be
2152 * <esltmpXXXXXX> on input, and <esltmp12ab34> on return; or, to
2153 * put the tmp file in a subdirectory under the current
2154 * working directory, something like <my_subdir/esltmpXXXXXX>
2155 * on input resulting in something like
2156 * <my_subdir/esltmp12ab34> on return. The tmpfile is opened
2157 * for reading and writing (in mode <w+b> with permissions
2158 * 0600) and the opened <FILE *> handle is returned through
2159 * <ret_fp>.
2160 *
2161 * The created tmpfile is persistent: it will be visible in
2162 * a directory listing, and will remain after program
2163 * termination unless the caller explicitly removes it by a
2164 * <remove()> or <unlink()> call.
2165 *
2166 * To use this function securely, if you reopen the
2167 * tmpfile, you must only reopen it for reading, not
2168 * writing, and you must not trust the contents.
2169 *
2170 * Because the <basename6X> will be modified, it cannot be
2171 * a string constant (especially on a picky compiler like
2172 * gcc). You have to declare it with something like
2173 * <char tmpfile[32] = "esltmpXXXXXX";>
2174 * not
2175 * <char *tmpfile = "esltmpXXXXXX";>
2176 * because a compiler is allowed to make the <*tmpfile> version
2177 * a constant.
2178 *
2179 * Returns: <eslOK> on success, <basename6X> contains the name of the
2180 * tmpfile, and <ret_fp> contains a new <FILE *> stream for the
2181 * opened file.
2182 *
2183 * <eslFAIL> on failure, and <ret_fp> is returned NULL and
2184 * the contents of <basename6X> are undefined. The most
2185 * common reason for a failure will be that the caller does
2186 * not have write permission for the directory that
2187 * <basename6X> is in. Easel handles this as a normal (user)
2188 * failure, not an exception, because these permissions are
2189 * most likely in the user's control (in contrast to
2190 * <esl_tmpfile()>, which always uses a system <TMPDIR>
2191 * that should always be user-writable on a properly
2192 * configured POSIX system).
2193 *
2194 * Xref: STL11/85.
2195 */
2196 int
2197 esl_tmpfile_named(char *basename6X, FILE **ret_fp)
2198 {
2199 FILE *fp;
2200 mode_t old_mode;
2201 int fd;
2202
2203 *ret_fp = NULL;
2204 old_mode = umask(077);
2205 if ((fd = mkstemp(basename6X)) < 0) return eslFAIL;
2206 umask(old_mode);
2207 if ((fp = fdopen(fd, "w+b")) == NULL) return eslFAIL;
2208
2209 *ret_fp = fp;
2210 return eslOK;
2211 }
2212
2213
2214 /* Function: esl_getcwd()
2215 * Synopsis: Gets the path for the current working directory.
2216 *
2217 * Purpose: Returns the path for the current working directory
2218 * in <*ret_cwd>, as reported by POSIX <getcwd()>.
2219 * <*ret_cmd> is allocated here and must be freed by
2220 * the caller.
2221 *
2222 * Returns: <eslOK> on success, and <*ret_cwd> points to
2223 * the pathname of the current working directory.
2224 *
2225 * If <getcwd()> is unavailable on this system,
2226 * returns <eslEUNIMPLEMENTED> and <*ret_cwd> is <NULL>.
2227 *
2228 * If the pathname length exceeds a set limit (16384 char),
2229 * returns <eslERANGE> and <*ret_cwd> is <NULL>.
2230 *
2231 * Throws: <eslEMEM> on allocation failure; <*ret_cwd> is <NULL>.
2232 * <eslESYS> on getcwd() failure; <*ret_cwd> is <NULL>.
2233 *
2234 * Xref: J7/54.
2235 */
2236 int
2237 esl_getcwd(char **ret_cwd)
2238 {
2239 char *cwd = NULL;
2240 int status = eslOK;
2241 #ifdef _POSIX_VERSION
2242 int nalloc = 256;
2243 int maxalloc = 16384;
2244 do {
2245 ESL_ALLOC(cwd, sizeof(char) * nalloc);
2246 if (getcwd(cwd, nalloc) == NULL)
2247 {
2248 if (errno != ERANGE) ESL_XEXCEPTION(eslESYS, "unexpected getcwd() error");
2249 if (nalloc * 2 > maxalloc) { status = eslERANGE; goto ERROR; }
2250 free(cwd);
2251 cwd = NULL;
2252 nalloc *= 2;
2253 }
2254 } while (cwd == NULL);
2255 *ret_cwd = cwd;
2256 return status;
2257
2258 ERROR:
2259 if (cwd) free(cwd);
2260 *ret_cwd = NULL;
2261 return status;
2262
2263 #else
2264 *ret_cwd = NULL;
2265 return eslEUNIMPLEMENTED;
2266 #endif
2267 }
2268 /*----------------- end of file path/name functions ------------------------*/
2269
2270
2271
2272
2273 /*****************************************************************
2274 * 8. Typed comparison routines.
2275 *****************************************************************/
2276
2277 /* Function: esl_{DF}Compare()
2278 * Synopsis: Compare floating point values for approximate equality, better version.
2279 * Incept: SRE, Thu 19 Jul 2018 [Benasque]
2280 *
2281 * Purpose: Return <eslOK> if <x0> and <x> are approximately equal within
2282 * relative tolerance tolerance <r_tol> and absolute
2283 * tolerance <a_tol>; <eslFAIL> if not.
2284 *
2285 * Equality is defined as $|x0-x| < |x0|*r_tol + a_tol$.
2286 *
2287 * <x0> is the reference value: the true value or the
2288 * better estimate. For example, in an iterative
2289 * optimization, if you are comparing a new (better)
2290 * estimate $x_i$ to a previous (worse) estimate $x_{i-1}$,
2291 * <x0> is the new, <x> is the old.
2292 *
2293 * Tolerances <r_tol> and <a_tol> must be $\geq 0$. For a
2294 * strictly relative tolerance test, use <a_tol=0>; for
2295 * strict absolute tolerance, use <r_tol=0>.
2296 *
2297 * "Approximate equality" in floating point math: here be
2298 * dragons. Usually you want to compare floating point
2299 * values by their relative difference <r_tol>. An <r_tol>
2300 * of $1e-5$ essentially means they agree up to their first
2301 * five digits, regardless of absolute magnitude. However,
2302 * relative difference fails for <x0 ~ 0>. Using both
2303 * <r_tol> and <a_tol>, there is a switch at <|x0| = a_tol
2304 * / r_tol>: above this |x0|, <rtol> dominates, and below
2305 * it, <a_tol> does. You typically want <a_tol << r_tol>,
2306 * so the switchover only happens close to zero.
2307 *
2308 * In floating point math, the smallest possible |x0-x| is
2309 * on the order of |x0| times machine epsilon, where
2310 * <DBL_EPSILON> is 2.2e-16 and <FLT_EPSILON> is 1.2e-7, so
2311 * it does not make sense to set <a_tol> smaller than this.
2312 * (If you do, the function will require exact equality.)
2313 *
2314 * Special values follow IEEE754 floating point exact
2315 * comparison rules; <a_tol> and <r_tol> have no
2316 * effect. Any comparison involving <NaN> is
2317 * <eslFAIL>. Equal-signed infinities are <eslOK>:
2318 * <inf==inf>, <-inf==-inf>.
2319
2320 * Note that <eslOK> has value 0, not TRUE, so you don't want to
2321 * write code like <if (esl_DCompare_old()) ...>; you want to
2322 * test explicitly against <eslOK>.
2323 *
2324 * Args: x0 - reference value to compare against (either true, or better estimate)
2325 * x - test value
2326 * r_tol - relative tolerance
2327 * a_tol - absolute tolerance
2328 *
2329 * Returns: <eslOK> if <x0> and <x> are approximately equal.
2330 * <eslFAIL> if not.
2331 *
2332 * Xref: H5/116
2333 */
2334 int
2335 esl_DCompare(double x0, double x, double r_tol, double a_tol)
2336 {
2337 if (isfinite(x0)) { if (fabs(x0 - x) <= r_tol * fabs(x0) + a_tol) return eslOK; }
2338 else { if (x0 == x) return eslOK; } // inf=inf, -inf=-inf; -inf!=inf, NaN!=(inf,-inf,NaN)
2339 return eslFAIL;
2340 }
2341 int
2342 esl_FCompare(float x0, float x, float r_tol, float a_tol)
2343 {
2344 if (isfinite(x0)) { if (fabs(x0 - x) <= r_tol * fabs(x0) + a_tol) return eslOK; }
2345 else { if (x0 == x) return eslOK; }
2346 return eslFAIL;
2347 }
2348
2349 /* Function: esl_CCompare()
2350 * Synopsis: Compare two optional strings for equality.
2351 *
2352 * Purpose: Compare two optional strings <s1> and <s2>
2353 * for equality.
2354 *
2355 * If they're non-<NULL> and identical up to their
2356 * <NUL>-terminator, return <eslOK>.
2357 *
2358 * If they're both <NULL> (unset), return <eslOK>.
2359 *
2360 * Otherwise, they're not identical; return <eslFAIL>.
2361 */
2362 int
2363 esl_CCompare(char *s1, char *s2)
2364 {
2365 if (s1 == NULL && s2 == NULL) return eslOK;
2366 if (s1 == NULL || s2 == NULL) return eslFAIL;
2367 if (strcmp(s1, s2) != 0) return eslFAIL;
2368 return eslOK;
2369 }
2370
2371 /* Function: esl_{DF}Compare_old()
2372 * OBSOLETE. Use esl_{DF}Compare() instead.
2373 *
2374 * Purpose: Compare two floating point scalars <a> and <b> for approximate equality.
2375 * Return <eslOK> if equal, <eslFAIL> if not.
2376 *
2377 * Equality is defined by being within a relative
2378 * epsilon <tol>, as <2*fabs(a-b)/(a+b)> $\leq$ <tol>.
2379 * Additionally, we catch the special cases where <a>
2380 * and/or <b> are 0 or -0. If both are, return <eslOK>; if
2381 * one is, check that the absolute value of the other is
2382 * $\leq$ <tol>.
2383 *
2384 * <esl_DCompare_old()> and <esl_FCompare_old()> work on <double> and <float>
2385 * scalars, respectively.
2386 */
2387 int
2388 esl_DCompare_old(double a, double b, double tol)
2389 {
2390 if (isinf(a) && isinf(b)) return eslOK;
2391 if (isnan(a) && isnan(b)) return eslOK;
2392 if (!isfinite(a) || !isfinite(b)) return eslFAIL;
2393 if (a == b) return eslOK;
2394 if (fabs(a) == 0. && fabs(b) <= tol) return eslOK;
2395 if (fabs(b) == 0. && fabs(a) <= tol) return eslOK;
2396 if (2.*fabs(a-b) / fabs(a+b) <= tol) return eslOK;
2397 return eslFAIL;
2398 }
2399 int
2400 esl_FCompare_old(float a, float b, float tol)
2401 {
2402 if (isinf(a) && isinf(b)) return eslOK;
2403 if (isnan(a) && isnan(b)) return eslOK;
2404 if (!isfinite(a) || !isfinite(b)) return eslFAIL;
2405 if (a == b) return eslOK;
2406 if (fabs(a) == 0. && fabs(b) <= tol) return eslOK;
2407 if (fabs(b) == 0. && fabs(a) <= tol) return eslOK;
2408 if (2.*fabs(a-b) / fabs(a+b) <= tol) return eslOK;
2409 return eslFAIL;
2410 }
2411 /*-------------- end, typed comparison routines --------------------*/
2412
2413
2414
2415 /*****************************************************************
2416 * 9. Other miscellaneous functions
2417 *****************************************************************/
2418
2419 /* Function: esl_mix3()
2420 * Synopsis: Make a quasirandom number by mixing three inputs.
2421 * Incept: SRE, Tue 21 Aug 2018
2422 *
2423 * Purpose: This is Bob Jenkin's <mix()>. Given <a,b,c>,
2424 * generate a number that's generated reasonably
2425 * uniformly on $[0,2^{32}-1]$ even for closely
2426 * spaced choices of $a,b,c$.
2427 *
2428 * We have it in easel.c because it's used both in
2429 * esl_random and esl_rand64, which we want to be
2430 * independent of each other.
2431 */
2432 uint32_t
2433 esl_mix3(uint32_t a, uint32_t b, uint32_t c)
2434 {
2435 a -= b; a -= c; a ^= (c>>13);
2436 b -= c; b -= a; b ^= (a<<8);
2437 c -= a; c -= b; c ^= (b>>13);
2438 a -= b; a -= c; a ^= (c>>12);
2439 b -= c; b -= a; b ^= (a<<16);
2440 c -= a; c -= b; c ^= (b>>5);
2441 a -= b; a -= c; a ^= (c>>3);
2442 b -= c; b -= a; b ^= (a<<10);
2443 c -= a; c -= b; c ^= (b>>15);
2444 return c;
2445 }
2446 /*-------------- end, miscellaneous functions -------------------*/
2447
2448
2449
2450
2451
2452 /*****************************************************************
2453 * 10. Unit tests.
2454 *****************************************************************/
2455 #ifdef eslEASEL_TESTDRIVE
2456
2457 #include "esl_random.h"
2458
2459 static void
2460 utest_resize(ESL_RANDOMNESS *rng)
2461 {
2462 char msg[] = "esl_resize unit test failed";
2463 int ntrials = 100;
2464 int i;
2465 int a,n,r,b;
2466
2467 for (i = 0; i < ntrials; i++)
2468 {
2469 if (esl_rnd_Roll(rng, 2)) { n = esl_rnd_Roll(rng, INT_MAX); a = esl_rnd_Roll(rng, INT_MAX); r = esl_rnd_Roll(rng, INT_MAX); }
2470 else { n = esl_rnd_Roll(rng, 8); a = esl_rnd_Roll(rng, 8); r = esl_rnd_Roll(rng, 8); }
2471
2472 b = esl_resize(n,a,r);
2473
2474 if (r == 0) r = INT_MAX; // that's the calling convention used by esl_resize
2475
2476 if (n > a) // if we need to reallocate to fit n...
2477 {
2478 if (b < n) esl_fatal(msg); // new allocation b is always sufficient to hold n
2479 if (n <= r) { // if requested n is under redline...
2480 if (b > r) esl_fatal(msg); // ... new allocation b cannot exceed redline
2481 if (n < INT_MAX/2 && b > 2*n) esl_fatal(msg); // ... and it won't be more than 2x overallocated
2482 } else {
2483 if (b != n) esl_fatal(msg); // if requested n is over redline, then it is exactly allocated, not overallocated
2484 }
2485 }
2486 else
2487 { // existing allocation a suffices...
2488 if (a > r && n <= r && b != r) esl_fatal(msg); // if r suffices too, and a is over redline r, shrink allocation back to r
2489 if (a > r && n > r && b != n) esl_fatal(msg); // if r doesn't suffice, only shrink back to n
2490 if (a <= r && a == 0 && b != 1) esl_fatal(msg); // even for n=0 a=0, where a zero allocation "suffices", return 1 to avoid zero allocation
2491 if (a <= r && a > 0 && b != a) esl_fatal(msg); // normal case where a suffices and is under redline; don't change allocation.
2492 }
2493 }
2494 }
2495
2496 static void
2497 utest_IsInteger(void)
2498 {
2499 char *goodones[] = { " 99 " };
2500 char *badones[] = { "", " 99 foo " };
2501 int ngood = sizeof(goodones) / sizeof(char *);
2502 int nbad = sizeof(badones) / sizeof(char *);
2503 int i;
2504
2505 for (i = 0; i < ngood; i++)
2506 if (! esl_str_IsInteger(goodones[i])) esl_fatal("esl_str_IsInteger() should have recognized %s", goodones[i]);
2507 for (i = 0; i < nbad; i++)
2508 if ( esl_str_IsInteger(badones[i])) esl_fatal("esl_str_IsInteger() should not have recognized %s", badones[i]);
2509 }
2510
2511 static void
2512 utest_IsReal(void)
2513 {
2514 char *goodones[] = { "99", " \t 99", "-99.00", "+99.00e-12", "+0xabc.defp-12", " +INFINITY", "-nan" };
2515 char *badones[] = { "",
2516 "FIBB_BOVIN/67-212", /* testing for a fixed bug, 17 Dec 2012, reported by ER */
2517 };
2518 int ngood = sizeof(goodones) / sizeof(char *);
2519 int nbad = sizeof(badones) / sizeof(char *);
2520 int i;
2521
2522 for (i = 0; i < ngood; i++)
2523 if (! esl_str_IsReal(goodones[i])) esl_fatal("esl_str_IsReal() should have recognized %s", goodones[i]);
2524 for (i = 0; i < nbad; i++)
2525 if ( esl_str_IsReal(badones[i])) esl_fatal("esl_str_IsReal() should not have recognized %s", badones[i]);
2526 }
2527
2528
2529 static void
2530 utest_strmapcat(void)
2531 {
2532 char *msg = "esl_strmapcat() unit test failed";
2533 ESL_DSQ inmap[128];
2534 char *pfx = "testing testing";
2535 char *append = "one two three";
2536 char *bad = "1 2 three";
2537 char *dest;
2538 int64_t L1;
2539 esl_pos_t L2;
2540 int x;
2541
2542 /* a simple input map, for testing */
2543 for (x = 0; x < 128; x++) inmap[x] = eslDSQ_ILLEGAL;
2544 for (x = 'a'; x < 'z'; x++) inmap[x] = x;
2545 for (x = 'A'; x < 'Z'; x++) inmap[x] = x;
2546 inmap[' '] = eslDSQ_IGNORED;
2547 inmap[0] = '?';
2548
2549 L1 = strlen(pfx);
2550 L2 = strlen(append);
2551 if ( ( esl_strdup (pfx, L1, &dest)) != eslOK) esl_fatal(msg);
2552 if ( ( esl_strmapcat(inmap, &dest, &L1, append, L2)) != eslOK) esl_fatal(msg);
2553 if ( strcmp(dest, "testing testingonetwothree") != 0) esl_fatal(msg);
2554 free(dest);
2555
2556 L1 = -1;
2557 L2 = -1;
2558 if ( ( esl_strdup (pfx, L1, &dest)) != eslOK) esl_fatal(msg);
2559 if ( ( esl_strmapcat(inmap, &dest, &L1, append, L2)) != eslOK) esl_fatal(msg);
2560 if ( strcmp(dest, "testing testingonetwothree") != 0) esl_fatal(msg);
2561 free(dest);
2562
2563 L1 = 0;
2564 dest = NULL;
2565 if ( ( esl_strmapcat(inmap, &dest, &L1, pfx, -1)) != eslOK) esl_fatal(msg);
2566 if ( ( esl_strmapcat(inmap, &dest, &L1, append, -1)) != eslOK) esl_fatal(msg);
2567 if ( strcmp(dest, "testingtestingonetwothree") != 0) esl_fatal(msg);
2568 free(dest);
2569
2570
2571 if ( ( esl_strdup(pfx, -1, &dest)) != eslOK) esl_fatal(msg);
2572 L1 = 8;
2573 if ( ( esl_strmapcat(inmap, &dest, &L1, bad, -1)) != eslEINVAL) esl_fatal(msg);
2574 if ( strcmp(dest, "testing ??three") != 0) esl_fatal(msg);
2575 free(dest);
2576 }
2577
2578
2579 static void
2580 utest_strtok(void)
2581 {
2582 char msg[] = "esl_strtok() unit test failed";
2583 char *teststring;
2584 char *s;
2585 char *tok;
2586 int toklen;
2587 char endc;
2588
2589 if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg);
2590
2591 s = teststring;
2592 if (esl_strtok(&s, " ", &tok) != eslOK) esl_fatal(msg);
2593 if (strcmp(tok, "This") != 0) esl_fatal(msg);
2594 if (*s != 'i') esl_fatal(msg);
2595
2596 if (esl_strtok_adv(&s, " \t", &tok, &toklen, &endc) != eslOK) esl_fatal(msg);
2597 if (strcmp(tok, "is") != 0) esl_fatal(msg);
2598 if (*s != ' ') esl_fatal(msg);
2599 if (toklen != 2) esl_fatal(msg);
2600 if (endc != '\t') esl_fatal(msg);
2601
2602 if (esl_strtok_adv(&s, "\n", &tok, NULL, NULL) != eslOK) esl_fatal(msg);
2603 if (strcmp(tok, " a sentence.") != 0) esl_fatal(msg);
2604 if (*s != '\0') esl_fatal(msg);
2605
2606 free(teststring);
2607 }
2608
2609 static void
2610 utest_sprintf(void)
2611 {
2612 char msg[] = "unit tests for esl_[v]sprintf() failed";
2613 int num = 99;
2614 char *what = "beer";
2615 char *s = NULL;
2616
2617 if (esl_sprintf(&s, "%d bottles of %s", num, what) != eslOK) esl_fatal(msg);
2618 if (strcmp(s, "99 bottles of beer") != 0) esl_fatal(msg);
2619 free(s);
2620
2621 if (esl_sprintf(&s, NULL) != eslOK) esl_fatal(msg);
2622 if (s != NULL) esl_fatal(msg);
2623 }
2624
2625
2626
2627 static void
2628 utest_FileExists(void)
2629 {
2630 char msg[] = "FileExists unit test failed";
2631 char tmpfile[32] = "esltmpXXXXXX";
2632 FILE *fp = NULL;
2633 #ifdef _POSIX_VERSION
2634 struct stat st;
2635 mode_t mode;
2636 #endif
2637
2638 /* create a tmpfile */
2639 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2640 fprintf(fp, "Unit test.\n");
2641 fclose(fp);
2642
2643 if (! esl_FileExists(tmpfile)) esl_fatal(msg);
2644
2645 #ifdef _POSIX_VERSION
2646 /* The FileExists doesn't just test existence; it also checks read permission */
2647 if (stat(tmpfile, &st) != 0) esl_fatal(msg);
2648 mode = st.st_mode & ~S_IRUSR;
2649 if (chmod(tmpfile, mode) != 0) esl_fatal(msg);
2650 if (esl_FileExists(tmpfile)) esl_fatal(msg);
2651 #endif
2652
2653 remove(tmpfile);
2654 if (esl_FileExists(tmpfile)) esl_fatal(msg);
2655 }
2656
2657 static void
2658 utest_tmpfile_named(void)
2659 {
2660 char msg[] = "tmpfile_named unit test failed";
2661 char tmpfile[32] = "esltmpXXXXXX";
2662 FILE *fp = NULL;
2663 char buf[256];
2664
2665 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2666 fprintf(fp, "Unit test.\n");
2667 fclose(fp);
2668 if ((fp = fopen(tmpfile, "r")) == NULL) esl_fatal(msg);
2669 if (fgets(buf, 256, fp) == NULL) esl_fatal(msg);
2670 if (strcmp(buf, "Unit test.\n") != 0) esl_fatal(msg);
2671 fclose(fp);
2672 remove(tmpfile);
2673 }
2674
2675 static void
2676 utest_compares(void)
2677 {
2678 char msg[] = "easel utest_compares failed";
2679
2680 if (esl_DCompare(-eslINFINITY, eslINFINITY, 1e-12, 1e-16) != eslFAIL) esl_fatal(msg); // -inf != inf
2681 if (esl_DCompare(eslINFINITY, eslINFINITY, 1e-12, 1e-16) != eslOK) esl_fatal(msg); // inf = inf, even though rel and abs diff = inf!
2682 if (esl_DCompare(-eslINFINITY,-eslINFINITY, 1e-12, 1e-16) != eslOK) esl_fatal(msg);
2683 if (esl_DCompare(eslNaN, eslNaN, 1e-12, 1e-16) != eslFAIL) esl_fatal(msg); // NaN fails in any comparison
2684 if (esl_DCompare(0., eslNaN, 1e-12, 1e-16) != eslFAIL) esl_fatal(msg);
2685 if (esl_DCompare(eslNaN, 0., 1e-12, 1e-16) != eslFAIL) esl_fatal(msg);
2686 if (esl_DCompare(0., 1e-17, 1e-12, 1e-16) != eslOK) esl_fatal(msg);
2687
2688 /* exact comparisons with zero tolerance: eslOK unless a NaN is involved */
2689 if (esl_DCompare(0., 0.0, 0.0, 0.0) != eslOK) esl_fatal(msg);
2690 if (esl_DCompare(eslINFINITY, eslINFINITY, 0.0, 0.0) != eslOK) esl_fatal(msg);
2691 if (esl_DCompare(-eslINFINITY, -eslINFINITY, 0.0, 0.0) != eslOK) esl_fatal(msg);
2692 if (esl_DCompare(eslNaN, eslNaN, 0.0, 0.0) != eslFAIL) esl_fatal(msg);
2693
2694 /* float versions */
2695 if (esl_FCompare(-eslINFINITY, eslINFINITY, 1e-6, 1e-10) != eslFAIL) esl_fatal(msg);
2696 if (esl_FCompare(eslINFINITY, eslINFINITY, 1e-6, 1e-10) != eslOK) esl_fatal(msg);
2697 if (esl_FCompare(-eslINFINITY,-eslINFINITY, 1e-6, 1e-10) != eslOK) esl_fatal(msg);
2698 if (esl_FCompare(eslNaN, eslNaN, 1e-6, 1e-10) != eslFAIL) esl_fatal(msg);
2699 if (esl_FCompare(0., eslNaN, 1e-6, 1e-10) != eslFAIL) esl_fatal(msg);
2700 if (esl_FCompare(eslNaN, 0., 1e-6, 1e-10) != eslFAIL) esl_fatal(msg);
2701 if (esl_FCompare(0., 1e-11, 1e-6, 1e-10) != eslOK) esl_fatal(msg);
2702
2703 if (esl_FCompare(0., 0.0, 0.0, 0.0) != eslOK) esl_fatal(msg);
2704 if (esl_FCompare(eslINFINITY, eslINFINITY, 0.0, 0.0) != eslOK) esl_fatal(msg);
2705 if (esl_FCompare(-eslINFINITY, -eslINFINITY, 0.0, 0.0) != eslOK) esl_fatal(msg);
2706 if (esl_FCompare(eslNaN, eslNaN, 0.0, 0.0) != eslFAIL) esl_fatal(msg);
2707
2708 // if (esl_DCompare_old(-eslINFINITY, eslINFINITY, 1e-5) != eslFAIL) esl_fatal(msg); /* -inf != inf */
2709 // if (esl_DCompare_old(eslNaN, eslNaN, 1e-5) != eslFAIL) esl_fatal(msg); /* NaN fails in any comparison */
2710 if (esl_DCompare_old(0., eslNaN, 1e-12) != eslFAIL) esl_fatal(msg);
2711 if (esl_DCompare_old(eslNaN, 0., 1e-12) != eslFAIL) esl_fatal(msg);
2712 // if (esl_DCompare_old(eslINFINITY, eslINFINITY, 1e-12) != eslFAIL) esl_fatal(msg);
2713 }
2714
2715
2716
2717 #endif /*eslEASEL_TESTDRIVE*/
2718
2719
2720 /*****************************************************************
2721 * 11. Test driver.
2722 *****************************************************************/
2723
2724 #ifdef eslEASEL_TESTDRIVE
2725
2726 #include "easel.h"
2727 #include "esl_getopts.h"
2728 #include "esl_random.h"
2729
2730 static ESL_OPTIONS options[] = {
2731 /* name type default env range toggles reqs incomp help docgroup*/
2732 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
2733 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
2734 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
2735 };
2736 static char usage[] = "[-options]";
2737 static char banner[] = "test driver for easel module";
2738
2739 int
2740 main(int argc, char **argv)
2741 {
2742 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
2743 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
2744
2745 fprintf(stderr, "## %s\n", argv[0]);
2746 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
2747
2748 #ifdef eslTEST_THROWING
2749 esl_exception_SetHandler(&esl_nonfatal_handler);
2750 #endif
2751
2752 utest_resize(rng);
2753 utest_IsInteger();
2754 utest_IsReal();
2755 utest_strmapcat();
2756 utest_strtok();
2757 utest_sprintf();
2758 utest_FileExists();
2759 utest_tmpfile_named();
2760 utest_compares();
2761
2762 fprintf(stderr, "# status = ok\n");
2763
2764 esl_randomness_Destroy(rng);
2765 esl_getopts_Destroy(go);
2766 return eslOK;
2767 }
2768 #endif /*eslEASEL_TESTDRIVE*/
2769
2770 /*****************************************************************
2771 * 12. Examples.
2772 *****************************************************************/
2773
2774 #ifdef eslEASEL_EXAMPLE
2775 /*::cexcerpt::easel_example_tmpfiles::begin::*/
2776 /* gcc -g -Wall -o example -I. -L. -DeslEASEL_EXAMPLE_TMPFILES easel.c -leasel -lm
2777 * ./example
2778 */
2779 #include "easel.h"
2780
2781 int main(void)
2782 {
2783 char tmpfile1[32] = "esltmpXXXXXX"; /* a transient, secure tmpfile: 6 X's are important */
2784 char tmpfile2[32] = "esltmpXXXXXX"; /* a named tmpfile */
2785 FILE *fp = NULL;
2786 char buf[256];
2787
2788 /* Example of using a secure, unnamed tmpfile.
2789 * Note, the new tmpfile is automatically deleted, so to cleanup, just fclose() the FILE */
2790 esl_tmpfile(tmpfile1, &fp);
2791 fprintf(fp, "Hello world!\n");
2792 rewind(fp);
2793 if (fgets(buf, 256, fp) == NULL) esl_fatal("bad fread()");
2794 printf("first temp file says: %s\n", buf);
2795 fclose(fp);
2796
2797 /* Example of reasonably securely using a named tmpfile.
2798 * To cleanup, must both fclose() the FILE and remove() the file by name */
2799 esl_tmpfile_named(tmpfile2, &fp);
2800 fprintf(fp, "Hello insecure world!\n");
2801 fclose(fp); /* tmpfile2 now exists on disk and can be closed/reopened */
2802
2803 fp = fopen(tmpfile2, "r");
2804 if (fgets(buf, 256, fp) == NULL) esl_fatal("bad fread()");
2805 printf("second temp file says: %s\n", buf);
2806 fclose(fp);
2807 remove(tmpfile2); /* disk file cleanup necessary with this version. */
2808
2809 return eslOK;
2810 }
2811 /*::cexcerpt::easel_example_tmpfiles::end::*/
2812 #endif /*eslEASEL_EXAMPLE*/
2813
2814