Debian Codegraph @

hmmer/easel/esl_buffer.c

raw symbols SCIP
1 /*::cexcerpt::header_example::begin::*/
2 /* An input parsing abstraction.
3 *
4 * Table of contents:
5 * 1. ESL_BUFFER object: opening/closing.
6 * 2. Positioning and anchoring an ESL_BUFFER.
7 * 3. Raw access to the buffer.
8 * 4. Line-based parsing.
9 * 5. Token-based parsing.
10 * 6. Binary (fread-like) parsing.
11 * 7. Private (static) functions.
12 * 8. Benchmark.
13 * 9. Unit tests.
14 * 10. Test driver.
15 * 11. Examples.
16 */
17 /*::cexcerpt::header_example::end::*/
18
19 /*::cexcerpt::include_example::begin::*/
20 #include <esl_config.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <signal.h> // one of the utests uses alarm() to catch an infinite loop bug
26
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #ifdef _POSIX_VERSION
31 #include <fcntl.h>
32 #include <sys/mman.h>
33 #include <sys/stat.h>
34 #endif /* _POSIX_VERSION */
35
36 #include "easel.h"
37 #include "esl_mem.h"
38
39 #include "esl_buffer.h"
40 /*::cexcerpt::include_example::end::*/
41
42
43
44 /*::cexcerpt::statics_example::begin::*/
45 static int buffer_create (ESL_BUFFER **ret_bf);
46 static int buffer_init_file_mmap (ESL_BUFFER *bf, esl_pos_t filesize);
47 static int buffer_init_file_slurped(ESL_BUFFER *bf, esl_pos_t filesize);
48 static int buffer_init_file_basic (ESL_BUFFER *bf);
49
50 static int buffer_refill (ESL_BUFFER *bf, esl_pos_t nmin);
51 static int buffer_countline(ESL_BUFFER *bf, esl_pos_t *opt_nc, esl_pos_t *opt_nskip);
52 static int buffer_skipsep (ESL_BUFFER *bf, const char *sep);
53 static int buffer_newline (ESL_BUFFER *bf);
54 static int buffer_counttok (ESL_BUFFER *bf, const char *sep, esl_pos_t *ret_nc);
55 /*::cexcerpt::statics_example::end::*/
56
57
58
59 /*****************************************************************
60 *# 1. ESL_BUFFER object: opening/closing.
61 *****************************************************************/
62
63 /* Function: esl_buffer_Open()
64 * Synopsis: Standard Easel idiom for opening a stream by filename.
65 *
66 * Purpose: Open <filename> for parsing. Return an open
67 * <ESL_BUFFER> for it.
68 *
69 * The standard Easel idiom allows reading from standard
70 * input (pass <filename> as '-'), allows reading gzip'ed
71 * files automatically (any <filename> ending in <.gz> is
72 * opened as a pipe from <gzip -dc>), and allows using an
73 * environment variable to specify a colon-delimited list
74 * of directories in which <filename> may be found. Normal
75 * files are memory mapped (if <mmap()> is available) when
76 * they are large, and slurped into memory if they are
77 * small.
78 *
79 * If <filename> is '-' (a single dash character),
80 * capture the standard input stream rather than
81 * opening a file; return <eslOK>.
82 *
83 * Else, try to find <filename> in a directory <d>,
84 * starting with the current working directory. If
85 * <./filename> is found (note that <filename> may include
86 * a relative path), directory <d> is <.>. Else, if
87 * <envvar> is non-<NULL>, check the environment variable
88 * <envvar> for a colon-delimited list of directories, and
89 * for each directory <d> in that list, try to find
90 * <d/filename>. Use the first <d> that succeeds. If
91 * none succeed, return <eslENOTFOUND>.
92 *
93 * Now open the file. If <filename> ends in <.gz>, 'open'
94 * it by running <gzip -dc d/filename 2>/dev/null>,
95 * capturing the standard output from gunzip decompression
96 * in the <ESL_BUFFER>. Otherwise, open <d/filename> as a
97 * normal file. If its size is not more than
98 * <eslBUFFER_SLURPSIZE> (default 4 MB), it is slurped into
99 * memory; else, if <mmap()> is available, it is memory
100 * mapped; else, it is opened as a read-only binary stream
101 * with <fopen()> in mode <"rb">.
102 *
103 * Args: filename - file to open for reading; or '-' for STDIN
104 * envvar - name of an environment variable in which to
105 * find a colon-delimited list of directories;
106 * or <NULL> if none.
107 * ret_bf - RETURN: new ESL_BUFFER
108 *
109 * Returns: <eslOK> on success; <*ret_bf> is the new <ESL_BUFFER>.
110 *
111 * <eslENOTFOUND> if file isn't found or isn't readable.
112 * <eslFAIL> if gzip -dc fails on a .gz file, probably
113 * because a gzip executable isn't found in PATH.
114 *
115 * On any normal error, <*ret_bf> is still returned,
116 * in an unset state, with a user-directed error message
117 * in <*ret_bf->errmsg>.
118 *
119 * Throws: <eslESYS> on system call failures (such as fread()).
120 * <eslEMEM> on allocation failure.
121 * Now <*ret_bf> is <NULL>.
122 */
123 int
124 esl_buffer_Open(const char *filename, const char *envvar, ESL_BUFFER **ret_bf)
125 {
126 char *path = NULL;
127 int n;
128 int status;
129
130 /* "-" => stdin */
131 if (strcmp(filename, "-") == 0)
132 return esl_buffer_OpenStream(stdin, ret_bf);
133
134 /* else, a file. find its fully qualified path */
135 if (esl_FileExists(filename)) /* look in current working directory */
136 { if ( (status = esl_strdup(filename, -1, &path)) != eslOK) { *ret_bf = NULL; goto ERROR; } }
137 else { /* then search directory list in envvar, if any */
138 status = esl_FileEnvOpen(filename, envvar, NULL, &path);
139 if (status == eslENOTFOUND) { esl_buffer_OpenFile(filename, ret_bf); goto ERROR; }
140 else if (status != eslOK) { *ret_bf = NULL; goto ERROR; }
141 /* yeah, the esl_buffer_OpenFile() looks weird - we know the file's not there! -
142 * but it's a clean way to set our error return status properly,
143 * recording the correct error message in a live ESL_BUFFER's bf->errmsg.
144 * note that esl_FileEnvOpen() correctly handles envvar==NULL,
145 * returning eslENOTFOUND.
146 */
147 }
148
149 n = strlen(path);
150 if (n > 3 && strcmp(filename+n-3, ".gz") == 0) /* if .gz => gzip -dc */
151 { if ( (status = esl_buffer_OpenPipe(path, "gzip -dc %s 2>/dev/null", ret_bf)) != eslOK) goto ERROR; }
152 else
153 { if ( (status = esl_buffer_OpenFile(path, ret_bf)) != eslOK) goto ERROR; }
154
155 free(path);
156 return eslOK;
157
158 ERROR:
159 if (path) free(path);
160 return status;
161 }
162
163 /* Function: esl_buffer_OpenFile()
164 * Synopsis: Open a file.
165 *
166 * Purpose: Open <filename> for reading. Return an open <ESL_BUFFER> in
167 * <*ret_bf>.
168 *
169 * <filename> may be a relative path such as <subdir/foo>
170 * or a full path such as </my/dir/foo>.
171 *
172 * On a POSIX-compliant system, large files are memory
173 * mapped, and small files are just slurped into memory.
174 *
175 * On non-POSIX systems, the file is opened as a stream.
176 * On a short initial read (if the file size is smaller than
177 * the buffer page size), the file is considered to be
178 * completely slurped.
179 *
180 * Args: filename - name of (or path to) file to open
181 * *ret_bf - RETURN: new ESL_BUFFER
182 *
183 * Returns: <eslOK> on success; <*ret_bf> is new <ESL_BUFFER>.
184 *
185 * <eslENOTFOUND> if <filename> isn't found or isn't readable.
186 *
187 * On normal errors, a new <*ret_bf> is still returned, in
188 * an unset state, with a user-directed error message in
189 * <*ret_bf->errmsg>.
190 *
191 * Throws: <eslEMEM> on allocation failure.
192 */
193 int
194 esl_buffer_OpenFile(const char *filename, ESL_BUFFER **ret_bf)
195 {
196 ESL_BUFFER *bf = NULL;
197 #ifdef _POSIX_VERSION
198 struct stat fileinfo;
199 #endif
200 esl_pos_t filesize = -1;
201 int status;
202
203 if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
204
205 if ((bf->fp = fopen(filename, "rb")) == NULL)
206 ESL_XFAIL(eslENOTFOUND, bf->errmsg, "couldn't open %s for reading", filename);
207
208 if ((status = esl_strdup(filename, -1, &(bf->filename))) != eslOK) goto ERROR;
209
210 /* Try to use POSIX fstat() to get file size and optimal read size.
211 * Use filesize to decide whether to slurp, mmap, or read normally.
212 * If we don't have fstat(), we'll just read normally, and pagesize
213 * will be the Easel default 4096 (set in buffer_create().)
214 */
215 #ifdef _POSIX_VERSION
216 if (fstat(fileno(bf->fp), &fileinfo) == -1) ESL_XEXCEPTION(eslESYS, "fstat() failed");
217 filesize = fileinfo.st_size;
218 bf->pagesize = fileinfo.st_blksize;
219 if (bf->pagesize < 512) bf->pagesize = 512; /* I feel paranoid about st_blksize range not being guaranteed to be sensible */
220 if (bf->pagesize > 4194304) bf->pagesize = 4194304;
221 #endif
222
223 if (filesize != -1 && filesize <= eslBUFFER_SLURPSIZE)
224 { if ((status = buffer_init_file_slurped(bf, filesize)) != eslOK) goto ERROR; }
225 #ifdef _POSIX_VERSION
226 else if (filesize > eslBUFFER_SLURPSIZE)
227 { if ((status = buffer_init_file_mmap(bf, filesize)) != eslOK) goto ERROR; }
228 #endif
229 else
230 { if ((status = buffer_init_file_basic(bf)) != eslOK) goto ERROR; }
231
232 *ret_bf = bf;
233 return status;
234
235 ERROR:
236 if (status != eslENOTFOUND) { esl_buffer_Close(bf); bf = NULL; }
237 if (bf) {
238 if (bf->fp) { fclose(bf->fp); bf->fp = NULL; }
239 if (bf->filename) { free(bf->filename); bf->filename = NULL; }
240 bf->pagesize = eslBUFFER_PAGESIZE;
241 }
242 *ret_bf = bf;
243 return status;
244 }
245
246
247 /* Function: esl_buffer_OpenPipe()
248 * Synopsis: Open a file through a command's stdout pipe (e.g. gunzip).
249 *
250 * Purpose: Run the command <cmdfmt> on <filename> and capture its <stdout>
251 * stream for parsing. Return the open <ESL_BUFFER> in
252 * <*ret_bf>.
253 *
254 * <cmdfmt> has a restricted format; it is a <printf()>-style
255 * format string with a single <%s>, where <filename> is to
256 * be substituted. An example <cmdfmt> is "gzip -dc %s
257 * 2>/dev/null".
258 *
259 * <filename> is checked for existence and read permission
260 * before a command line is constructed.
261
262 * <filename> may be <NULL>. In this case, <cmdfmt> is
263 * assumed to be be the complete command, and (obviously)
264 * the diagnostic check for <filename>
265 * existence/readability is skipped. This gives you some
266 * ability to skip the restricted single-argument format of
267 * <cmdfmt>. If you need to do something fancier with a
268 * pipe, you can always open and manage it yourself and use
269 * <esl_buffer_OpenStream()>.
270 *
271 * <popen()> executes the command under </bin/sh>.
272 *
273 * The <stderr> stream of the command should almost
274 * certainly be redirected (else it will appear on output
275 * of your program). In general it should be discarded
276 * to </dev/null>. One of the only signs of a command
277 * failure is that the command produces a "short read", of
278 * less than <bf->pagesize> (and often 0, on a complete
279 * failure, if <stderr> has been discarded). If <stderr>
280 * is longer than the buffer's <pagesize>, we may not
281 * accurately detect error conditions. If you must capture
282 * <stderr> (for example with a <cmdfmt> like
283 * "gzip -dc %s 2>&1") be aware that the parser may
284 * see that output as "successful" execution, if it's long
285 * enough.
286 *
287 * The reason to pass <cmdfmt> and <filename> separately is
288 * to enable better error diagnostics. <popen()> itself
289 * tends to "succeed" whether the command or the file exist
290 * or not. By having <filename>, we can check for its
291 * existence/readability first.
292 *
293 * The reason that error checking <popen()> isn't entirely
294 * straightforward is that we don't see the exit status of
295 * the command until we <pclose()>. We can only <pclose()>
296 * when we're done loading data from the file, and that
297 * only happens here on a short initial read. If we do get
298 * a short read, we <pclose()>, get and check the command's
299 * exit status, and return the <ESL_BUFFER> in an
300 * <eslBUFFER_ALLFILE> state with <bf->cmdline> set.
301 *
302 * Args: filename - file name (or path) to plug into <cmdfmt>; or NULL
303 * if <cmdfmt> is complete command already
304 * cmdfmt - command to execute (with /bin/sh) and capture
305 * stdout from.
306 * *ret_bf - RETURN: new ESL_BUFFER
307 *
308 * Returns: <eslOK> on success, and <*ret_bf> is the new <ESL_BUFFER>.
309 *
310 * <eslENOTFOUND> if <filename> isn't found or isn't readable.
311 *
312 * <eslFAIL> if the constructed command fails - which
313 * usually means that the program isn't found or isn't
314 * executable, or that the command returned nonzero
315 * (quickly, i.e. with zero or little output and a 'short
316 * read').
317 *
318 * On any normal error, the <*ret_bf> is returned (in an
319 * <eslBUFFER_UNSET> state) and <bf->errmsg> contains a
320 * user-directed error message.
321 *
322 * Throws: <eslESYS> on <*sprintf()> or <fread()> failure.
323 * <eslEMEM> on allocation failure.
324 *
325 * On any exception, <*ret_bf> is NULL.
326 */
327 int
328 esl_buffer_OpenPipe(const char *filename, const char *cmdfmt, ESL_BUFFER **ret_bf)
329 {
330 ESL_BUFFER *bf = NULL;
331 char *cmd = NULL;
332 int status;
333
334 if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
335
336 if (filename && ! esl_FileExists(filename))
337 ESL_XFAIL(eslENOTFOUND, bf->errmsg, "couldn't read file %s", filename);
338
339 if (filename) { if ((status = esl_sprintf(&cmd, cmdfmt, filename)) != eslOK) goto ERROR; }
340 else { if ((status = esl_strdup(cmdfmt, -1, &cmd)) != eslOK) goto ERROR; }
341
342 if ((bf->fp = popen(cmd, "r")) == NULL)
343 ESL_XFAIL(eslENOTFOUND, bf->errmsg, "couldn't popen() the command: %s\n", cmd);
344
345 if ( (status = esl_strdup(cmd, -1, &(bf->cmdline))) != eslOK) goto ERROR;
346 if (filename && (status = esl_strdup(filename, -1, &(bf->filename))) != eslOK) goto ERROR;
347
348 ESL_ALLOC(bf->mem, sizeof(char) * bf->pagesize);
349 bf->balloc = bf->pagesize;
350
351 bf->n = fread(bf->mem, sizeof(char), bf->pagesize, bf->fp);
352 /* Now check for various errors on a short read. A short read can mean:
353 * - a small file; success, and we have the whole file in one page
354 * - popen() "succeeded" but the command failed
355 * - an fread() failure
356 * Sort it out. The trick here is that we don't get the exit status
357 * of <cmd> until we pclose(). So (assuming it isn't fread() itself
358 * that failed) we take advantage of the fact that we can set the
359 * ESL_BUFFER to a eslBUFFER_ALLFILE state on a short initial read;
360 * pclose() and check command exit status.
361 * This pretty much relies on what <stderr> from <cmd> looks like;
362 * it needs to either be redirected, or short enough to be a short read.
363 */
364 if (bf->n < bf->pagesize)
365 {
366 /* Delayed exception throwing. If popen() failed, ferror() may be set too; evaluate what happened to popen() first. */
367 status = (ferror(bf->fp) ? eslESYS : eslOK);
368 if (pclose(bf->fp) != 0) {
369 bf->fp = NULL; /* error block is going to try to pclose() too */
370 ESL_XFAIL(eslFAIL, bf->errmsg, "pipe command '%s' did not succeed", cmd);
371 }
372 /* now deal with an fread() error. */
373 if (status != eslOK) ESL_XEXCEPTION(eslESYS, "fread() failed");
374 bf->fp = NULL;
375 bf->balloc = 0;
376 bf->mode_is = eslBUFFER_ALLFILE;
377 }
378 else
379 bf->mode_is = eslBUFFER_CMDPIPE;
380
381 free(cmd);
382 *ret_bf = bf;
383 return eslOK;
384
385 ERROR:
386 if (status != eslENOTFOUND && status != eslFAIL) { esl_buffer_Close(bf); bf = NULL; }
387 if (bf) { /* restore state to UNSET; w/ error message in errmsg */
388 if (bf->mem) { free(bf->mem); bf->mem = NULL; }
389 if (bf->fp) { pclose(bf->fp); bf->fp = NULL; }
390 if (bf->filename) { free(bf->filename); bf->filename = NULL; }
391 if (bf->cmdline) { free(bf->cmdline); bf->cmdline = NULL; }
392 bf->n = 0;
393 bf->balloc = 0;
394 }
395 if (cmd) free(cmd);
396 *ret_bf = bf;
397 return status;
398
399 }
400
401 /* Function: esl_buffer_OpenMem()
402 * Synopsis: "Open" an existing string for parsing.
403 *
404 * Purpose: Given a buffer or string <p> of length <n>, turn it into
405 * an <ESL_BUFFER>. Return the new buffer in <*ret_bf>.
406 *
407 * The memory for <p> is still managed by the caller.
408 * Caller should free it, if necessary, only after the
409 * <ESL_BUFFER> has been closed.
410 *
411 * As a special case, if <n> is -1, <p> is assumed to be a
412 * \verb+\0+-terminated string and its length is calculated with
413 * <strlen()>.
414 *
415 * Args: p - ptr to buffer or string
416 * n - length of buffer/string <p>, in bytes
417 * ret_bf - RETURN: new ESL_BUFFER
418 *
419 * Returns: <eslOK> on success, and <*ret_bf> points to new buffer.
420 *
421 * Throws: <eslEMEM> on allocation failure.
422 * On any exception, <*ret_bf> is <NULL>.
423 */
424 int
425 esl_buffer_OpenMem(const char *p, esl_pos_t n, ESL_BUFFER **ret_bf)
426 {
427 ESL_BUFFER *bf = NULL;
428 int status;
429
430 if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
431
432 bf->mem = (char *) p; /* force discard of const qualifier; this is ok; mem won't be altered in eslBUFFER_STRING mode */
433 bf->n = (n == -1) ? strlen(p) : n;
434 bf->mode_is = eslBUFFER_STRING;
435
436 *ret_bf = bf;
437 return eslOK;
438
439 ERROR:
440 if (bf) { /* on error, restore to UNSET state */
441 bf->mem = NULL;
442 bf->n = 0;
443 bf->mode_is = eslBUFFER_UNSET;
444 }
445 *ret_bf = bf;
446 return status;
447 }
448
449
450 /* Function: esl_buffer_OpenStream()
451 * Synopsis: "Open" an existing stream for parsing.
452 *
453 * Purpose: Given an open stream <fp> for reading, create an
454 * <ESL_BUFFER> around it.
455 *
456 * <fp> is often <stdin>, for example.
457 *
458 * The caller remains responsible for closing <fp>, if it
459 * opened it.
460 *
461 * Args: fp - stream to associate with new ESL_BUFFER
462 * *ret_bf - RETURN: new ESL_BUFFER.
463 *
464 * Returns: <eslOK> on success, and <*ret_bf> points to a new <ESL_BUFFER>.
465 *
466 * Throws: <eslEINVAL>: <fp> is NULL, in error state, or already at eof before any reading occurs.
467 * <eslESYS> : fread() failed
468 * <eslEMEM> : an allocation failed
469 */
470 int
471 esl_buffer_OpenStream(FILE *fp, ESL_BUFFER **ret_bf)
472 {
473 ESL_BUFFER *bf = NULL;
474 int status;
475
476 if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
477 bf->mode_is = eslBUFFER_STREAM;
478
479 if (fp == NULL || ferror(fp) || feof(fp)) ESL_XEXCEPTION(eslEINVAL, "invalid stream");
480 bf->fp = fp; /* a copy of <fp>; caller is still responsible for it */
481
482 ESL_ALLOC(bf->mem, sizeof(char) * bf->pagesize);
483 bf->balloc = bf->pagesize;
484
485 bf->n = fread(bf->mem, sizeof(char), bf->pagesize, bf->fp);
486 if (bf->n < bf->pagesize && ferror(bf->fp))
487 ESL_XEXCEPTION(eslESYS, "failed to read first chunk of stream");
488
489 *ret_bf = bf;
490 return eslOK;
491
492 ERROR:
493 esl_buffer_Close(bf);
494 *ret_bf = NULL;
495 return status;
496 }
497
498 /* Function: esl_buffer_Close()
499 * Synopsis: Close an input buffer.
500 * Incept: SRE, Mon Feb 14 09:09:04 2011 [Janelia]
501 *
502 * Purpose: Close the input buffer <bf>, freeing all resources that it
503 * was responsible for.
504 *
505 * Args: bf - the input buffer
506 *
507 * Returns: <eslOK> on success.
508 *
509 * Throws: <eslESYS> on a system call failure such as <munmap()>, <pclose()>, or <fclose()>.
510 *
511 * Note: error handling here departs from usual idiom, because we try to tolerate errors
512 * and continue free'ing resources; only at the end do we return a failure code, if
513 * something went awry.
514 */
515 int
516 esl_buffer_Close(ESL_BUFFER *bf)
517 {
518 if (bf)
519 {
520 if (bf->mem)
521 {
522 switch (bf->mode_is) {
523 case eslBUFFER_MMAP: if (munmap(bf->mem, bf->n) == -1) ESL_EXCEPTION(eslESYS, "munmap() failed"); break;
524 case eslBUFFER_STRING: break; /* caller provided and remains responsible for an input memory buffer */
525 default: free(bf->mem);
526 }
527 }
528
529 if (bf->fp)
530 {
531 switch (bf->mode_is) {
532 case eslBUFFER_CMDPIPE: if (pclose(bf->fp) == -1) ESL_EXCEPTION(eslESYS, "pclose() failed"); break;
533 case eslBUFFER_STREAM: break; /* caller provided and remains responsible for an open stream */
534 default: if (fclose(bf->fp) == -1) ESL_EXCEPTION(eslESYS, "fclose() failed"); break;
535 }
536 }
537
538 if (bf->filename) free(bf->filename);
539 if (bf->cmdline) free(bf->cmdline);
540 free(bf);
541 }
542 return eslOK;
543 }
544 /*--------------- end, ESL_BUFFER open/close --------------------*/
545
546
547
548
549
550 /*****************************************************************
551 *# 2. Positioning and anchoring an ESL_BUFFER
552 *****************************************************************/
553
554 /* Function: esl_buffer_GetOffset()
555 * Synopsis: Get the current position of parser in input buffer.
556 *
557 * Purpose: Returns the current offset position of the parser
558 * in the input buffer: <bf->baseoffset + bf->pos>.
559 */
560 esl_pos_t
561 esl_buffer_GetOffset(ESL_BUFFER *bf)
562 {
563 return bf->baseoffset + bf->pos;
564 }
565
566 /* Function: esl_buffer_SetOffset()
567 * Synopsis: Reposition the input buffer to a new place.
568 * Incept: SRE, Mon Jan 31 13:14:09 2011 [Janelia]
569 *
570 * Purpose: Set the buffer's internal state (<bf->pos>) to position
571 * <offset> in the input. Load new data into the buffer if
572 * necessary.
573 *
574 * In modes where <bf->mem> contains the whole input
575 * (ALLFILE, MMAP, STRING), this always works.
576 *
577 * In modes where we're reading a
578 * nonrewindable/nonpositionable stream (STREAM, CMDPIPE),
579 * <offset> may be at or ahead of the current position, but
580 * rewinding to an offset behind the current position only
581 * works if <offset> is within the current buffer
582 * window. If the caller knows it wants to return to some
583 * <offset> later, it should set an anchor to make sure it
584 * stays in the buffer. New data may need to be read into
585 * <bf->mem> to assure <pagesize> bytes are available. If
586 * an anchor is set, this may require reoffset and/or
587 * reallocation of <bf->mem>.
588 *
589 * FILE mode is handled as above, but additionally, if no
590 * anchor is set and <offset> is not in the current buffer,
591 * <fseeko()> is used to reposition in the open file. If
592 * <fseeko()> is unavailable (non-POSIX compliant systems),
593 * FILE mode is handled like other streams, with limited
594 * rewind ability.
595 *
596 * Args: bf - input buffer being manipulated
597 * offset - new position in the input
598 *
599 * Returns: <eslOK> on success.
600 *
601 * Throws: <eslEINVAL> if <offset> is invalid, either because it
602 * would require rewinding the (nonrewindable) stream,
603 * or because it's beyond the end.
604 * <eslESYS> if a system call fails, such as fread().
605 * <eslEMEM> on allocation failure.
606 * <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
607 */
608 int
609 esl_buffer_SetOffset(ESL_BUFFER *bf, esl_pos_t offset)
610 {
611 int status;
612
613 /* Case 1. We have the entire file in bf->mem (or an mmap of it);
614 * Then this is trivial; we just set bf->pos.
615 */
616 if (bf->mode_is == eslBUFFER_ALLFILE ||
617 bf->mode_is == eslBUFFER_MMAP ||
618 bf->mode_is == eslBUFFER_STRING)
619 {
620 bf->baseoffset = 0; /* (redundant: just to assure you that state is correctly set) */
621 bf->pos = offset;
622 }
623
624 /* Case 2. We have an open stream.
625 * Then:
626 * - if offset is behind us, and in our current buffer window,
627 * rewind is always possible and trivial: set bf->pos; or
628 * - if we're a FILE, and we're on a POSIX system with fseeko(),
629 * and there's no anchor set -- then we can fseeko() to the
630 * desired offset (no matter where it is) and
631 * reinitialize the buffer; or
632 * - otherwise rewinding a stream is not possible, generating
633 * an <eslEINVAL> error; or
634 * - finally, the remaining possibility is that the offset is
635 * ahead of (or at) the current parser position; fread()
636 * (respecting any set anchor) until <offset> is in the
637 * current buffer window, put bf->pos on it, and call
638 * buffer_refill() to be sure that we either have at least
639 * <bf->pagesize> bytes to parse (inclusive of current pos)
640 * or the stream reaches EOF.
641 */
642 else if (bf->mode_is == eslBUFFER_STREAM ||
643 bf->mode_is == eslBUFFER_CMDPIPE ||
644 bf->mode_is == eslBUFFER_FILE)
645 {
646 if (offset >= bf->baseoffset && offset < bf->baseoffset + bf->pos) /* offset is in our current window and behind our current pos; rewind is trivial */
647 {
648 bf->pos = offset-bf->baseoffset;
649 }
650
651 #ifdef _POSIX_VERSION
652 else if (bf->mode_is == eslBUFFER_FILE && bf->anchor == -1)
653 { /* a posix-compliant system can always fseeko() on a file */
654 if (fseeko(bf->fp, offset, SEEK_SET) != 0) ESL_EXCEPTION(eslEINVAL, "fseeko() failed, probably bad offset");
655 bf->baseoffset = offset;
656 bf->n = 0;
657 bf->pos = 0;
658 status = buffer_refill(bf, 0);
659 if (status == eslEOF) ESL_EXCEPTION(eslEINVAL, "requested offset is beyond end of file");
660 else if (status != eslOK) return status;
661 }
662 #endif /*_POSIX_VERSION*/
663
664 else if (offset < bf->baseoffset) /* we've already streamed past the requested offset. */
665 ESL_EXCEPTION(eslEINVAL, "can't rewind stream past base offset");
666
667 else /* offset is ahead of pos (or on it); fast forward, put bf->pos on it, reloading bf->mem as needed, respecting any anchors */
668 {
669 while (offset >= bf->baseoffset + bf->n)
670 {
671 bf->pos = bf->n;
672 status = buffer_refill(bf, 0);
673 if (status == eslEOF) ESL_EXCEPTION(eslEINVAL, "requested offset is beyond end of stream");
674 else if (status != eslOK) return status;
675 }
676 bf->pos = offset - bf->baseoffset;
677 status = buffer_refill(bf, 0);
678 if (status != eslEOF && status != eslOK) return status;
679 }
680 }
681
682 else ESL_EXCEPTION(eslEINCONCEIVABLE, "attempting to manipulate an uninitialized buffer");
683
684 return eslOK;
685 }
686
687
688
689 /* Function: esl_buffer_SetAnchor()
690 * Synopsis: Sets an anchor in an input stream.
691 *
692 * Purpose: Set an anchor at byte <offset> (in input coords) in
693 * input <bf>: which means, keep everything from this byte
694 * on in buffer memory, until anchor is raised.
695 *
696 * The presence of an anchor affects new reads from <fp>;
697 * <mem[r..n-1]> are protected from overwrite, and may be
698 * moved to <mem[0..n-r-1]> as new data is read from the
699 * stream. Anchors are only needed for input streams that
700 * we read chunkwise. If entire input is already in <bf>,
701 * setting an anchor is a no-op.
702 *
703 * In general, the caller should remember what anchor(s) it
704 * sets, so it can raise them later with
705 * <esl_buffer_RaiseAnchor()>.
706 *
707 * Byte <offset> must be in the current buffer window. If
708 * not, an <eslEINVAL> exception is thrown.
709 *
710 * Only one anchor is active at a time. If an anchor is
711 * already set for <bf>, the most upstream one is used.
712 *
713 * Args: bf - input buffer
714 * offset - absolute position in input, <0..inputlen-1>
715 *
716 * Returns: <eslOK> on success.
717 *
718 * Throws: <eslEINVAL> if <offset> is not in current buffer window.
719 */
720 int
721 esl_buffer_SetAnchor(ESL_BUFFER *bf, esl_pos_t offset)
722 {
723 if (! bf->fp) return eslOK; /* without an open stream, no-op */
724 if (offset < bf->baseoffset || offset > bf->baseoffset + bf->n)
725 ESL_EXCEPTION(eslEINVAL, "can't set an anchor outside current buffer");
726
727 if (bf->anchor == -1 || offset-bf->baseoffset < bf->anchor)
728 { /* setting a new anchor */
729 bf->anchor = offset-bf->baseoffset;
730 bf->nanchor = 1;
731 }
732 else if (offset-bf->baseoffset == bf->anchor)
733 { /* reinforcing an anchor */
734 bf->nanchor++;
735 }
736
737 return eslOK;
738 }
739
740 /* Function: esl_buffer_SetStableAnchor()
741 * Synopsis: Set a stable anchor.
742 *
743 * Purpose: Same as <esl_buffer_SetAnchor()>, except the anchor is
744 * such that all pointers returned by <_Get*()> functions
745 * (i.e. as opposed to just the last <_Get*> function)
746 * will remain valid at least until the anchor is raised.
747 *
748 * The main use of this is when the caller wants to get
749 * multiple lines or tokens in the input before parsing
750 * them.
751 *
752 * A stable anchor prevents buffer refills/reloads from
753 * moving the internal memory around while the anchor is
754 * in place.
755 *
756 * Args: bf - input buffer
757 * offset - absolute position in input, <0..inputlen-1>
758 *
759 * Returns: <eslOK> on success.
760 *
761 * Throws: <eslEINVAL> if <offset> is not in current buffer window.
762 *
763 * Notes: We make a special call for stable anchors, as opposed
764 * to most anchors, because the <memmove()> call here
765 * to rebaseline the buffer's <mem> is expensive.
766 */
767 int
768 esl_buffer_SetStableAnchor(ESL_BUFFER *bf, esl_pos_t offset)
769 {
770 esl_pos_t ndel;
771 int status;
772
773 if (! bf->fp) return eslOK; /* without an open stream, no-op: everything is available */
774
775 if ( (status = esl_buffer_SetAnchor(bf, offset)) != eslOK) return status;
776
777 ndel = bf->anchor;
778 bf->anchor = 0;
779 bf->n -= ndel;
780 bf->pos -= ndel;
781 if (bf->n) memmove(bf->mem, bf->mem+ndel, bf->n);
782 bf->baseoffset += ndel;
783 return eslOK;
784 }
785
786
787 /* Function: esl_buffer_RaiseAnchor()
788 * Synopsis: Raise an anchor.
789 *
790 * Purpose: Declare that an anchor previously set at <offset>
791 * in buffer <bf> may be raised.
792 *
793 * <offset> is in absolute input coordinates (<0..len-1> for
794 * an input of length <len>). Because it's supposed to be
795 * anchored, this position ought to be in the current
796 * buffer window. If an anchor is in effect in <bf>,
797 * <offset> should be at or distal to that anchor.
798 *
799 * The buffer's memory and position are not changed yet. A
800 * caller can raise an anchor and still assume that the
801 * buffer contains all data from that anchor, until the
802 * next call to something that would alter the buffer.
803 *
804 * Args: bf - input buffer
805 * offset - absolute position in input, <0..len-1>
806 *
807 * Returns: <eslOK> on success.
808 *
809 * Throws: (none)
810 */
811 int
812 esl_buffer_RaiseAnchor(ESL_BUFFER *bf, esl_pos_t offset)
813 {
814 ESL_DASSERT1(( offset >= bf->baseoffset && offset <= bf->baseoffset + bf->n ));
815 ESL_DASSERT1(( bf->anchor <= offset - bf->baseoffset ));
816
817 if (bf->anchor == offset - bf->baseoffset) {
818 bf->nanchor--;
819 if (bf->nanchor == 0) bf->anchor = -1;
820 }
821 return eslOK;
822 }
823 /*--------------- end, ESL_BUFFER manipulation ------------------*/
824
825
826
827
828 /*****************************************************************
829 *# 3. Raw access to the buffer
830 *****************************************************************/
831
832 /* Function: esl_buffer_Get()
833 * Synopsis: Get a pointer into the current buffer window.
834 * Incept: SRE, Mon Jan 31 20:45:22 2011 [Casa de Gatos]
835 *
836 * Purpose: Given a buffer <bf>, return a pointer to the current
837 * parsing position in <*ret_p>, and the number of valid
838 * bytes from that position in <*ret_n>.
839 *
840 * If buffer is at EOF (no valid bytes remain), returns
841 * <eslEOF> with <NULL> in <*ret_p> and 0 in <*ret_n>.
842 *
843 * The buffer's parsing position <bf->pos> is NOT
844 * changed. Another <Get()> call will return exactly
845 * the same <p> and <n>. Each <Get()> call is generally
846 * followed by a <Set()> call. It's the <Set()> call
847 * that moves <bf->pos> and refills the buffer.
848 *
849 * Assumes that the buffer <bf> is correctly loaded,
850 * with either at least <pagesize> bytes after the
851 * parser position, or near/at EOF.
852 *
853 * Args: bf - buffer to get ptr from
854 * ret_p - RETURN: pointer to current parser position, or NULL on EOF
855 * ret_n - RETURN: number of valid bytes at *ret_p, or 0 on EOF
856 *
857 * Returns: <eslOK> on success;
858 * <eslEOF> if no valid bytes remain in the input, or if
859 * <*ret_n> is less than <nrequest>.
860 *
861 * Throws: <eslEMEM> on allocation failure.
862 * <eslESYS> if fread() fails mysteriously.
863 * <eslEINCONCEIVABLE> if internal state of <bf> is corrupt.
864 */
865 int
866 esl_buffer_Get(ESL_BUFFER *bf, char **ret_p, esl_pos_t *ret_n)
867 {
868 *ret_p = (bf->pos < bf->n ? bf->mem + bf->pos : NULL);
869 *ret_n = (bf->pos < bf->n ? bf->n - bf->pos : 0);
870 return (bf->pos < bf->n ? eslOK : eslEOF);
871 }
872
873 /* Function: esl_buffer_Set()
874 * Synopsis: Set position and correct state of the <ESL_BUFFER>.
875 * Incept: SRE, Sun Jan 2 11:56:00 2011 [Zaragoza]
876 *
877 * Purpose: Reset the state of buffer <bf>: we were recently
878 * given a pointer <p> by an <esl_buffer_Get()> call
879 * and we parsed <nused> bytes starting at <p[0]>.
880 *
881 * <bf->pos> is set to point at <p+nused>, and we
882 * reload the buffer (if necessary) to try to have at
883 * least <bf->pagesize> bytes of input following that
884 * position.
885 *
886 * One use is in raw parsing, where we stop parsing
887 * somewhere in the buffer:
888 * \begin{cchunk}
889 * esl_buffer_Get(bf, &p, &n);
890 * (do some stuff on p[0..n-1], using up <nused> bytes)
891 * esl_buffer_Set(bf, p, nused);
892 * \end{cchunk}
893 * This includes the case of nused=n, where we parse the
894 * whole buffer that Get() gave us, and the Set() call may
895 * be needed to load new input data before the next Get().
896 *
897 * Another use is an idiom for peeking at a token, line, or
898 * a number of bytes without moving the parser position:
899 * \begin{cchunk}
900 * esl_buffer_GetLine(bf, &p, &n);
901 * (do we like what we see in p[0..n-1]? no? then put it back)
902 * esl_buffer_Set(bf, p, 0);
903 * \end{cchunk}
904 *
905 * Because it is responsible for loading new input as
906 * needed, Set() may reoffset and reallocate <mem>. If the
907 * caller wants an anchor respected, it must make sure that
908 * anchor is still in effect; i.e., a caller that is
909 * restoring state to an <ESL_BUFFER> should call Set()
910 * BEFORE calling RaiseAnchor().
911 *
912 * As a special case, if <p> is NULL, then <nused> is
913 * ignored, <bf->pos> is left whereever it was, and the
914 * only thing the <Set()> attempts to do is to fulfill the
915 * pagesize guarantee from the current position. If a
916 * <NULL> <p> has been returned by a Get*() call because we
917 * reached EOF, for example in some parsing loop that the
918 * EOF has broken us out of, it is safe to call
919 * <esl_buffer_Set(bf, NULL, 0)>: this is a no-op on a
920 * buffer that is at EOF.
921 *
922 * Args: bf - buffer to set
923 * p - pointer that previous Get() gave us
924 * nused - number of bytes we used, starting at p[0]
925 *
926 * Returns: <eslOK> on success.
927 *
928 * Throws: <eslEMEM> on allocation failure.
929 * <eslESYS> if fread() fails mysteriously.
930 * <eslEINCONCEIVABLE> if internal state of <bf> is corrupt.
931 */
932 int
933 esl_buffer_Set(ESL_BUFFER *bf, char *p, esl_pos_t nused)
934 {
935 int status;
936 if (p) bf->pos = (p - bf->mem) + nused;
937 status = buffer_refill(bf, 0);
938 if (status == eslOK || status == eslEOF) return eslOK;
939 else return status;
940 }
941 /*----------------- end, lowest level access --------------------*/
942
943
944
945
946 /*****************************************************************
947 *# 4. Line-based parsing
948 *****************************************************************/
949
950 /* Function: esl_buffer_GetLine()
951 * Synopsis: Get ptr to next line in buffer.
952 *
953 * Purpose: Get a pointer <*opt_p> to the next line in buffer <bf>,
954 * and the length of the line in <*opt_n> (in bytes, and
955 * exclusive of newline bytes). Advance buffer position
956 * past (one) newline, putting it on the next valid data
957 * byte. Thus <p[0..n-1]> is one data line. It is not
958 * NUL-terminated.
959 *
960 * <bf>'s buffer may be re(al)located as needed, to get
961 * the whole line into the current window.
962 *
963 * Because the caller only gets a pointer into <bf>'s
964 * internal state, no other <esl_buffer> functions
965 * should be called until the caller is done with <p>.
966 *
967 * To peek at next line, use Set to restore <bf>'s state:
968 * \begin{cchunk}
969 * esl_buffer_GetLine(bf, &p, &n);
970 * esl_buffer_Set(bf, p, 0);
971 * \end{cchunk}
972 *
973 * Args: bf - buffer to get line from
974 * *opt_p - optRETURN: pointer to next line
975 * *opt_n - optRETURN: line length, exclusive of newline.
976 *
977 * Returns: <eslOK> on success. <*opt_p> is a valid pointer into <bf>'s buffer,
978 * and <*opt_n> is >=0. (0 would be an empty line.)
979 *
980 * <eslEOF> if there's no line (even blank).
981 * On EOF, <*opt_p> is NULL and <*opt_n> is 0.
982 *
983 * Throws: <eslEMEM> if allocation fails.
984 * <eslESYS> if a system call such as fread() fails unexpectedly
985 * <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
986 */
987 int
988 esl_buffer_GetLine(ESL_BUFFER *bf, char **opt_p, esl_pos_t *opt_n)
989 {
990 int anch_set = FALSE;
991 esl_pos_t nc, nskip;
992 esl_pos_t anch;
993 int status;
994
995 /* The next line starts at offset <baseoffset + pos> */
996 anch = bf->baseoffset + bf->pos;
997 status = esl_buffer_SetAnchor(bf, anch);
998 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; } /* we know bf->pos is in current window */
999 else if (status != eslOK) { goto ERROR; }
1000 anch_set = TRUE;
1001
1002 if ( (status = buffer_countline(bf, &nc, &nskip)) != eslOK) goto ERROR; /* includes normal EOF. */
1003
1004 status = buffer_refill(bf, nskip);
1005 if (status != eslEOF && status != eslOK) goto ERROR; /* accept EOF here, we've already got our line */
1006
1007 anch_set = FALSE;
1008 status = esl_buffer_RaiseAnchor(bf, anch);
1009 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; } /* we know bf->pos is in current window */
1010 else if (status != eslOK) { goto ERROR; }
1011 if (opt_p) *opt_p = bf->mem + bf->pos;
1012 if (opt_n) *opt_n = nc;
1013 bf->pos += nskip;
1014 return eslOK;
1015
1016 ERROR:
1017 if (anch_set) esl_buffer_RaiseAnchor(bf, anch);
1018 if (opt_p) *opt_p = NULL;
1019 if (opt_n) *opt_n = 0;
1020 return status;
1021 }
1022
1023 /* Function: esl_buffer_FetchLine()
1024 * Synopsis: Fetch next line from a buffer.
1025 * Incept: SRE, Tue Feb 1 15:37:34 2011 [Janelia]
1026 *
1027 * Purpose: Get the next line from the buffer <bf>, starting from its
1028 * current position. Return an allocated copy of it in
1029 * <*opt_p>, and its length in bytes in <*opt_n>. Advance
1030 * the buffer position past (one) newline, putting it on
1031 * the next valid byte. The last line in a file does not
1032 * need to be terminated by a newline. The returned memory is not
1033 * NUL-terminated.
1034 *
1035 * If the next line is empty (solely a newline character),
1036 * returns <eslOK>, but with <*opt_p> as <NULL> and
1037 * <*opt_n> as 0.
1038 *
1039 * Caller is responsible for free'ing <*opt_p>.
1040 *
1041 * Because <*ret_p> is a copy of <bf>'s internal buffer,
1042 * caller may continue to manipulate <bf>, unlike
1043 * <esl_buffer_GetLine()>.
1044 *
1045 * Args: bf - buffer to get line from
1046 * *opt_p - optRETURN: pointer to allocated copy of next line
1047 * *opt_n - optRETURN: length of <*opt_p>
1048 *
1049 * Returns: <eslOK> on success. Either <*opt_p> is an allocated copy
1050 * of next line and <*opt_n> is $>0$, or <*opt_p> is <NULL>
1051 * and <*opt_n> is 0 (in the case where the line is empty,
1052 8 immediately terminated by newline, such as \verb+"\n"+.).
1053 *
1054 * <eslEOF> if there's no line (even blank).
1055 * On EOF, <*opt_p> is NULL and <*opt_n> is 0.
1056 *
1057 * Throws: <eslEMEM> if allocation fails.
1058 * <eslESYS> if a system call such as fread() fails unexpectedly
1059 * <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
1060 */
1061 int
1062 esl_buffer_FetchLine(ESL_BUFFER *bf, char **opt_p, esl_pos_t *opt_n)
1063 {
1064 int anch_set = FALSE;
1065 char *p = NULL;
1066 esl_pos_t anch;
1067 esl_pos_t nc, nskip;
1068 int status;
1069
1070 anch = bf->baseoffset + bf->pos;
1071 status = esl_buffer_SetAnchor(bf, anch);
1072 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; } /* we know bf->pos is in current window */
1073 else if (status != eslOK) { goto ERROR; }
1074 anch_set = TRUE;
1075
1076 if ( (status = buffer_countline(bf, &nc, &nskip)) != eslOK) goto ERROR; /* inc. normal EOF */
1077
1078 if (nc) { /* nc==0 on an empty line - then <*opt_p> comes back NULL */
1079 ESL_ALLOC(p, sizeof(char) * nc);
1080 memcpy(p, bf->mem+bf->pos, nc);
1081 }
1082 bf->pos += nskip;
1083
1084 anch_set = FALSE;
1085 status = esl_buffer_RaiseAnchor(bf, anch);
1086 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1087 else if (status != eslOK) { goto ERROR; }
1088
1089 status = buffer_refill(bf, 0);
1090 if (status != eslEOF && status != eslOK) goto ERROR; /* accept EOF here, we've already got our line */
1091
1092 if (opt_p) *opt_p = p; else free(p);
1093 if (opt_n) *opt_n = nc;
1094 return eslOK;
1095
1096 ERROR:
1097 if (anch_set) esl_buffer_RaiseAnchor(bf, anch);
1098 if (p) free(p);
1099 if (opt_p) *opt_p = NULL;
1100 if (opt_n) *opt_n = 0;
1101 return status;
1102 }
1103
1104 /* Function: esl_buffer_FetchLineAsStr()
1105 * Synopsis: Fetch next line from buffer, and NUL-terminate it.
1106 * Incept: SRE, Thu Feb 10 09:22:47 2011 [Janelia]
1107 *
1108 * Purpose: Same as <esl_buffer_FetchLine()> except the
1109 * returned line is <NUL>-terminated and can be treated
1110 * as a string.
1111 *
1112 * Args: bf - input buffer
1113 * *opt_s - optRETURN: pointer to allocated copy of next line
1114 * *opt_n - optRETURN: strlen() of <*opt_s>
1115 *
1116 * Returns: <eslOK> on success. <*opt_p> is an allocated copy
1117 * of next line and <*opt_n> is >=0. (0 would be an empty line
1118 * terminated by newline, such as \verb+\n+.)
1119 *
1120 * <eslEOF> if there's no line (even blank).
1121 * On EOF, <*opt_p> is NULL and <*opt_n> is 0.
1122 *
1123 * Throws: <eslEMEM> if allocation fails.
1124 * <eslEINVAL> if an anchoring attempt is invalid
1125 * <eslESYS> if a system call such as fread() fails unexpectedly
1126 * <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
1127 */
1128 int
1129 esl_buffer_FetchLineAsStr(ESL_BUFFER *bf, char **opt_s, esl_pos_t *opt_n)
1130 {
1131 int anch_set = FALSE;
1132 char *s = NULL;
1133 esl_pos_t anch;
1134 esl_pos_t nc, nskip;
1135 int status;
1136
1137 anch = bf->baseoffset + bf->pos;
1138 status = esl_buffer_SetAnchor(bf, anch);
1139 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; } /* we know bf->pos is in current window */
1140 else if (status != eslOK) { goto ERROR; }
1141 anch_set = TRUE;
1142
1143 if ( (status = buffer_countline(bf, &nc, &nskip)) != eslOK) goto ERROR; /* inc normal EOF */
1144
1145 ESL_ALLOC(s, sizeof(char) * (nc+1));
1146 memcpy(s, bf->mem+bf->pos, nc);
1147 s[nc] = '\0';
1148 bf->pos += nskip;
1149
1150 anch_set = FALSE;
1151 status = esl_buffer_RaiseAnchor(bf, anch);
1152 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1153 else if (status != eslOK) { goto ERROR; }
1154
1155 status = buffer_refill(bf, 0);
1156 if (status != eslEOF && status != eslOK) goto ERROR; /* accept EOF here, we've already got our line */
1157
1158 if (opt_s) *opt_s = s; else free(s);
1159 if (opt_n) *opt_n = nc;
1160 return eslOK;
1161
1162 ERROR:
1163 if (anch_set) esl_buffer_RaiseAnchor(bf, anch);
1164 if (s) free(s);
1165 if (opt_s) *opt_s = NULL;
1166 if (opt_n) *opt_n = 0;
1167 return status;
1168
1169 }
1170 /*------------------ end, line-based parsing --------------------*/
1171
1172 /*****************************************************************
1173 *# 5. Token-based parsing
1174 *****************************************************************/
1175
1176 /* Function: esl_buffer_GetToken()
1177 * Synopsis: Get next token.
1178 * Incept: SRE, Sat Jan 1 19:42:44 2011 [Janelia]
1179 *
1180 * Purpose: Find the next token in <bf> delimited by the separator
1181 * characters in <sep> or newline. Return a pointer
1182 * to that token in <*opt_tok>, and its length in <*opt_n>.
1183 * A 'token' consists of one or more characters that are
1184 * neither in <sep> nor a newline (verb+\r+ or \verb+\n+).
1185 *
1186 * Because the caller only gets a pointer into the buffer's
1187 * current memory, it should not call another
1188 * <esl_buffer_*> function until it's done with the token
1189 * or made a copy of it.
1190 *
1191 * In detail, starting from the buffer <bf>'s current
1192 * point; first skip past any leading characters in <sep>. If EOF
1193 * is reached, return <eslEOF>. If the point is now on a
1194 * newline, skip past it and return <eslEOL>. Set an anchor
1195 * at the current point. Count how many non-separator
1196 * characters <n> occur from the current point <p>
1197 * (expand/refill buffer as needed), and define the token
1198 * as <p[0..n-1]>. Skip any trailing characters in <sep>.
1199 * Set the point to the start of the next token (a char not
1200 * in <sep>.) Release the anchor and return.
1201 *
1202 * If caller knows how many tokens it expects on each line,
1203 * it should not include \verb+"\r\n"+ in its <sep>. This way,
1204 * hitting a newline will cause a <eslEOL> return. The
1205 * caller can check for expected or unexpected <EOL>'s.
1206 *
1207 * If the caller doesn't care how many tokens it allows per
1208 * line, it should include \verb+"\r\n"+ in its <sep>. Now
1209 * newlines will be skipped like any other separator
1210 * character, and the only normal returns are <eslEOF> and
1211 * <eslOK>.
1212 *
1213 * Args: bf - open buffer
1214 * sep - string defining separator characters; <" \t\r\n"> for example.
1215 * opt_tok - optRETURN: pointer to token in the <bf>
1216 * opt_n - optRETURN: number of characters in the token
1217 *
1218 * Returns: <eslOK> if a token is found; <*ret_p> points to it,
1219 * and <*opt_n> is its length in chars (> 0). The current
1220 * point is at the start of the next token.
1221 *
1222 * <eslEOF> if the input ends before any token is found.
1223 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The current
1224 * point is at EOF.
1225 *
1226 * <eslEOL> if a line ends before a token is found. (This
1227 * case only arises if *sep does not contain newline.)
1228 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The current
1229 * point is at the next character following the newline.
1230 *
1231 * <bf->mem> may be modified and/or reallocated, if new
1232 * input reads are required to find the entire token.
1233 *
1234 * Throws: <eslEMEM> if an allocation fails.
1235 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The
1236 * current point is undefined.
1237 */
1238 int
1239 esl_buffer_GetToken(ESL_BUFFER *bf, const char *sep, char **opt_tok, esl_pos_t *opt_n)
1240 {
1241 esl_pos_t anch;
1242 esl_pos_t nc;
1243 int anch_set = FALSE;
1244 int status;
1245
1246 if ( (status = buffer_skipsep(bf, sep)) != eslOK) goto ERROR; /* includes EOF */
1247 /* Now bf->pos is sitting on first char after seps */
1248
1249 if ( ( status = buffer_newline(bf)) != eslOK) goto ERROR; /* includes EOL */
1250
1251 anch = bf->baseoffset + bf->pos;
1252 status = esl_buffer_SetAnchor(bf, anch);
1253 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; } /* we know bf->pos is in current window */
1254 else if (status != eslOK) { goto ERROR; }
1255
1256 anch_set = TRUE;
1257
1258 if ( (status = buffer_counttok(bf, sep, &nc)) != eslOK) goto ERROR;
1259 bf->pos += nc;
1260
1261 if ((status = buffer_skipsep(bf, sep)) != eslOK && status != eslEOF) goto ERROR;
1262 if ((status = buffer_refill(bf, 0)) != eslOK && status != eslEOF) goto ERROR;
1263
1264 if (opt_tok) *opt_tok = bf->mem + (anch - bf->baseoffset);
1265 if (opt_n) *opt_n = nc;
1266 anch_set = FALSE;
1267
1268 status = esl_buffer_RaiseAnchor(bf, anch);
1269 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1270 else if (status != eslOK) { goto ERROR; }
1271 return eslOK;
1272
1273 ERROR:
1274 if (anch_set) esl_buffer_RaiseAnchor(bf, anch);
1275 if (opt_tok) *opt_tok = NULL;
1276 if (opt_n) *opt_n = 0;
1277 return status;
1278 }
1279
1280 /* Function: esl_buffer_FetchToken()
1281 * Synopsis: Fetch copy of next token.
1282 * Incept: SRE, Thu Feb 24 08:54:54 2011 [Janelia]
1283 *
1284 * Purpose: Essentially the same as <esl_buffer_GetToken()>, except a
1285 * copy of the token is made into newly allocated memory,
1286 * and a pointer to this memory is returned in <*opt_tok>.
1287 * The caller is responsible for freeing the memory.
1288 *
1289 * The token is raw memory, not a <NUL>-terminated string.
1290 * To fetch tokens as <NUL>-terminated strings, see
1291 * <esl_buffer_GetTokenAsStr()>.
1292 *
1293 * Args: bf - open buffer
1294 * sep - string defining separator characters; <" \t\r\n"> for example.
1295 * opt_tok - optRETURN: allocated copy of token
1296 * opt_n - optRETURN: number of characters in the token
1297 *
1298 * Returns: <eslOK> if a token is found; <*ret_p> points to it,
1299 * and <*opt_n> is its length in chars (> 0). The current
1300 * point is at the start of the next token.
1301 *
1302 * <eslEOF> if the input ends before any token is found.
1303 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The current
1304 * point is at EOF.
1305 *
1306 * <eslEOL> if a line ends before a token is found. (This
1307 * case only arises if *sep does not contain newline.)
1308 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The current
1309 * point is at the next character following the newline.
1310 *
1311 * <bf->mem> may be modified and/or reallocated, if new
1312 * input reads are required to find the entire token.
1313 *
1314 * Throws: <eslEMEM> if an allocation fails.
1315 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The
1316 * current point is undefined.
1317 */
1318 int
1319 esl_buffer_FetchToken(ESL_BUFFER *bf, const char *sep, char **opt_tok, esl_pos_t *opt_n)
1320 {
1321 char *tok = NULL;
1322 esl_pos_t anch;
1323 esl_pos_t nc;
1324 int anch_set = FALSE;
1325 int status;
1326
1327 if ( (status = buffer_skipsep(bf, sep)) != eslOK) goto ERROR; /* includes EOF */
1328 /* Now bf->pos is sitting on first char after seps */
1329
1330 if ( ( status = buffer_newline(bf)) != eslOK) goto ERROR; /* includes EOL */
1331
1332 anch = bf->baseoffset + bf->pos;
1333 status = esl_buffer_SetAnchor(bf, anch);
1334 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1335 else if (status != eslOK) { goto ERROR; }
1336 anch_set = TRUE;
1337
1338 if ( (status = buffer_counttok(bf, sep, &nc)) != eslOK) goto ERROR;
1339 /* now we know that pos..pos+nc-1 is a token; pos+nc is the next parser position */
1340
1341 /* copy the token */
1342 ESL_ALLOC(tok, sizeof(char) * nc);
1343 memcpy(tok, bf->mem+bf->pos, nc);
1344 bf->pos += nc;
1345
1346 /* in a Fetch, we can raise the anchor before the new refill */
1347 status = esl_buffer_RaiseAnchor(bf, anch);
1348 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1349 else if (status != eslOK) { goto ERROR; }
1350 anch_set = FALSE;
1351
1352 if ((status = buffer_skipsep(bf, sep)) != eslOK && status != eslEOF) goto ERROR;
1353 if ((status = buffer_refill(bf, 0)) != eslOK && status != eslEOF) goto ERROR;
1354
1355 if (opt_tok) *opt_tok = tok; else free(tok);
1356 if (opt_n) *opt_n = nc;
1357 return eslOK;
1358
1359 ERROR:
1360 if (tok) free(tok);
1361 if (anch_set) esl_buffer_RaiseAnchor(bf, anch);
1362 if (opt_tok) *opt_tok = NULL;
1363 if (opt_n) *opt_n = 0;
1364 return status;
1365 }
1366
1367
1368 /* Function: esl_buffer_FetchTokenAsStr()
1369 * Synopsis: Fetch copy of next token as \verb+\0+-terminated string.
1370 * Incept: SRE, Sat Jan 1 19:31:57 2011 [Zaragoza]
1371 *
1372 * Purpose: Essentially the same as <esl_buffer_FetchToken()>
1373 * except the copied token is \verb+\0+-terminated so it
1374 * can be treated as a string.
1375 *
1376 * Args: bf - open buffer
1377 * sep - string defining separator characters; <" \t\r\n"> for example.
1378 * opt_tok - optRETURN: allocated copy of token
1379 * opt_n - optRETURN: number of characters in the token
1380 *
1381 * Returns: <eslOK> if a token is found; <*ret_p> points to it,
1382 * and <*opt_n> is its length in chars (> 0). The current
1383 * point is at the start of the next token.
1384 *
1385 * <eslEOF> if the input ends before any token is found.
1386 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The current
1387 * point is at EOF.
1388 *
1389 * <eslEOL> if a line ends before a token is found. (This
1390 * case only arises if *sep does not contain newline.)
1391 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The current
1392 * point is at the next character following the newline.
1393 *
1394 * <bf->mem> may be modified and/or reallocated, if new
1395 * input reads are required to find the entire token.
1396 *
1397 * Throws: <eslEMEM> if an allocation fails.
1398 * Now <*ret_p> is <NULL> and <*opt_n> is 0. The
1399 * current point is undefined.
1400 */
1401 int
1402 esl_buffer_FetchTokenAsStr(ESL_BUFFER *bf, const char *sep, char **opt_tok, esl_pos_t *opt_n)
1403 {
1404 char *tok = NULL;
1405 esl_pos_t anch;
1406 esl_pos_t nc;
1407 int anch_set = FALSE;
1408 int status;
1409
1410 if ( (status = buffer_skipsep(bf, sep)) != eslOK) goto ERROR; /* includes EOF */
1411 /* Now bf->pos is sitting on first char after seps */
1412
1413 if ( ( status = buffer_newline(bf)) != eslOK) goto ERROR; /* includes EOL */
1414
1415 anch = bf->baseoffset + bf->pos;
1416 status = esl_buffer_SetAnchor(bf, anch);
1417 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1418 else if (status != eslOK) { goto ERROR; }
1419 anch_set = TRUE;
1420
1421 if ( (status = buffer_counttok(bf, sep, &nc)) != eslOK) goto ERROR;
1422 /* now we know that pos..pos+nc-1 is a token; pos+nc is the next parser position */
1423
1424 /* copy the token */
1425 ESL_ALLOC(tok, sizeof(char) * (nc+1));
1426 memcpy(tok, bf->mem+bf->pos, nc);
1427 tok[nc] = '\0';
1428 bf->pos += nc;
1429
1430 /* in a Fetch, we can raise the anchor before the new refill */
1431 status = esl_buffer_RaiseAnchor(bf, anch);
1432 if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; }
1433 else if (status != eslOK) { goto ERROR; }
1434 anch_set = FALSE;
1435
1436
1437 if ((status = buffer_skipsep(bf, sep)) != eslOK && status != eslEOF) goto ERROR;
1438 if ((status = buffer_refill(bf, 0)) != eslOK && status != eslEOF) goto ERROR;
1439
1440 if (opt_tok) *opt_tok = tok; else free(tok);
1441 if (opt_n) *opt_n = nc;
1442 return eslOK;
1443
1444 ERROR:
1445 if (tok) free(tok);
1446 if (anch_set) esl_buffer_RaiseAnchor(bf, anch);
1447 if (opt_tok) *opt_tok = NULL;
1448 if (opt_n) *opt_n = 0;
1449 return status;
1450 }
1451 /*----------------- end, token-based parsing --------------------*/
1452
1453
1454
1455 /*****************************************************************
1456 *# 6. Binary (fread-like) parsing
1457 *****************************************************************/
1458
1459 /* Function: esl_buffer_Read()
1460 * Synopsis: Copy a fixed number of bytes from a buffer.
1461 * Incept: SRE, Thu Feb 24 09:25:04 2011 [Janelia]
1462 *
1463 * Purpose: Given an input buffer <bf>, read exactly <nbytes>
1464 * characters into memory <p> provided by the caller.
1465 *
1466 * Suitable for copying known-width scalars from
1467 * binary files, as in:
1468 * \begin{cchunk}
1469 * char c;
1470 * int n;
1471 * esl_buffer_Read(bf, sizeof(char), c);
1472 * esl_buffer_Read(bf, sizeof(int), n);
1473 * \end{cchunk}
1474 *
1475 * Args: bf - open input buffer
1476 * nbytes - number of characters to read
1477 * p - caller-provided memory for storing the copied bytes
1478 *
1479 * Returns: <eslOK> on success; <p> contains exactly <nbytes>
1480 * of data from <bf>, and the point is advanced by <nbytes>.
1481 *
1482 * <eslEOF> if less than <nbytes> characters remain
1483 * in <bf>. Point is unchanged.
1484 *
1485 * Throws: <eslEMEM> if an allocation fails.
1486 * <eslESYS> if an fread() fails mysteriously.
1487 * <eslEINCONCEIVABLE> if internal state of <bf> is corrupted.
1488 */
1489 int
1490 esl_buffer_Read(ESL_BUFFER *bf, size_t nbytes, void *p)
1491 {
1492 int status;
1493
1494 if (bf->n - bf->pos < nbytes)
1495 {
1496 status = buffer_refill(bf, nbytes + bf->pagesize);
1497 if (status == eslEOF) return eslEOF;
1498 else if (status != eslOK) return status; /* EMEM, ESYS, EINCONCEIVABLE */
1499 else if (bf->n-bf->pos < nbytes) return eslEOF;
1500 }
1501
1502 memcpy(p, bf->mem+bf->pos, nbytes);
1503 bf->pos += nbytes;
1504
1505 if ((status = buffer_refill(bf, 0)) != eslOK && status != eslEOF) return status; /* accept EOF, we've already copied what we need */
1506 return eslOK;
1507 }
1508 /*------------ end, binary (fread-like) parsing -----------------*/
1509
1510
1511 /*****************************************************************
1512 * 7. Private (static) functions
1513 *****************************************************************/
1514
1515 /* buffer_create()
1516 * SRE, Sun Jan 23 19:18:40 2011 [UA975 IAD->SFO]
1517 *
1518 * Allocate a new ESL_BUFFER and return it in <*ret_bf>;
1519 * with all fields initialized; return <eslOK>.
1520 *
1521 * On allocation failure, returns <eslEMEM> and <*ret_bf>
1522 * is <NULL>.
1523 */
1524 static int
1525 buffer_create(ESL_BUFFER **ret_bf)
1526 {
1527 ESL_BUFFER *bf = NULL;
1528 int status;
1529
1530 ESL_ALLOC(bf, sizeof(ESL_BUFFER));
1531 bf->mem = NULL;
1532 bf->n = 0;
1533 bf->balloc = 0;
1534 bf->pos = 0;
1535 bf->baseoffset = 0;
1536 bf->anchor = -1;
1537 bf->fp = NULL;
1538 bf->filename = NULL;
1539 bf->cmdline = NULL;
1540 bf->pagesize = eslBUFFER_PAGESIZE;
1541 bf->errmsg[0] = '\0';
1542 bf->mode_is = eslBUFFER_UNSET;
1543
1544 *ret_bf = bf;
1545 return eslOK;
1546
1547 ERROR:
1548 if (bf) free(bf);
1549 *ret_bf = NULL;
1550 return status;
1551 }
1552
1553 /* buffer_init_file_mmap()
1554 * SRE, Sun Jan 23 19:02:34 2011 [UA975 IAD->SFO]
1555 *
1556 * On entry, we've already opened the file;
1557 * bf->fp = open stream for reading
1558 * bf->filename = name of the file
1559 *
1560 * On success, returns eslOK, and *ret_bf has:
1561 * bf->mem mmap'ed file
1562 * bf->n size of the entire file, in bytes
1563 * bf->mode_is eslBUFFER_MMAP
1564 *
1565 * On failure, returns error code, and *ret_bf has:
1566 * bf->errmsg helpful error message
1567 * (all other fields at creation defaults)
1568 *
1569 * On exception, returns error code, and *ret_bf
1570 * is left with all fields at creation defaults.
1571 */
1572 static int
1573 buffer_init_file_mmap(ESL_BUFFER *bf, esl_pos_t filesize)
1574 {
1575 int status;
1576 /* mmap(addr, len, prot, flags, fd, offset */
1577 bf->mem = mmap(0, filesize, PROT_READ, MAP_PRIVATE, fileno(bf->fp), 0);
1578 if (bf->mem == MAP_FAILED) ESL_XEXCEPTION(eslESYS, "mmap()");
1579
1580 bf->n = filesize;
1581 bf->mode_is = eslBUFFER_MMAP;
1582
1583 /* open fp no longer needed - close it. */
1584 fclose(bf->fp);
1585 bf->fp = NULL;
1586 return eslOK;
1587
1588 ERROR:
1589 if (bf->mem != MAP_FAILED) munmap(bf->mem, bf->n);
1590 bf->mem = NULL;
1591 bf->n = 0;
1592 bf->mode_is = eslBUFFER_UNSET;
1593 return status;
1594 }
1595
1596 int
1597 buffer_init_file_slurped(ESL_BUFFER *bf, esl_pos_t filesize)
1598 {
1599 int status;
1600
1601 if (filesize > 0)
1602 {
1603 ESL_ALLOC(bf->mem, sizeof(char) * filesize);
1604 bf->balloc = filesize;
1605
1606 bf->n = fread(bf->mem, sizeof(char), filesize, bf->fp);
1607 if (bf->n < filesize)
1608 ESL_XEXCEPTION(eslESYS, "failed to slurp %s\n", bf->filename);
1609 }
1610 else /* empty file, NULL buffer, 0 length */
1611 {
1612 bf->mem = NULL;
1613 bf->balloc = 0;
1614 bf->n = 0;
1615 }
1616
1617 bf->mode_is = eslBUFFER_ALLFILE;
1618 fclose(bf->fp); /* open fp no longer needed - close it. */
1619 bf->fp = NULL;
1620 return eslOK;
1621
1622 ERROR:
1623 if (bf->mem) { free(bf->mem); bf->mem = NULL; }
1624 return status;
1625 }
1626
1627 int
1628 buffer_init_file_basic(ESL_BUFFER *bf)
1629 {
1630 int status;
1631
1632 ESL_ALLOC(bf->mem, sizeof(char) * bf->pagesize);
1633 bf->balloc = bf->pagesize;
1634
1635 bf->n = fread(bf->mem, sizeof(char), bf->pagesize, bf->fp);
1636 if (bf->n < bf->pagesize && ferror(bf->fp))
1637 ESL_XEXCEPTION(eslESYS, "failed to read first chunk of %s", bf->filename);
1638
1639 bf->mode_is = eslBUFFER_FILE;
1640 return eslOK;
1641
1642 ERROR:
1643 if (bf->mem) { free(bf->mem); bf->mem = NULL; }
1644 return status;
1645 }
1646
1647 /* buffer_refill()
1648 * For current buffer position bf->pos, try to assure that
1649 * we have at least <bf->pagesize> bytes loaded in <bf->mem> to parse.
1650 *
1651 * If new read won't fit (space remaining: balloc-n; read size: memreadsize)
1652 * then make room for it:
1653 * if no anchor: ndel = pos
1654 * else w/ anchor: ndel = anchor; anchor = 0
1655 * n -= ndel bytes are moved
1656 * pos -= ndel
1657 * if (n) move <n> bytes from <ndel> to 0.
1658 * base_offset += ndel
1659 * if (n + memreadsize > balloc) reallocate mem
1660 * fread() a block into position mem+n
1661 * n += memreadsize
1662 *
1663 * For example, suppose we've completely parsed the buffer (pos == n) and we have no
1664 * anchor: then:
1665 * ndel = n
1666 * n = 0 (no bytes are moved)
1667 * pos = 0
1668 * base_offset += n
1669 * fread a new block into mem+0
1670 * n += memreadsize
1671 *
1672 * Returns: <eslOK> on success.
1673 * <eslEOF> if no data remain in buffer nor to be read. Now pos == n.
1674 *
1675 * Throws: <eslEMEM> if an allocation fails.
1676 * <eslESYS> if fread() fails mysteriously.
1677 * <eslEINCONCEIVABLE> if internal state of <bf> is corrupt.
1678 */
1679 static int
1680 buffer_refill(ESL_BUFFER *bf, esl_pos_t nmin)
1681 {
1682 esl_pos_t ndel;
1683 esl_pos_t nread;
1684 int status;
1685
1686 if (! bf->fp || feof(bf->fp)) return ( (bf->pos < bf->n) ? eslOK : eslEOF); /* without an active fp, we have whole buffer in memory; either no-op OK, or EOF */
1687 if (bf->n - bf->pos >= nmin + bf->pagesize) return eslOK; /* if we already have enough data in buffer window, no-op w */
1688
1689 if (bf->pos > bf->n) ESL_EXCEPTION(eslEINCONCEIVABLE, "impossible position for buffer <pos>");
1690
1691 /* Relocation, shift left to conserve memory */
1692 if (bf->balloc - bf->n < bf->pagesize && bf->pos > 0)
1693 {
1694 if (bf->anchor == -1) ndel = bf->pos;
1695 else { ndel = bf->anchor; bf->anchor = 0; }
1696 bf->n -= ndel;
1697 bf->pos -= ndel;
1698 if (bf->n) {
1699 ESL_DASSERT1(( bf->mem != NULL ));
1700 memmove(bf->mem, bf->mem+ndel, bf->n);
1701 }
1702 bf->baseoffset += ndel;
1703 }
1704
1705 if (bf->n + bf->pagesize > bf->balloc)
1706 {
1707 ESL_REALLOC(bf->mem, sizeof(char) * (bf->n + bf->pagesize));
1708 bf->balloc = bf->n + bf->pagesize;
1709 }
1710
1711 nread = fread(bf->mem+bf->n, sizeof(char), bf->pagesize, bf->fp);
1712 if (nread == 0 && !feof(bf->fp) && ferror(bf->fp)) ESL_EXCEPTION(eslESYS, "fread() failure");
1713
1714 bf->n += nread;
1715 if (nread == 0 && bf->pos == bf->n) return eslEOF; else return eslOK;
1716
1717 ERROR:
1718 return status;
1719 }
1720
1721 /* buffer_countline()
1722 * The guts of esl_buffer_GetLine().
1723 *
1724 * Starting from the current buffer position bf->pos, count the number
1725 * of characters to the next newline or EOF. Return the number of
1726 * chars EXCLUSIVE of newline in <*opt_nc>; this is the line length to
1727 * be parsed starting from bf->pos. Return the number of chars
1728 * INCLUSIVE of newline in <*opt_nskip>; this is the amount the caller
1729 * should increment bf->pos by, to position the parser at the start of
1730 * the next line.
1731 *
1732 * This is used in GetLine() and FetchLine*(). They differ in the order
1733 * of calling RaiseAnchor() and buffer_refill(): if we're
1734 * fetching, we don't need to keep the memory of the current
1735 * line in the buffer's window, so we can raise the anchor
1736 * before refilling the buffer, which can save some memory.
1737 *
1738 * If necessary, the buffer is refilled. This relies on the caller having
1739 * already set an anchor at the beginning of the line.
1740 *
1741 * Newlines are defined by esl_memnewline().
1742 *
1743 * Returns: <eslOK> on success.
1744 * <*opt_nc> is >= 0. (0 means an empty line.)
1745 * <*opt_nskip> is >= <*opt_nc>. (Equality means the line ended at EOF.)
1746 *
1747 * <eslEOF> if there's no line (even blank).
1748 * On EOF, <*opt_p> is NULL and <*opt_n> is 0.
1749 *
1750 * Throws: <eslEMEM> if allocation fails.
1751 * <eslESYS> if a system call such as fread() fails unexpectedly.
1752 * <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
1753 */
1754 static int
1755 buffer_countline(ESL_BUFFER *bf, esl_pos_t *opt_nc, esl_pos_t *opt_nskip)
1756 {
1757 esl_pos_t nc; /* line length exclusive of newline */
1758 esl_pos_t nc2; /* tmp nc for a suffix of the current line */
1759 int nterm; /* length of newline; 0..2 */
1760 int status;
1761
1762 if (bf->pos == bf->n) { status = eslEOF; goto ERROR; } /* normal EOF */
1763
1764 nc = 0;
1765 do { // Make sure that a complete input line is loaded in buf, up to a newline or EOF.
1766 if ( nc && bf->mem[bf->pos+nc-1] == '\r') nc--; // see iss#23. If \r was last char, back up so esl_memnewline can see \r\n
1767 if ((status = esl_memnewline(bf->mem + bf->pos + nc, bf->n - bf->pos - nc, &nc2, &nterm)) != eslOK && status != eslEOD) goto ERROR;
1768 nc += nc2;
1769 if (nterm) break; // esl_memnewline found \n or \r\n.
1770 if (( status = buffer_refill(bf, nc)) != eslOK && status != eslEOF) goto ERROR; // only returns EOF if no data left in buf at all (pos==n)
1771 } while (bf->n - bf->pos > nc);
1772
1773 /* EOF check. If we get here with status == eslEOF, nc = nterm = 0,
1774 * then esl_memnewline found no data for a line and buffer_refill returned EOF.
1775 */
1776 if (status == eslEOF && nc == 0 && nterm == 0) goto ERROR;
1777
1778 /* Now the line extends from bf->pos..pos+nc-1 in the buffer window
1779 * The newline itself is position pos+nc..pos+nc+nterm-1 (one or two chars)
1780 * The next line starts at pos+nc+nterm
1781 * We know that everything up to pos+nc+nterm-1 is in the buffer window.
1782 * It's safe to set the current buffer position to pos+nc+nterm, which
1783 * may be bf->n; the next buffer_refill() will do the right thing with it.
1784 */
1785 if (opt_nc) *opt_nc = nc;
1786 if (opt_nskip) *opt_nskip = nc + nterm;
1787 return eslOK;
1788
1789 ERROR: /* including normal EOF */
1790 if (opt_nc) *opt_nc = 0;
1791 if (opt_nskip) *opt_nskip = 0;
1792 return status;
1793 }
1794
1795 /* First chunk of token parsing, shared amongst GetToken(), FetchToken(), FetchTokenAsStr()
1796 * Skip the parser past chars in *sep; return eslEOF if no non-sep char is found.
1797 * Now parser is bf->pos == bf->n, buffer is in EOF state.
1798 * eslOK on success, and bf->pos is on the first nonsep char.
1799 *
1800 * Returns: eslOK or eslEOF
1801 * Throws: eslEMEM, eslESYS, eslEINCONCEIVABLE
1802 */
1803 static int
1804 buffer_skipsep(ESL_BUFFER *bf, const char *sep)
1805 {
1806 int status;
1807
1808 /* skip characters in sep[], or hit EOF. */
1809 do {
1810 for ( ; bf->pos < bf->n; bf->pos++)
1811 if (strchr(sep, bf->mem[bf->pos]) == NULL) goto DONE;
1812 if ( (status = buffer_refill(bf, 0)) != eslOK && status != eslEOF) return status;
1813 } while (bf->n > bf->pos);
1814
1815 DONE:
1816 return (bf->pos == bf->n ? eslEOF : eslOK);
1817 }
1818
1819 /* buffer_skipnewline()
1820 * if bf->pos is on a newline (1 or 2 chars);
1821 * advance bf->pos to next byte after newline and return eslEOL
1822 * else do nothing, and return eslOK.
1823 */
1824 static int
1825 buffer_newline(ESL_BUFFER *bf)
1826 {
1827 esl_pos_t nc = bf->n - bf->pos;
1828 int status;
1829
1830 if (nc == 0)
1831 return eslEOL; /* no newline, but EOF is as good as */
1832 if (nc >= 1 && bf->mem[bf->pos] == '\n')
1833 { bf->pos += 1; return eslEOL; }
1834 if (nc >= 2 && memcmp(bf->mem + bf->pos, "\r\n", 2) == 0)
1835 { bf->pos += 2; return eslEOL; }
1836
1837 status = buffer_refill(bf, 0);
1838 if (status != eslEOF && status != eslOK) return status;
1839
1840 return eslOK;
1841 }
1842
1843 /* bf->pos is sitting on a non-sep, non-newline character, starting
1844 * a token (i.e., the way buffer_skipsep() left us on
1845 * success). Caller has set anchor to be sure this position stays in
1846 * buffer. Count how many nonsep, nonnewline characters there are,
1847 * starting here. Expand bf as needed.
1848 */
1849 static int
1850 buffer_counttok(ESL_BUFFER *bf, const char *sep, esl_pos_t *ret_nc)
1851 {
1852 esl_pos_t nc;
1853 int status;
1854
1855 /* skip chars NOT in sep[]. */
1856 nc = 1;
1857 do {
1858 for ( ; nc < bf->n-bf->pos; nc++)
1859 {
1860 if (strchr(sep, bf->mem[bf->pos+nc]) != NULL) break; /* token ends on any char in sep */
1861 if (bf->mem[bf->pos+nc] == '\n') break; /* token also always ends on a newline */
1862 }
1863 if (nc < bf->n-bf->pos) break; /* token ended in our current buffer */
1864
1865 if ( (status = buffer_refill(bf, nc)) != eslOK && status != eslEOF) goto ERROR;
1866 } while (bf->n - bf->pos > nc);
1867
1868 // check for \r\n newline, but beware, bf->pos+nc can be off edge of bf->mem, if input ends with token.
1869 if (bf->pos+nc < bf->n && bf->mem[bf->pos+nc] == '\n' && bf->mem[bf->pos+nc-1] == '\r') { nc--; }
1870
1871 /* if still in input, bf->mem[bf->pos+nc] now sitting on the first char that's in sep, or a newline char */
1872 *ret_nc = nc;
1873 return eslOK;
1874
1875 ERROR:
1876 *ret_nc = 0;
1877 return status;
1878 }
1879 /*----------------- end, private functions ----------------------*/
1880
1881
1882
1883
1884 /*****************************************************************
1885 * 8. Benchmark
1886 *****************************************************************/
1887 #ifdef eslBUFFER_BENCHMARK
1888
1889 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_benchmark -DeslBUFFER_BENCHMARK esl_buffer.c -leasel -lm
1890 * run: ./esl_buffer_benchmark
1891 */
1892 #include <esl_config.h>
1893
1894 #include <stdio.h>
1895 #include <fcntl.h>
1896 #include <sys/mman.h>
1897 #include <sys/stat.h>
1898
1899 #include "easel.h"
1900 #include "esl_buffer.h"
1901 #include "esl_getopts.h"
1902 #include "esl_stopwatch.h"
1903
1904 static ESL_OPTIONS options[] = {
1905 /* name type default env range togs reqs incomp help docgrp */
1906 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
1907 { "--with-oneread", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "run single slurp times too (<infile> fits in RAM)", 0},
1908 { 0,0,0,0,0,0,0,0,0,0},
1909 };
1910 static char usage[] = "[-options] <infile>";
1911 static char banner[] = "benchmark driver for buffer module";
1912
1913
1914 static void
1915 benchmark_buffer_raw(char *filename, esl_pos_t *counts)
1916 {
1917 ESL_BUFFER *bf = NULL;
1918 char *p;
1919 esl_pos_t nc;
1920 esl_pos_t pos;
1921
1922 esl_buffer_OpenFile(filename, &bf);
1923 while (esl_buffer_Get(bf, &p, &nc) == eslOK)
1924 {
1925 for (pos = 0; pos < nc; pos++)
1926 counts[(int) p[pos]]++;
1927
1928 esl_buffer_Set(bf, p, nc);
1929 }
1930 esl_buffer_Close(bf);
1931 return;
1932 }
1933
1934 static void
1935 benchmark_buffer_lines(char *filename, esl_pos_t *counts)
1936 {
1937 ESL_BUFFER *bf = NULL;
1938 char *p;
1939 esl_pos_t nc;
1940 esl_pos_t pos;
1941
1942 esl_buffer_OpenFile(filename, &bf);
1943 while (esl_buffer_GetLine(bf, &p, &nc) == eslOK)
1944 {
1945 for (pos = 0; pos < nc; pos++)
1946 counts[(int) p[pos]]++;
1947 }
1948 esl_buffer_Close(bf);
1949 return;
1950 }
1951
1952 static void
1953 benchmark_buffer_stream_raw(char *filename, esl_pos_t *counts)
1954 {
1955 FILE *fp = fopen(filename, "rb");
1956 ESL_BUFFER *bf = NULL;
1957 char *p;
1958 esl_pos_t nc;
1959 esl_pos_t pos;
1960
1961 esl_buffer_OpenStream(fp, &bf);
1962 while (esl_buffer_Get(bf, &p, &nc) == eslOK)
1963 {
1964 for (pos = 0; pos < nc; pos++)
1965 counts[(int) p[pos]]++;
1966
1967 esl_buffer_Set(bf, p, nc);
1968 }
1969 esl_buffer_Close(bf);
1970 return;
1971 }
1972
1973 static void
1974 benchmark_buffer_stream_lines(char *filename, esl_pos_t *counts)
1975 {
1976 FILE *fp = fopen(filename, "rb");
1977 ESL_BUFFER *bf = NULL;
1978 char *p;
1979 esl_pos_t nc;
1980 esl_pos_t pos;
1981
1982 esl_buffer_OpenStream(fp, &bf);
1983 while (esl_buffer_GetLine(bf, &p, &nc) == eslOK)
1984 {
1985 for (pos = 0; pos < nc; pos++)
1986 counts[(int) p[pos]]++;
1987 }
1988 esl_buffer_Close(bf);
1989 return;
1990 }
1991
1992 static void
1993 benchmark_buffer_tokens(char *filename, esl_pos_t *counts)
1994 {
1995 FILE *fp = fopen(filename, "rb");
1996 ESL_BUFFER *bf = NULL;
1997 char sep[] = " \t\r\n";
1998 char *tok;
1999 esl_pos_t nc;
2000 esl_pos_t pos;
2001
2002 esl_buffer_OpenStream(fp, &bf);
2003 while (esl_buffer_GetToken(bf, sep, &tok, &nc) == eslOK)
2004 {
2005 for (pos = 0; pos < nc; pos++)
2006 counts[(int) tok[pos]]++;
2007 }
2008 esl_buffer_Close(bf);
2009 return;
2010 }
2011
2012
2013 static void
2014 benchmark_mmap(char *filename, esl_pos_t filesize, esl_pos_t *counts)
2015 {
2016 char *buf = NULL;
2017 int prot = PROT_READ;
2018 int flags = MAP_FILE | MAP_PRIVATE;
2019 int fd = -1;
2020 off_t offset = 0;
2021 esl_pos_t pos;
2022
2023 fd = open(filename, O_RDONLY);
2024 buf = (char *) mmap(0, filesize, prot, flags, fd, offset);
2025 // posix_madvise(buf, len, POSIX_MADV_SEQUENTIAL);
2026 close(fd);
2027
2028 for (pos = 0; pos < filesize; pos++)
2029 counts[(int) buf[pos]]++;
2030
2031 munmap(buf, filesize);
2032 return;
2033 }
2034
2035 static void
2036 benchmark_one_read(char *filename, esl_pos_t filesize, esl_pos_t *counts)
2037 {
2038 int fd = -1;
2039 char *buf = malloc(filesize);
2040 int n;
2041 esl_pos_t pos;
2042
2043 fd = open(filename, O_RDONLY);
2044 if (( n = read(fd, buf, filesize)) != filesize) esl_fatal("bad read()");
2045 close(fd);
2046
2047 for (pos = 0; pos < filesize; pos++)
2048 counts[(int) buf[pos]]++;
2049
2050 free(buf);
2051 return;
2052 }
2053
2054 static void
2055 benchmark_one_fread(char *filename, esl_pos_t filesize, esl_pos_t *counts)
2056 {
2057 FILE *fp = fopen(filename, "rb");
2058 char *buf = malloc(filesize);
2059 size_t n;
2060 esl_pos_t pos;
2061
2062 if ((n = fread(buf, 1, filesize, fp)) != filesize) esl_fatal("bad fread()");
2063 fclose(fp);
2064
2065 for (pos = 0; pos < filesize; pos++)
2066 counts[(int) buf[pos]]++;
2067 free(buf);
2068 return;
2069 }
2070
2071 static void
2072 benchmark_fgets(char *filename, esl_pos_t *counts)
2073 {
2074 FILE *fp = fopen(filename, "rb");
2075 char *buf = malloc(4096);
2076 char *p;
2077
2078 while (fgets(buf, 4096, fp) != NULL)
2079 {
2080 for (p = buf; *p != '\0'; p++)
2081 counts[(int) (*p)]++;
2082 }
2083 fclose(fp);
2084 free(buf);
2085 return;
2086 }
2087
2088 static void
2089 benchmark_strtok(char *filename, esl_pos_t *counts)
2090 {
2091 FILE *fp = fopen(filename, "rb");
2092 char *buf = malloc(8192);
2093 char *tok = NULL;
2094 char *p, *p2;
2095
2096 while (fgets(buf, 8192, fp) != NULL)
2097 {
2098 p = buf;
2099 do {
2100 if ((tok = strtok(p, " \t\r\n")) != NULL)
2101 {
2102 for (p2 = tok; *p2 != '\0'; p2++)
2103 counts[(int) (*p2)]++;
2104 }
2105 p = NULL;
2106 } while (tok);
2107 }
2108 fclose(fp);
2109 free(buf);
2110 return;
2111 }
2112
2113 static void
2114 benchmark_esl_fgets(char *filename, esl_pos_t *counts)
2115 {
2116 FILE *fp = fopen(filename, "rb");
2117 char *buf = NULL;
2118 int n = 0;
2119 char *p;
2120
2121 while (esl_fgets(&buf, &n, fp) == eslOK)
2122 {
2123 for (p = buf; *p != '\0'; p++)
2124 counts[(int) (*p)]++;
2125 }
2126 fclose(fp);
2127 free(buf);
2128 return;
2129 }
2130
2131 int
2132 main(int argc, char **argv)
2133 {
2134 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
2135 ESL_STOPWATCH *w = esl_stopwatch_Create();
2136 char *infile = esl_opt_GetArg(go, 1);
2137 struct stat fstats;
2138 esl_pos_t filesize;
2139 esl_pos_t counts[256];
2140
2141 stat(infile, &fstats);
2142 filesize = fstats.st_size;
2143
2144 /* roughly in fastest->slowest order */
2145 esl_stopwatch_Start(w); benchmark_mmap (infile, filesize, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "mmap(): ");
2146 esl_stopwatch_Start(w); benchmark_buffer_stream_raw (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "ESL_BUFFER (stream, raw): ");
2147 esl_stopwatch_Start(w); benchmark_buffer_raw (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "ESL_BUFFER (mmap, raw): ");
2148 if (esl_opt_GetBoolean(go, "--with-oneread")) {
2149 esl_stopwatch_Start(w); benchmark_one_read (infile, filesize, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "one read(): ");
2150 esl_stopwatch_Start(w); benchmark_one_fread (infile, filesize, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "one fread(): ");
2151 }
2152 esl_stopwatch_Start(w); benchmark_fgets (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "fgets(): ");
2153 esl_stopwatch_Start(w); benchmark_esl_fgets (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "esl_fgets(): ");
2154 esl_stopwatch_Start(w); benchmark_buffer_lines (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "ESL_BUFFER (mmap, lines): ");
2155 esl_stopwatch_Start(w); benchmark_buffer_stream_lines(infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "ESL_BUFFER (stream, lines): ");
2156 esl_stopwatch_Start(w); benchmark_strtok (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "strtok(): ");
2157 esl_stopwatch_Start(w); benchmark_buffer_tokens (infile, counts); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, "ESL_BUFFER (stream, tokens): ");
2158
2159 esl_stopwatch_Destroy(w);
2160 esl_getopts_Destroy(go);
2161 return 0;
2162 }
2163
2164 #endif /*eslBUFFER_BENCHMARK*/
2165 /*----------------- end, benchmark driver -----------------------*/
2166
2167
2168
2169
2170
2171 /*****************************************************************
2172 * 9. Unit tests
2173 *****************************************************************/
2174 #ifdef eslBUFFER_TESTDRIVE
2175
2176 #include "esl_random.h"
2177 #include <ctype.h>
2178
2179 /* A variant of esl_buffer_OpenFile() that lets us specify
2180 * whether we want to slurp, mmap, or basic, using
2181 * eslBUFFER_ALLFILE, eslBUFFER_MMAP, eslBUFFER_FILE flags.
2182 * We use this to force code coverage of the different
2183 * buffer_init_file_*() functions.
2184 * For example, the default unit test driver generates a
2185 * test file of ~3 MB, which is always slurped and never
2186 * mmap()'ed; if we want to test mmap() we have to force it.
2187 */
2188 static int
2189 buffer_OpenFileAs(const char *filename, enum esl_buffer_mode_e mode_is, ESL_BUFFER **ret_bf)
2190 {
2191 char msg[] = "buffer_OpenFileAs() failed";
2192 ESL_BUFFER *bf = NULL;
2193 #ifdef _POSIX_VERSION
2194 struct stat fileinfo;
2195 #endif
2196 esl_pos_t filesize = -1;
2197
2198 if (buffer_create(&bf) != eslOK) esl_fatal(msg);
2199 if ((bf->fp = fopen(filename, "rb")) == NULL) esl_fatal(msg);
2200 if (esl_strdup(filename, -1, &(bf->filename)) != eslOK) esl_fatal(msg);
2201
2202 #ifdef _POSIX_VERSION
2203 if (fstat(fileno(bf->fp), &fileinfo) == -1) esl_fatal(msg);
2204 filesize = fileinfo.st_size;
2205 bf->pagesize = fileinfo.st_blksize;
2206 if (bf->pagesize < 512) bf->pagesize = 512;
2207 if (bf->pagesize > 4194304) bf->pagesize = 4194304;
2208 #endif
2209
2210 switch (mode_is) {
2211 case eslBUFFER_ALLFILE: if (buffer_init_file_slurped(bf, filesize) != eslOK) esl_fatal(msg); break;
2212 case eslBUFFER_MMAP: if (buffer_init_file_mmap (bf, filesize) != eslOK) esl_fatal(msg); break;
2213 case eslBUFFER_FILE: if (buffer_init_file_basic (bf) != eslOK) esl_fatal(msg); break;
2214 default: esl_fatal(msg);
2215 }
2216 *ret_bf = bf;
2217 return eslOK;
2218 }
2219
2220
2221
2222
2223 /* Test lines:
2224 * long: \s{0,1}[<line#> _{0,5000} <line#>]\s{0,1}\r?\n (line length > pagesize)
2225 * short: \s{0,1}[<line#> _{0,60} <line#>]\s{0,1}\r?\n (typical text file lines)
2226 * empty: \s{0,1}\r?\n (parser shouldn't lose track of blank lines)
2227 * Final line in file does not necessarily end in newline.
2228 */
2229 static void
2230 create_testfile_lines(ESL_RANDOMNESS *r, char *tmpfile, int nlines)
2231 {
2232 char msg[] = "create_testfile_lines() failed";
2233 FILE *fp = NULL;
2234 double fq_leadspace = 0.2;
2235 double fq_longline = 0.1;
2236 double fq_empty = 0.2;
2237 double fq_dos = 0.5;
2238 double fq_finalnewline = 0.5;
2239 int longxnum = 5000;
2240 int shortxnum = 60;
2241 double roll;
2242 int i, n;
2243
2244 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2245
2246 for (i = 0; i < nlines; i++)
2247 {
2248 if (esl_random(r) < fq_leadspace) fputc(' ', fp);
2249
2250 roll = esl_random(r);
2251 if (roll < fq_empty) {
2252 if (esl_random(r) < fq_dos) fputs("\r\n", fp); else fputc('\n', fp);
2253 continue;
2254 }
2255
2256 if (roll < fq_empty + fq_longline) { n = esl_rnd_Roll(r, longxnum+1); }
2257 else { n = esl_rnd_Roll(r, shortxnum+1); }
2258
2259 fprintf(fp, "[%d %*s %d]", i+1, n, " ", i+1);
2260
2261 if (esl_random(r) < fq_leadspace) fputc(' ', fp);
2262 if (i < nlines-1 || esl_random(r) < fq_finalnewline) {
2263 if (esl_random(r) < fq_dos) fputs("\r\n", fp); else fputc('\n', fp);
2264 }
2265 }
2266 fclose(fp);
2267 }
2268
2269 static void
2270 utest_compare_line(char *p, esl_pos_t n, int nline_expected)
2271 {
2272 const char msg[] = "line input fails to match expected";
2273 int32_t which = 0;
2274 int nc;
2275
2276 if (esl_memspn(p, n, " \t\r\n") == n) return; /* blank test lines */
2277
2278 if (n && *p == ' ') { p++; n--; }
2279 if (n && *p == '[') { p++; n--; } else esl_fatal(msg);
2280
2281 if (! isdigit(*p)) esl_fatal(msg);
2282 if (esl_mem_strtoi32(p, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2283 if (which != nline_expected) esl_fatal(msg);
2284 p += nc; n -= nc;
2285
2286 while (n && isspace(*p)) { p++; n--; } if (!n) esl_fatal(msg);
2287 if (! isdigit(*p)) esl_fatal(msg);
2288 if (esl_mem_strtoi32(p, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2289 if (which != nline_expected) esl_fatal(msg);
2290 p += nc; n -= nc;
2291
2292 if (n && *p == ']') { p++; n--; } else esl_fatal(msg);
2293 if (n && *p == ' ') { p++; n--; }
2294 if (n != 0) esl_fatal(msg);
2295 }
2296
2297 static int
2298 utest_whichline(char *p, esl_pos_t n)
2299 {
2300 char msg[] = "utest_whichline() failed";
2301 int which;
2302
2303 if (esl_memspn(p, n, " \t\r\n") == n) return -1;
2304 while (n && isspace(*p)) { p++; n--; }
2305 if (n && *p == '[') { p++; n--; } else esl_fatal(msg);
2306 if (esl_mem_strtoi32(p, n, 10, NULL, &which) != eslOK) esl_fatal(msg);
2307 return which;
2308 }
2309
2310 static void
2311 utest_SetOffset(const char *tmpfile, int nlines_expected)
2312 {
2313 char msg[] = "utest_Position() failed";
2314 FILE *fp;
2315 ESL_BUFFER *bf;
2316 char *p;
2317 esl_pos_t n;
2318 esl_pos_t thisoffset;
2319 esl_pos_t testoffset1 = -1;
2320 esl_pos_t testoffset2 = -1;
2321 int testline1 = -1;
2322 int testline2 = -2;
2323 int thisline;
2324 #ifdef HAVE_GZIP
2325 char gzipfile[32];
2326 char cmd[256];
2327 #endif
2328
2329 /* Find offsets of lines ~2000 and ~5000; we'll use these positions as tests. */
2330 if (nlines_expected <= 8000) return; /* require at least 8000 lines to do this test */
2331 if (esl_buffer_Open(tmpfile, NULL, &bf) != eslOK) esl_fatal(msg);
2332 testline1 = -1;
2333 thisoffset = esl_buffer_GetOffset(bf);
2334 while (esl_buffer_GetLine(bf, &p, &n) == eslOK)
2335 {
2336 if ((thisline = utest_whichline(p, n)) == -1) continue;
2337 if (testline1 == -1 && thisline >= 2000) {
2338 testline1 = thisline; testoffset1 = thisoffset;
2339 }
2340 if (thisline >= 5000) {
2341 testline2 = thisline; testoffset2 = thisoffset;
2342 break;
2343 }
2344 thisoffset = esl_buffer_GetOffset(bf);
2345 }
2346 esl_buffer_Close(bf);
2347
2348 /* Now we're going to walk through SetOffset()'s various cases;
2349 * we'll also exercise Open() while we're at it.
2350 */
2351 /* Test 1. We have the entire file in bf->mem and SetOffset() is trivial.
2352 * Since a file is either slurped or mmap'ed, this is what we expect.
2353 */
2354 if ( esl_buffer_Open(tmpfile, NULL, &bf) != eslOK) esl_fatal(msg);
2355 if ( esl_buffer_SetOffset(bf, testoffset2) != eslOK) esl_fatal(msg);
2356 if ( esl_buffer_GetLine(bf, &p, &n) != eslOK) esl_fatal(msg);
2357 utest_compare_line(p, n, testline2);
2358 esl_buffer_Close(bf);
2359
2360 /* All subsequent tests are for streams. */
2361 /* Test 2. Offset *forward* to line ~2000 (testline1), and read it.
2362 * Anchor.
2363 * Offset forward again to line ~5000 (testline2), read it.
2364 * Anchor (should no-op; first anchor is already in effect)
2365 * Offset backward to testline1, read it.
2366 * Try to offset back to 0; this should throw eslEINVAL.
2367 * (also exercise gzip reading, if we can)
2368 */
2369 #if defined HAVE_GZIP
2370 snprintf(gzipfile, 32, "%s.gz", tmpfile);
2371 snprintf(cmd, 256, "gzip -c %s 2>/dev/null > %s", tmpfile, gzipfile);
2372 if (system(cmd) != 0) esl_fatal(msg);
2373 if (esl_buffer_Open(gzipfile, NULL, &bf) != eslOK) esl_fatal(msg);
2374 fp = NULL;
2375 #else
2376 if ( (fp = fopen(tmpfile, "r")) == NULL) esl_fatal(msg);
2377 if (esl_buffer_OpenStream(fp, &bf) != eslOK) esl_fatal(msg);
2378 #endif
2379 if (esl_buffer_SetOffset(bf, testoffset1) != eslOK) esl_fatal(msg);
2380 if (esl_buffer_GetLine(bf, &p, &n) != eslOK) esl_fatal(msg);
2381 utest_compare_line(p, n, testline1);
2382
2383 if (esl_buffer_SetAnchor(bf, testoffset1) != eslOK) esl_fatal(msg);
2384 if (esl_buffer_SetOffset(bf, testoffset2) != eslOK) esl_fatal(msg);
2385 if (esl_buffer_GetLine(bf, &p, &n) != eslOK) esl_fatal(msg);
2386 utest_compare_line(p, n, testline2);
2387
2388 if (esl_buffer_SetAnchor(bf, testoffset2) != eslOK) esl_fatal(msg);
2389 if (esl_buffer_RaiseAnchor(bf, testoffset2) != eslOK) esl_fatal(msg);
2390 if (esl_buffer_SetOffset(bf, testoffset1) != eslOK) esl_fatal(msg);
2391 if (esl_buffer_GetLine(bf, &p, &n) != eslOK) esl_fatal(msg);
2392 utest_compare_line(p, n, testline1);
2393
2394 esl_exception_SetHandler(&esl_nonfatal_handler);
2395 if (esl_buffer_SetOffset(bf, 0) != eslEINVAL) esl_fatal(msg);
2396 esl_exception_ResetDefaultHandler();
2397
2398 esl_buffer_Close(bf);
2399 if (fp) fclose(fp);
2400
2401
2402 /* test 3. The remaining case is using fseeko(), which
2403 * can only happen on a eslBUFFER_FILE opened in basic mode.
2404 */
2405 #ifdef _POSIX_VERSION
2406 if (buffer_OpenFileAs(tmpfile, eslBUFFER_FILE, &bf) != eslOK) esl_fatal(msg);
2407 if (esl_buffer_SetOffset(bf, testoffset2) != eslOK) esl_fatal(msg);
2408 if (esl_buffer_GetLine(bf, &p, &n) != eslOK) esl_fatal(msg);
2409 utest_compare_line(p, n, testline2);
2410
2411 if (esl_buffer_SetOffset(bf, testoffset1) != eslOK) esl_fatal(msg);
2412 if (esl_buffer_GetLine(bf, &p, &n) != eslOK) esl_fatal(msg);
2413 utest_compare_line(p, n, testline1);
2414 esl_buffer_Close(bf);
2415 #endif /*_POSIX_VERSION*/
2416
2417 #if defined HAVE_GZIP
2418 remove(gzipfile);
2419 #endif
2420
2421 }
2422
2423 static void
2424 utest_Get(ESL_BUFFER *bf, int nlines_expected)
2425 {
2426 const char msg[] = "utest_Get() failed";
2427 char *p = NULL;
2428 esl_pos_t n = 0;
2429 int nlines = 0;
2430 char line[8192];
2431 int lpos = 0;
2432 esl_pos_t i;
2433 int status;
2434
2435 while ( (status = esl_buffer_Get(bf, &p, &n)) == eslOK)
2436 {
2437 for (i = 0; i < n; i++)
2438 {
2439 if (p[i] == '\n')
2440 {
2441 nlines++;
2442 if (lpos && line[lpos-1] == '\r') lpos--;
2443 utest_compare_line(line, lpos, nlines);
2444 lpos = 0;
2445 i++;
2446 break;
2447 }
2448 else
2449 line[lpos++] = p[i];
2450 }
2451 esl_buffer_Set(bf, p, i);
2452 }
2453 if (lpos) { nlines++; utest_compare_line(line, lpos, nlines); }
2454 if (status != eslEOF) esl_fatal(msg);
2455 if (nlines != nlines_expected) esl_fatal(msg);
2456 }
2457
2458 static void
2459 utest_GetLine(ESL_BUFFER *bf, int nlines_expected)
2460 {
2461 const char msg[] = "utest_GetLine() failed";
2462 char *p = NULL;
2463 esl_pos_t n = 0;
2464 int nlines = 0;
2465 int status;
2466
2467 while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK)
2468 {
2469 nlines++;
2470 utest_compare_line(p, n, nlines);
2471 }
2472 if (status != eslEOF) esl_fatal(msg);
2473 if (nlines != nlines_expected) esl_fatal(msg);
2474 return;
2475 }
2476
2477 static void
2478 utest_FetchLine(ESL_BUFFER *bf, int nlines_expected)
2479 {
2480 const char msg[] = "utest_FetchLine() failed";
2481 char *p = NULL;
2482 esl_pos_t n = 0;
2483 int nlines = 0;
2484 int status;
2485
2486 while ( (status = esl_buffer_FetchLine(bf, &p, &n)) == eslOK)
2487 {
2488 nlines++;
2489 utest_compare_line(p, n, nlines);
2490 free(p);
2491 }
2492 if (status != eslEOF) esl_fatal(msg);
2493 if (nlines != nlines_expected) esl_fatal(msg);
2494 return;
2495 }
2496
2497 static void
2498 utest_FetchLineAsStr(ESL_BUFFER *bf, int nlines_expected)
2499 {
2500 const char msg[] = "utest_FetchLineAsStr() failed";
2501 char *p = NULL;
2502 esl_pos_t n = 0;
2503 int nlines = 0;
2504 int status;
2505
2506 while ( (status = esl_buffer_FetchLineAsStr(bf, &p, &n)) == eslOK)
2507 {
2508 nlines++;
2509 utest_compare_line(p, n, nlines);
2510 if (p[n] != '\0') esl_fatal(msg);
2511 free(p);
2512 }
2513 if (status != eslEOF) esl_fatal(msg);
2514 if (nlines != nlines_expected) esl_fatal(msg);
2515 return;
2516 }
2517
2518
2519 static void
2520 utest_GetToken(ESL_BUFFER *bf, int nlines_expected)
2521 {
2522 char msg[] = "utest_GetToken() failed";
2523 const char sep[] = " \t"; /* without newline chars \r\n, GetToken() will return EOL when it reaches end of line. *Next* GetToken() succeeds. */
2524 int nlines = 0;
2525 char *tok;
2526 int which;
2527 int nc;
2528 esl_pos_t n;
2529 int status;
2530
2531 while ((status = esl_buffer_GetToken(bf, sep, &tok, &n)) == eslOK || status == eslEOL) /* EOL needed for blank lines */
2532 { /* each line has two tokens: "[%d" and "%d]" */
2533 nlines++;
2534 if (status == eslEOL) continue;
2535
2536 if (*tok == '[') { tok++; n--; } else esl_fatal(msg);
2537 if (! isdigit(*tok)) esl_fatal(msg);
2538 if (esl_mem_strtoi32(tok, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2539 if (nc != n) esl_fatal(msg);
2540 if (which != nlines) esl_fatal(msg);
2541
2542 if (esl_buffer_GetToken(bf, sep, &tok, &n) != eslOK) esl_fatal(msg);
2543 if (! isdigit(*tok)) esl_fatal(msg);
2544 if (esl_mem_strtoi32(tok, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2545 if (nc != n-1) esl_fatal(msg);
2546 if (which != nlines) esl_fatal(msg);
2547 if (*(tok+nc) != ']') esl_fatal(msg);
2548
2549 if ( (status = esl_buffer_GetToken(bf, sep, &tok, &n)) != eslEOL && status != eslEOF) esl_fatal(msg);
2550 if (tok != NULL || n != 0) esl_fatal(msg);
2551 }
2552 if (status != eslEOF) esl_fatal(msg);
2553 if (nlines != nlines_expected) esl_fatal(msg);
2554 return;
2555 }
2556
2557
2558 static void
2559 utest_GetTokenWrapped(ESL_BUFFER *bf, int nlines_expected)
2560 {
2561 char msg[] = "utest_GetTokenWrapped() failed";
2562 const char sep[] = " \t\r\n"; /* with newline chars \r\n, GetToken() wraps to next line to find token. */
2563 int nlines = 0;
2564 char *tok;
2565 int which;
2566 int nc;
2567 esl_pos_t n;
2568 int status;
2569
2570 while ((status = esl_buffer_GetToken(bf, sep, &tok, &n)) == eslOK)
2571 { /* each line has two tokens: "[%d" and "%d]" */
2572 nlines++;
2573
2574 if (*tok == '[') { tok++; n--; } else esl_fatal(msg);
2575 if (! isdigit(*tok)) esl_fatal(msg);
2576 if (esl_mem_strtoi32(tok, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2577 if (nc != n) esl_fatal(msg);
2578 if (which > nlines) nlines = which; /* can skip lines that are all newline */
2579 else if (which < nlines) esl_fatal(msg);
2580
2581 if (esl_buffer_GetToken(bf, sep, &tok, &n) != eslOK) esl_fatal(msg);
2582 if (! isdigit(*tok)) esl_fatal(msg);
2583 if (esl_mem_strtoi32(tok, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2584 if (nc != n-1) esl_fatal(msg);
2585 if (which != nlines) esl_fatal(msg);
2586 if (*(tok+nc) != ']') esl_fatal(msg);
2587 }
2588 if (status != eslEOF) esl_fatal(msg);
2589 if (nlines > nlines_expected) esl_fatal(msg); /* probably can't happen. can't check for equality though - last line(s) could be blank */
2590 return;
2591 }
2592
2593 static void
2594 utest_FetchToken(ESL_BUFFER *bf, int nlines_expected)
2595 {
2596 char msg[] = "utest_FetchToken() failed";
2597 const char sep[] = " \t";
2598 int nlines = 0;
2599 char *tok;
2600 int which;
2601 int nc;
2602 esl_pos_t n;
2603 int status;
2604
2605 while ((status = esl_buffer_FetchToken(bf, sep, &tok, &n)) == eslOK || status == eslEOL) /* EOL needed for blank lines */
2606 { /* each line has two tokens: "[%d" and "%d]" */
2607 nlines++;
2608 if (status == eslEOL) { if (tok != NULL) esl_fatal(msg); else continue; }
2609
2610 if (*tok != '[') esl_fatal(msg);
2611 if (! isdigit(*(tok+1))) esl_fatal(msg);
2612 if (esl_mem_strtoi32(tok+1, n-1, 10, &nc, &which) != eslOK) esl_fatal(msg);
2613 if (nc != n-1) esl_fatal(msg);
2614 if (which != nlines) esl_fatal(msg);
2615 free(tok);
2616
2617 if (esl_buffer_FetchToken(bf, sep, &tok, &n) != eslOK) esl_fatal(msg);
2618 if (! isdigit(*tok)) esl_fatal(msg);
2619 if (esl_mem_strtoi32(tok, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2620 if (nc != n-1) esl_fatal(msg);
2621 if (which != nlines) esl_fatal(msg);
2622 if (*(tok+nc) != ']') esl_fatal(msg);
2623 free(tok);
2624
2625 if ( (status = esl_buffer_FetchToken(bf, sep, &tok, &n)) != eslEOL && status != eslEOF) esl_fatal(msg);
2626 if (tok != NULL || n != 0) esl_fatal(msg);
2627 }
2628 if (status != eslEOF) esl_fatal(msg);
2629 if (nlines != nlines_expected) esl_fatal(msg);
2630 return;
2631 }
2632
2633
2634 static void
2635 utest_FetchTokenAsStrWrapped(ESL_BUFFER *bf, int nlines_expected)
2636 {
2637 char msg[] = "utest_FetchTokenAsStrWrapped() failed";
2638 const char sep[] = " \t\r\n";
2639 int nlines = 0;
2640 char *tok;
2641 int which;
2642 int nc;
2643 esl_pos_t n;
2644 int status;
2645
2646 while ((status = esl_buffer_FetchTokenAsStr(bf, sep, &tok, &n)) == eslOK)
2647 { /* each line has two tokens: "[%d" and "%d]" */
2648 nlines++;
2649
2650 if (strlen(tok) != n) esl_fatal(msg);
2651 if (*tok != '[') esl_fatal(msg);
2652 if (! isdigit(*(tok+1))) esl_fatal(msg);
2653 if (esl_mem_strtoi32(tok+1, n-1, 10, &nc, &which) != eslOK) esl_fatal(msg);
2654 if (nc != n-1) esl_fatal(msg);
2655 if (which > nlines) nlines = which; /* can skip lines that are all newline */
2656 else if (which < nlines) esl_fatal(msg);
2657 free(tok);
2658
2659 if (esl_buffer_FetchTokenAsStr(bf, sep, &tok, &n) != eslOK) esl_fatal(msg);
2660 if (strlen(tok) != n) esl_fatal(msg);
2661 if (! isdigit(*tok)) esl_fatal(msg);
2662 if (esl_mem_strtoi32(tok, n, 10, &nc, &which) != eslOK) esl_fatal(msg);
2663 if (nc != n-1) esl_fatal(msg);
2664 if (which != nlines) esl_fatal(msg);
2665 if (*(tok+nc) != ']') esl_fatal(msg);
2666 free(tok);
2667 }
2668 if (status != eslEOF) esl_fatal(msg);
2669 if (nlines > nlines_expected) esl_fatal(msg); /* probably can't happen. can't check for equality though - last line(s) could be blank */
2670 return;
2671 }
2672
2673 static void
2674 utest_Read(void)
2675 {
2676 char msg[] = "utest_Read() failed";
2677 char tmpfile[32] = "esltmpXXXXXX";
2678 int32_t ntotal = 1000000;
2679 int32_t testi = 456789; /* arbitrary */
2680 esl_pos_t testoffset = testi * sizeof(int32_t);
2681 int32_t i, val;
2682 FILE *fp;
2683 ESL_BUFFER *bf;
2684
2685 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2686 for (i = 0; i < 1000000; i++)
2687 fwrite(&i, sizeof(int32_t), 1, fp);
2688 fclose(fp);
2689
2690 if (esl_buffer_OpenFile (tmpfile, &bf) != eslOK) esl_fatal(msg);
2691 if (esl_buffer_SetOffset(bf, testoffset) != eslOK) esl_fatal(msg);
2692 for (i = testi; i < ntotal; i++)
2693 {
2694 if (esl_buffer_Read(bf, sizeof(int32_t), &val) != eslOK) esl_fatal(msg);
2695 if (val != i) esl_fatal(msg);
2696 }
2697 if (esl_buffer_Read(bf, sizeof(int32_t), &val) != eslEOF) esl_fatal(msg);
2698 esl_buffer_Close(bf);
2699
2700 remove(tmpfile);
2701 }
2702
2703
2704 static void
2705 utest_OpenFile(const char *tmpfile, int nlines)
2706 {
2707 char msg[] = "utest_OpenFile failed";
2708 ESL_BUFFER *bf;
2709
2710 /* Normal errors */
2711 if (esl_buffer_OpenFile("esltmpXYZXYZXYZ", &bf) != eslENOTFOUND || bf == NULL) esl_fatal(msg); else esl_buffer_Close(bf);
2712 }
2713
2714 static void
2715 utest_OpenStream(const char *tmpfile, int nlines)
2716 {
2717 char msg[] = "utest_OpenStream failed";
2718 ESL_BUFFER *bf;
2719
2720 /* Exceptions */
2721 esl_exception_SetHandler(&esl_nonfatal_handler);
2722 if (esl_buffer_OpenStream(NULL, &bf) != eslEINVAL) esl_fatal(msg); else esl_buffer_Close(bf);
2723 esl_exception_ResetDefaultHandler();
2724 }
2725
2726 static void
2727 utest_OpenPipe(const char *tmpfile, int nlines)
2728 {
2729 ESL_BUFFER *bf;
2730 char msg[] = "utest_OpenPipe failed";
2731 char goodcmd[] = "cat %s 2>/dev/null";
2732 char badcmd[] = "./esltmpXYZXYZXYZ %s 2>/dev/null";
2733
2734 /* Normal errors */
2735 if (esl_buffer_OpenPipe("esltmpXYZXYZXYZ", goodcmd, &bf) != eslENOTFOUND || bf == NULL) esl_fatal(msg); else esl_buffer_Close(bf);
2736 if (esl_buffer_OpenPipe(tmpfile, badcmd, &bf) != eslFAIL || bf == NULL) esl_fatal(msg); else esl_buffer_Close(bf);
2737 }
2738
2739
2740 /* utest_halfnewline()
2741 * Tests for issue #23: esl_buffer hangs when input ends in \r
2742 * [xref SRE:H5/62]
2743 */
2744 static void alarm_handler(int signum) { esl_fatal("utest_halfnewline() timed out and failed"); }
2745
2746 static void
2747 utest_halfnewline(void)
2748 {
2749 char msg[] = "utest_halfnewline() failed";
2750 ESL_BUFFER *bf = NULL;
2751 char s[] = "xxx\r"; // bug manifested when \r is the last char of a file.
2752 char *p = NULL;
2753 esl_pos_t n = 0;
2754 int status;
2755
2756 signal(SIGALRM, alarm_handler); // the bug is an infinite loop in esl_buffer_GetLine(), so we use an alarm signal to trap it.
2757 alarm(1); // this utest will self destruct in one second...
2758
2759 if ( (status = esl_buffer_OpenMem(s, strlen(s), &bf)) != eslOK) esl_fatal(msg);
2760 if ( (status = esl_buffer_GetLine(bf, &p, &n)) != eslOK) esl_fatal(msg);
2761 if ( n != strlen(s)) esl_fatal(msg);
2762 if ( strncmp(p, s, n) != 0) esl_fatal(msg); // a lone \r is a char, not a newline, per current esl_memnewline() spec
2763 if ( (status = esl_buffer_GetLine(bf, &p, &n)) != eslEOF) esl_fatal(msg); // (perhaps that should change)
2764 if ( n != 0) esl_fatal(msg);
2765 if ( p != NULL) esl_fatal(msg);
2766
2767 esl_buffer_Close(bf);
2768 alarm(0); // removes self-destruct alarm
2769 signal(SIGALRM, SIG_DFL); // deletes self-destruct handler
2770 return;
2771 }
2772
2773
2774
2775 #endif /* eslBUFFER_TESTDRIVE */
2776
2777 /*****************************************************************
2778 * 10. Test driver
2779 *****************************************************************/
2780
2781 #ifdef eslBUFFER_TESTDRIVE
2782 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_utest -DeslBUFFER_TESTDRIVE esl_buffer.c -leasel -lm
2783 * (gcov): gcc -g -Wall -fprofile-arcs -ftest-coverage -I. -L. -o esl_buffer_utest -DeslBUFFER_TESTDRIVE esl_buffer.c -leasel -lm
2784 * run: ./esl_buffer_utest
2785 */
2786 #include <esl_config.h>
2787
2788 #include <stdio.h>
2789
2790 #include "easel.h"
2791 #include "esl_buffer.h"
2792 #include "esl_getopts.h"
2793 #include "esl_random.h"
2794
2795 static ESL_OPTIONS options[] = {
2796 /* name type default env range togs reqs incomp help docgrp */
2797 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
2798 {"-n", eslARG_INT, "10000", NULL, NULL, NULL, NULL, NULL, "set number of lines in line-based tests to <n>", 0},
2799 {"-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
2800 {"-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show verbose commentary/output", 0},
2801 { 0,0,0,0,0,0,0,0,0,0},
2802 };
2803 static char usage[] = "[-options]";
2804 static char banner[] = "test driver for buffer module";
2805
2806 int
2807 main(int argc, char **argv)
2808 {
2809 char msg[] = "esl_buffer unit test driver failed";
2810 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
2811 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
2812 ESL_BUFFER *bf = NULL;
2813 ESL_BUFFER *bftmp = NULL;
2814 FILE *fp = NULL;
2815 int be_verbose = esl_opt_GetBoolean(go, "-v");
2816 int nlines = esl_opt_GetInteger(go, "-n");
2817 char tmpfile[32] = "esltmpXXXXXX";
2818 char cmdfmt[] = "cat %s 2>/dev/null";
2819 int bufidx, nbuftypes;
2820 int testidx, ntesttypes;
2821 int status;
2822
2823 create_testfile_lines(r, tmpfile, nlines);
2824 if (be_verbose) printf("created file %s; rng seed %" PRIu32 "\n", tmpfile, esl_randomness_GetSeed(r));
2825
2826 utest_OpenFile (tmpfile, nlines);
2827 utest_OpenStream(tmpfile, nlines);
2828 utest_OpenPipe (tmpfile, nlines);
2829
2830 utest_SetOffset (tmpfile, nlines);
2831 utest_Read();
2832
2833 utest_halfnewline();
2834
2835 nbuftypes = 7;
2836 ntesttypes = 8;
2837 for (bufidx = 0; bufidx < nbuftypes; bufidx++)
2838 for (testidx = 0; testidx < ntesttypes; testidx++)
2839 {
2840 switch (bufidx) {
2841 case 0: if (esl_buffer_OpenFile (tmpfile, &bf) != eslOK) esl_fatal(msg); break;
2842 case 1: if ( buffer_OpenFileAs(tmpfile, eslBUFFER_ALLFILE, &bf) != eslOK) esl_fatal(msg); break;
2843 case 2: if ( buffer_OpenFileAs(tmpfile, eslBUFFER_MMAP, &bf) != eslOK) esl_fatal(msg); break;
2844 case 3: if ( buffer_OpenFileAs(tmpfile, eslBUFFER_FILE, &bf) != eslOK) esl_fatal(msg); break;
2845 case 4:
2846 if ((fp = fopen(tmpfile, "rb")) == NULL) esl_fatal(msg);
2847 if (esl_buffer_OpenStream(fp, &bf) != eslOK) esl_fatal(msg);
2848 break;
2849 case 5:
2850 if (esl_buffer_OpenPipe(tmpfile, cmdfmt, &bf) != eslOK) esl_fatal(msg);
2851 break;
2852 case 6:
2853 if (esl_buffer_OpenFile(tmpfile, &bftmp) != eslOK) esl_fatal(msg);
2854 if (esl_buffer_SetAnchor(bftmp, 0) != eslOK) esl_fatal(msg);
2855 while ( (status = esl_buffer_GetLine(bftmp, NULL, NULL)) == eslOK); /*empty loop, do nothing*/
2856 if (status != eslEOF) esl_fatal(msg);
2857 /* now bftmp->mem is a slurped file */
2858 if (esl_buffer_OpenMem(bftmp->mem, bftmp->n, &bf) != eslOK) esl_fatal(msg);
2859 break;
2860 default: esl_fatal(msg);
2861 }
2862
2863 switch (testidx) {
2864 case 0: utest_Get (bf, nlines); break;
2865 case 1: utest_GetLine (bf, nlines); break;
2866 case 2: utest_FetchLine (bf, nlines); break;
2867 case 3: utest_FetchLineAsStr (bf, nlines); break;
2868 case 4: utest_GetToken (bf, nlines); break;
2869 case 5: utest_GetTokenWrapped(bf, nlines); break;
2870 case 6: utest_FetchToken (bf, nlines); break;
2871 case 7: utest_FetchTokenAsStrWrapped(bf, nlines); break;
2872 default: esl_fatal(msg);
2873 }
2874
2875 //printf("allocation: %" PRId64 "\n", bf->balloc);
2876
2877 esl_buffer_Close(bf); bf = NULL;
2878 if (fp) { fclose(fp); fp = NULL; }
2879 if (bftmp) { esl_buffer_Close(bftmp); bftmp = NULL; }
2880 }
2881
2882 esl_randomness_Destroy(r);
2883 esl_getopts_Destroy(go);
2884 remove(tmpfile);
2885 return 0;
2886 }
2887 #endif /* eslBUFFER_TESTDRIVE */
2888
2889
2890 /*****************************************************************
2891 * 11. Examples.
2892 *****************************************************************/
2893
2894 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_example -DeslBUFFER_EXAMPLE esl_buffer.c -leasel -lm
2895 * run: ./esl_buffer_example <file>
2896 */
2897 #ifdef eslBUFFER_EXAMPLE
2898 /*::cexcerpt::buffer_example::begin::*/
2899 #include "easel.h"
2900 #include "esl_buffer.h"
2901
2902 #include <stdio.h>
2903
2904 int main(int argc, char **argv)
2905 {
2906 char *filename = argv[1];
2907 int xcount = 0;
2908 int linecount = 0;
2909 ESL_BUFFER *bf;
2910 char *p;
2911 esl_pos_t n, i;
2912 int status;
2913
2914 status = esl_buffer_Open(filename, "TESTDIR", &bf);
2915 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf->errmsg);
2916 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf->errmsg);
2917 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
2918
2919 while (( status = esl_buffer_GetLine(bf, &p, &n)) == eslOK)
2920 {
2921 linecount++;
2922 for (i = 0; i < n; i++)
2923 if (p[i] == 'x') xcount++;
2924 }
2925 if (status != eslEOF) esl_fatal("file %s: expected EOF, got code %d", bf->filename, status);
2926
2927 esl_buffer_Close(bf);
2928 printf("Counted %d x's in %d lines.\n", xcount, linecount);
2929 return 0;
2930 }
2931 /*::cexcerpt::buffer_example::end::*/
2932 #endif /*eslBUFFER_EXAMPLE*/
2933
2934
2935
2936 #ifdef eslBUFFER_EXAMPLE2
2937 /*::cexcerpt::buffer_example2::begin::*/
2938 #include "easel.h"
2939 #include "esl_buffer.h"
2940
2941 #include <stdio.h>
2942
2943 int main(int argc, char **argv)
2944 {
2945 char *filename = argv[1];
2946 int xcount = 0;
2947 int tokcount = 0;
2948 ESL_BUFFER *bf;
2949 char *tok;
2950 esl_pos_t n, i;
2951 int status;
2952
2953 status = esl_buffer_Open(filename, "TESTDIR", &bf);
2954 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf->errmsg);
2955 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf->errmsg);
2956 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
2957
2958 while ( (status = esl_buffer_GetToken(bf, " \t\r\n", &tok, &n)) == eslOK)
2959 {
2960 tokcount++;
2961 for (i = 0; i < n; i++)
2962 if (tok[i] == 'x') xcount++;
2963 }
2964 if (status != eslEOF) esl_fatal("did not see expected EOF; code %d instead", status);
2965 esl_buffer_Close(bf);
2966 printf("Counted %d x's in %d words\n", xcount, tokcount);
2967 return 0;
2968 }
2969 /*::cexcerpt::buffer_example2::end::*/
2970 #endif /*eslBUFFER_EXAMPLE2*/
2971
2972
2973
2974 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_example3 -DeslBUFFER_EXAMPLE3 esl_buffer.c -leasel -lm
2975 * run: ./esl_buffer_example3 <file>
2976 */
2977 #ifdef eslBUFFER_EXAMPLE3
2978 /*::cexcerpt::buffer_example3::begin::*/
2979 #include "easel.h"
2980 #include "esl_buffer.h"
2981
2982 #include <stdio.h>
2983
2984 int main(int argc, char **argv)
2985 {
2986 char *filename = argv[1];
2987 int xcount = 0;
2988 int tokcount = 0;
2989 int linecount = 0;
2990 ESL_BUFFER *bf;
2991 char *tok;
2992 esl_pos_t n,i;
2993 int status;
2994
2995 status = esl_buffer_Open(filename, "TESTDIR", &bf);
2996 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf->errmsg);
2997 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf->errmsg);
2998 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
2999
3000 while (1)
3001 {
3002 status = esl_buffer_GetToken(bf, " \t", &tok, &n);
3003 if (status == eslOK)
3004 {
3005 tokcount++;
3006 for (i = 0; i < n; i++)
3007 if (tok[i] == 'x') xcount++;
3008 }
3009 else if (status == eslEOL) linecount++;
3010 else if (status == eslEOF) break;
3011 }
3012 esl_buffer_Close(bf);
3013 printf("Counted %d x's in %d words on %d lines\n", xcount, tokcount, linecount);
3014 return 0;
3015 }
3016 /*::cexcerpt::buffer_example3::end::*/
3017 #endif /*eslBUFFER_EXAMPLE3*/
3018
3019
3020
3021
3022 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_example4 -DeslBUFFER_EXAMPLE4 esl_buffer.c -leasel -lm
3023 * run: ./esl_buffer_example4 <file>
3024 */
3025 #ifdef eslBUFFER_EXAMPLE4
3026 /*::cexcerpt::buffer_example4::begin::*/
3027 #include "easel.h"
3028 #include "esl_buffer.h"
3029
3030 #include <stdio.h>
3031 #include <string.h>
3032
3033 int main(void)
3034 {
3035 char tmpfile[32] = "esltmpXXXXXX";
3036 char s1[] = "hello world!";
3037 char s2[] = "... and goodbye!";
3038 char buf[256];
3039 int n;
3040 FILE *fp;
3041 ESL_BUFFER *bf;
3042 int status;
3043
3044 esl_tmpfile_named(tmpfile, &fp);
3045 n = strlen(s1)+1; fwrite(&n, sizeof(int), 1, fp); fwrite(s1, sizeof(char), n, fp);
3046 n = strlen(s2)+1; fwrite(&n, sizeof(int), 1, fp); fwrite(s2, sizeof(char), n, fp);
3047 fclose(fp);
3048
3049 status = esl_buffer_Open(tmpfile, NULL, &bf);
3050 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf ? bf->errmsg : "(no other diagnostics available)");
3051 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf ? bf->errmsg : "(no other diagnostics available)");
3052 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
3053
3054 esl_buffer_Read(bf, sizeof(int), &n);
3055 esl_buffer_Read(bf, sizeof(char) * n, buf);
3056 puts(buf);
3057
3058 esl_buffer_Read(bf, sizeof(int), &n);
3059 esl_buffer_Read(bf, sizeof(char) * n, buf);
3060 puts(buf);
3061
3062 esl_buffer_Close(bf);
3063 return 0;
3064 }
3065 /*::cexcerpt::buffer_example4::end::*/
3066 #endif /*eslBUFFER_EXAMPLE4*/
3067
3068
3069
3070
3071 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_example5 -DeslBUFFER_EXAMPLE5 esl_buffer.c -leasel -lm
3072 * run: ./esl_buffer_example5 <fastafile>
3073 */
3074 #ifdef eslBUFFER_EXAMPLE5
3075 /*::cexcerpt::buffer_example5a::begin::*/
3076 #include "easel.h"
3077 #include "esl_buffer.h"
3078
3079 #include <stdio.h>
3080 #include <ctype.h>
3081
3082 int
3083 example_read_fasta(ESL_BUFFER *bf, char **ret_name, char **ret_desc, char **ret_seq, int *ret_seqlen)
3084 {
3085 char *seqname = NULL;
3086 char *seqdesc = NULL;
3087 char *seq = NULL;
3088 esl_pos_t seqlen = 0;
3089 esl_pos_t salloc = 0;
3090 char *p;
3091 void *tmp;
3092 esl_pos_t n, i;
3093 int status;
3094
3095 if ((status = esl_buffer_Get(bf, &p, &n)) != eslOK) goto ERROR; /* includes normal EOF */
3096 if (p[0] != '>') ESL_XFAIL(eslEINVAL, bf->errmsg, "Expected FASTA record to start with >");
3097 esl_buffer_Set(bf, p, 1);
3098
3099 status = esl_buffer_FetchTokenAsStr(bf, " \t", &seqname, NULL);
3100 if (status == eslEOF) ESL_XFAIL(eslEINVAL, bf->errmsg, "Premature eof while trying to parse sequence name");
3101 else if (status == eslEOL) ESL_XFAIL(eslEINVAL, bf->errmsg, "No sequence name found");
3102
3103 status = esl_buffer_FetchLineAsStr(bf, &seqdesc, NULL);
3104 if (status == eslEOF) goto DONE; /* weird but ok. name, no desc, and a blank sequence. */
3105
3106 ESL_ALLOC(seq, sizeof(char) * 256);
3107 salloc = 256;
3108
3109 while (esl_buffer_GetLine(bf, &p, &n) == eslOK)
3110 {
3111 if (p[0] == '>') { esl_buffer_Set(bf, p, 0); break; }
3112
3113 if (seqlen+n+1 > salloc) {
3114 ESL_RALLOC(seq, tmp, sizeof(char) * (seqlen+n+1));
3115 salloc = seqlen+n+1;
3116 }
3117
3118 for (i = 0; i < n; i++) {
3119 if (! isspace(p[i])) { seq[seqlen++] = p[i]; }
3120 }
3121 }
3122
3123 DONE:
3124 seq[seqlen] = '\0';
3125 *ret_name = seqname;
3126 *ret_desc = seqdesc;
3127 *ret_seq = seq;
3128 *ret_seqlen = seqlen;
3129 return eslOK;
3130
3131 ERROR:
3132 if (seqname) free(seqname);
3133 if (seqdesc) free(seqdesc);
3134 if (seq) free(seq);
3135 *ret_name = NULL;
3136 *ret_desc = NULL;
3137 *ret_seq = NULL;
3138 *ret_seqlen = 0;
3139 return status;
3140 }
3141 /*::cexcerpt::buffer_example5a::end::*/
3142
3143 /*::cexcerpt::buffer_example5b::begin::*/
3144 int
3145 main(int argc, char **argv)
3146 {
3147 char *filename = argv[1];
3148 ESL_BUFFER *bf;
3149 char *seqname, *seqdesc, *seq;
3150 int seqlen;
3151 int status;
3152
3153 status = esl_buffer_Open(filename, "TESTDIR", &bf);
3154 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf ? bf->errmsg : "(no other diagnostics available)");
3155 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf ? bf->errmsg : "(no other diagnostics available)");
3156 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
3157
3158 while ( (status = example_read_fasta(bf, &seqname, &seqdesc, &seq, &seqlen)) == eslOK)
3159 {
3160 printf("sequence: %20s length: %6d description: %s\n", seqname, seqlen, seqdesc);
3161 free(seqname);
3162 free(seqdesc);
3163 free(seq);
3164 }
3165 if (status != eslEOF) esl_fatal("bad FASTA format: %s", bf->errmsg);
3166 esl_buffer_Close(bf);
3167 return 0;
3168 }
3169 /*::cexcerpt::buffer_example5b::end::*/
3170 #endif /*eslBUFFER_EXAMPLE5*/
3171
3172
3173
3174 /* compile: gcc -g -Wall -I. -L. -o esl_buffer_example6 -DeslBUFFER_EXAMPLE6 esl_buffer.c -leasel -lm
3175 * run: ./esl_buffer_example6 <alifile>
3176 */
3177 #ifdef eslBUFFER_EXAMPLE6
3178 /*::cexcerpt::buffer_example6a::begin::*/
3179 #include "easel.h"
3180 #include "esl_buffer.h"
3181
3182 #include <stdio.h>
3183 #include <ctype.h>
3184
3185 int
3186 example_read_lineblock(ESL_BUFFER *bf, char ***ret_lines, esl_pos_t **ret_lens, esl_pos_t *ret_nlines)
3187 {
3188 char **lines = NULL;
3189 esl_pos_t *lens = NULL;
3190 esl_pos_t nlines = 0;
3191 char *p;
3192 esl_pos_t n;
3193 esl_pos_t start_offset;
3194 int status;
3195
3196 /* skip blank lines */
3197 do {
3198 start_offset = esl_buffer_GetOffset(bf);
3199 if ( (status = esl_buffer_GetLine(bf, &p, &n)) != eslOK) goto ERROR; /* includes normal EOF */
3200 } while (esl_memspn(p, n, " \t\r\n") == n);
3201 /* now p[0..n-1] is a non-blank line, start_offset is offset of p[0], point's on start of next line after it */
3202
3203 /* anchor stably at start of line block */
3204 esl_buffer_SetStableAnchor(bf, start_offset);
3205
3206 /* set pointers to non-blank lines */
3207 do {
3208 ESL_REALLOC(lines, sizeof(char *) * (nlines+1));
3209 ESL_REALLOC(lens, sizeof(esl_pos_t) * (nlines+1));
3210
3211 lines[nlines] = p; // cppcheck complains about these assignments: "possible null pointer deference";
3212 lens[nlines] = n; // but cppcheck is wrong. ESL_REALLOC will fail if lines[] or lens[] are NULL.
3213 nlines++;
3214 } while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK && esl_memspn(p, n, " \t\r\n") < n);
3215
3216 /* now p[0] is on a blank line, and point is on start of next line
3217 * after it. you might be fine with that; or you might want to push
3218 * the blank line back onto the parser. If so, you need to push
3219 * the line back *before* raising the anchor, because the _Set() function
3220 * is allowed to relocate the buffer's internal memory.
3221 */
3222 esl_buffer_Set(bf, p, 0);
3223 esl_buffer_RaiseAnchor(bf, start_offset);
3224
3225 *ret_lines = lines;
3226 *ret_lens = lens;
3227 *ret_nlines = nlines;
3228 return eslOK;
3229
3230 ERROR:
3231 if (lines) free(lines);
3232 if (lens) free(lens);
3233 *ret_lines = NULL;
3234 *ret_lens = NULL;
3235 *ret_nlines = 0;
3236 return status;
3237 }
3238 /*::cexcerpt::buffer_example6a::end::*/
3239
3240 /*::cexcerpt::buffer_example6b::begin::*/
3241 int
3242 main(int argc, char **argv)
3243 {
3244 char *filename = argv[1];
3245 int blockcount = 0;
3246 int linecount = 0;
3247 int xcount = 0;
3248 int i,j;
3249 ESL_BUFFER *bf;
3250 char **lines;
3251 esl_pos_t *lens;
3252 esl_pos_t nlines;
3253 int status;
3254
3255 status = esl_buffer_Open(filename, "TESTDIR", &bf);
3256 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf->errmsg);
3257 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf->errmsg);
3258 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
3259
3260 while ( (status = example_read_lineblock(bf, &lines, &lens, &nlines)) == eslOK)
3261 {
3262 blockcount++;
3263 linecount += nlines;
3264 for (i = 0; i < nlines; i++)
3265 for (j = 0; j < lens[i]; j++)
3266 if (lines[i][j] == 'x') xcount++;
3267
3268 free(lines);
3269 free(lens);
3270 }
3271 if (status != eslEOF) esl_fatal("bad MSA format: %s", bf->errmsg);
3272 esl_buffer_Close(bf);
3273 printf("Counted %d x's in %d blocks of %d total lines\n", xcount, blockcount, linecount);
3274 return 0;
3275 }
3276 /*::cexcerpt::buffer_example6b::end::*/
3277 #endif /*eslBUFFER_EXAMPLE6*/