-
Notifications
You must be signed in to change notification settings - Fork 26
/
esl_buffer.c
3277 lines (2860 loc) · 115 KB
/
esl_buffer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*::cexcerpt::header_example::begin::*/
/* An input parsing abstraction.
*
* Table of contents:
* 1. ESL_BUFFER object: opening/closing.
* 2. Positioning and anchoring an ESL_BUFFER.
* 3. Raw access to the buffer.
* 4. Line-based parsing.
* 5. Token-based parsing.
* 6. Binary (fread-like) parsing.
* 7. Private (static) functions.
* 8. Benchmark.
* 9. Unit tests.
* 10. Test driver.
* 11. Examples.
*/
/*::cexcerpt::header_example::end::*/
/*::cexcerpt::include_example::begin::*/
#include <esl_config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h> // one of the utests uses alarm() to catch an infinite loop bug
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _POSIX_VERSION
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#endif /* _POSIX_VERSION */
#include "easel.h"
#include "esl_mem.h"
#include "esl_buffer.h"
/*::cexcerpt::include_example::end::*/
/*::cexcerpt::statics_example::begin::*/
static int buffer_create (ESL_BUFFER **ret_bf);
static int buffer_init_file_mmap (ESL_BUFFER *bf, esl_pos_t filesize);
static int buffer_init_file_slurped(ESL_BUFFER *bf, esl_pos_t filesize);
static int buffer_init_file_basic (ESL_BUFFER *bf);
static int buffer_refill (ESL_BUFFER *bf, esl_pos_t nmin);
static int buffer_countline(ESL_BUFFER *bf, esl_pos_t *opt_nc, esl_pos_t *opt_nskip);
static int buffer_skipsep (ESL_BUFFER *bf, const char *sep);
static int buffer_newline (ESL_BUFFER *bf);
static int buffer_counttok (ESL_BUFFER *bf, const char *sep, esl_pos_t *ret_nc);
/*::cexcerpt::statics_example::end::*/
/*****************************************************************
*# 1. ESL_BUFFER object: opening/closing.
*****************************************************************/
/* Function: esl_buffer_Open()
* Synopsis: Standard Easel idiom for opening a stream by filename.
*
* Purpose: Open <filename> for parsing. Return an open
* <ESL_BUFFER> for it.
*
* The standard Easel idiom allows reading from standard
* input (pass <filename> as '-'), allows reading gzip'ed
* files automatically (any <filename> ending in <.gz> is
* opened as a pipe from <gzip -dc>), and allows using an
* environment variable to specify a colon-delimited list
* of directories in which <filename> may be found. Normal
* files are memory mapped (if <mmap()> is available) when
* they are large, and slurped into memory if they are
* small.
*
* If <filename> is '-' (a single dash character),
* capture the standard input stream rather than
* opening a file; return <eslOK>.
*
* Else, try to find <filename> in a directory <d>,
* starting with the current working directory. If
* <./filename> is found (note that <filename> may include
* a relative path), directory <d> is <.>. Else, if
* <envvar> is non-<NULL>, check the environment variable
* <envvar> for a colon-delimited list of directories, and
* for each directory <d> in that list, try to find
* <d/filename>. Use the first <d> that succeeds. If
* none succeed, return <eslENOTFOUND>.
*
* Now open the file. If <filename> ends in <.gz>, 'open'
* it by running <gzip -dc d/filename 2>/dev/null>,
* capturing the standard output from gunzip decompression
* in the <ESL_BUFFER>. Otherwise, open <d/filename> as a
* normal file. If its size is not more than
* <eslBUFFER_SLURPSIZE> (default 4 MB), it is slurped into
* memory; else, if <mmap()> is available, it is memory
* mapped; else, it is opened as a read-only binary stream
* with <fopen()> in mode <"rb">.
*
* Args: filename - file to open for reading; or '-' for STDIN
* envvar - name of an environment variable in which to
* find a colon-delimited list of directories;
* or <NULL> if none.
* ret_bf - RETURN: new ESL_BUFFER
*
* Returns: <eslOK> on success; <*ret_bf> is the new <ESL_BUFFER>.
*
* <eslENOTFOUND> if file isn't found or isn't readable.
* <eslFAIL> if gzip -dc fails on a .gz file, probably
* because a gzip executable isn't found in PATH.
*
* On any normal error, <*ret_bf> is still returned,
* in an unset state, with a user-directed error message
* in <*ret_bf->errmsg>.
*
* Throws: <eslESYS> on system call failures (such as fread()).
* <eslEMEM> on allocation failure.
* Now <*ret_bf> is <NULL>.
*/
int
esl_buffer_Open(const char *filename, const char *envvar, ESL_BUFFER **ret_bf)
{
char *path = NULL;
int n;
int status;
/* "-" => stdin */
if (strcmp(filename, "-") == 0)
return esl_buffer_OpenStream(stdin, ret_bf);
/* else, a file. find its fully qualified path */
if (esl_FileExists(filename)) /* look in current working directory */
{ if ( (status = esl_strdup(filename, -1, &path)) != eslOK) { *ret_bf = NULL; goto ERROR; } }
else { /* then search directory list in envvar, if any */
status = esl_FileEnvOpen(filename, envvar, NULL, &path);
if (status == eslENOTFOUND) { esl_buffer_OpenFile(filename, ret_bf); goto ERROR; }
else if (status != eslOK) { *ret_bf = NULL; goto ERROR; }
/* yeah, the esl_buffer_OpenFile() looks weird - we know the file's not there! -
* but it's a clean way to set our error return status properly,
* recording the correct error message in a live ESL_BUFFER's bf->errmsg.
* note that esl_FileEnvOpen() correctly handles envvar==NULL,
* returning eslENOTFOUND.
*/
}
n = strlen(path);
if (n > 3 && strcmp(filename+n-3, ".gz") == 0) /* if .gz => gzip -dc */
{ if ( (status = esl_buffer_OpenPipe(path, "gzip -dc %s 2>/dev/null", ret_bf)) != eslOK) goto ERROR; }
else
{ if ( (status = esl_buffer_OpenFile(path, ret_bf)) != eslOK) goto ERROR; }
free(path);
return eslOK;
ERROR:
if (path) free(path);
return status;
}
/* Function: esl_buffer_OpenFile()
* Synopsis: Open a file.
*
* Purpose: Open <filename> for reading. Return an open <ESL_BUFFER> in
* <*ret_bf>.
*
* <filename> may be a relative path such as <subdir/foo>
* or a full path such as </my/dir/foo>.
*
* On a POSIX-compliant system, large files are memory
* mapped, and small files are just slurped into memory.
*
* On non-POSIX systems, the file is opened as a stream.
* On a short initial read (if the file size is smaller than
* the buffer page size), the file is considered to be
* completely slurped.
*
* Args: filename - name of (or path to) file to open
* *ret_bf - RETURN: new ESL_BUFFER
*
* Returns: <eslOK> on success; <*ret_bf> is new <ESL_BUFFER>.
*
* <eslENOTFOUND> if <filename> isn't found or isn't readable.
*
* On normal errors, a new <*ret_bf> is still returned, in
* an unset state, with a user-directed error message in
* <*ret_bf->errmsg>.
*
* Throws: <eslEMEM> on allocation failure.
*/
int
esl_buffer_OpenFile(const char *filename, ESL_BUFFER **ret_bf)
{
ESL_BUFFER *bf = NULL;
#ifdef _POSIX_VERSION
struct stat fileinfo;
#endif
esl_pos_t filesize = -1;
int status;
if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
if ((bf->fp = fopen(filename, "rb")) == NULL)
ESL_XFAIL(eslENOTFOUND, bf->errmsg, "couldn't open %s for reading", filename);
if ((status = esl_strdup(filename, -1, &(bf->filename))) != eslOK) goto ERROR;
/* Try to use POSIX fstat() to get file size and optimal read size.
* Use filesize to decide whether to slurp, mmap, or read normally.
* If we don't have fstat(), we'll just read normally, and pagesize
* will be the Easel default 4096 (set in buffer_create().)
*/
#ifdef _POSIX_VERSION
if (fstat(fileno(bf->fp), &fileinfo) == -1) ESL_XEXCEPTION(eslESYS, "fstat() failed");
filesize = fileinfo.st_size;
bf->pagesize = fileinfo.st_blksize;
if (bf->pagesize < 512) bf->pagesize = 512; /* I feel paranoid about st_blksize range not being guaranteed to be sensible */
if (bf->pagesize > 4194304) bf->pagesize = 4194304;
#endif
if (filesize != -1 && filesize <= eslBUFFER_SLURPSIZE)
{ if ((status = buffer_init_file_slurped(bf, filesize)) != eslOK) goto ERROR; }
#ifdef _POSIX_VERSION
else if (filesize > eslBUFFER_SLURPSIZE)
{ if ((status = buffer_init_file_mmap(bf, filesize)) != eslOK) goto ERROR; }
#endif
else
{ if ((status = buffer_init_file_basic(bf)) != eslOK) goto ERROR; }
*ret_bf = bf;
return status;
ERROR:
if (status != eslENOTFOUND) { esl_buffer_Close(bf); bf = NULL; }
if (bf) {
if (bf->fp) { fclose(bf->fp); bf->fp = NULL; }
if (bf->filename) { free(bf->filename); bf->filename = NULL; }
bf->pagesize = eslBUFFER_PAGESIZE;
}
*ret_bf = bf;
return status;
}
/* Function: esl_buffer_OpenPipe()
* Synopsis: Open a file through a command's stdout pipe (e.g. gunzip).
*
* Purpose: Run the command <cmdfmt> on <filename> and capture its <stdout>
* stream for parsing. Return the open <ESL_BUFFER> in
* <*ret_bf>.
*
* <cmdfmt> has a restricted format; it is a <printf()>-style
* format string with a single <%s>, where <filename> is to
* be substituted. An example <cmdfmt> is "gzip -dc %s
* 2>/dev/null".
*
* <filename> is checked for existence and read permission
* before a command line is constructed.
* <filename> may be <NULL>. In this case, <cmdfmt> is
* assumed to be be the complete command, and (obviously)
* the diagnostic check for <filename>
* existence/readability is skipped. This gives you some
* ability to skip the restricted single-argument format of
* <cmdfmt>. If you need to do something fancier with a
* pipe, you can always open and manage it yourself and use
* <esl_buffer_OpenStream()>.
*
* <popen()> executes the command under </bin/sh>.
*
* The <stderr> stream of the command should almost
* certainly be redirected (else it will appear on output
* of your program). In general it should be discarded
* to </dev/null>. One of the only signs of a command
* failure is that the command produces a "short read", of
* less than <bf->pagesize> (and often 0, on a complete
* failure, if <stderr> has been discarded). If <stderr>
* is longer than the buffer's <pagesize>, we may not
* accurately detect error conditions. If you must capture
* <stderr> (for example with a <cmdfmt> like
* "gzip -dc %s 2>&1") be aware that the parser may
* see that output as "successful" execution, if it's long
* enough.
*
* The reason to pass <cmdfmt> and <filename> separately is
* to enable better error diagnostics. <popen()> itself
* tends to "succeed" whether the command or the file exist
* or not. By having <filename>, we can check for its
* existence/readability first.
*
* The reason that error checking <popen()> isn't entirely
* straightforward is that we don't see the exit status of
* the command until we <pclose()>. We can only <pclose()>
* when we're done loading data from the file, and that
* only happens here on a short initial read. If we do get
* a short read, we <pclose()>, get and check the command's
* exit status, and return the <ESL_BUFFER> in an
* <eslBUFFER_ALLFILE> state with <bf->cmdline> set.
*
* Args: filename - file name (or path) to plug into <cmdfmt>; or NULL
* if <cmdfmt> is complete command already
* cmdfmt - command to execute (with /bin/sh) and capture
* stdout from.
* *ret_bf - RETURN: new ESL_BUFFER
*
* Returns: <eslOK> on success, and <*ret_bf> is the new <ESL_BUFFER>.
*
* <eslENOTFOUND> if <filename> isn't found or isn't readable.
*
* <eslFAIL> if the constructed command fails - which
* usually means that the program isn't found or isn't
* executable, or that the command returned nonzero
* (quickly, i.e. with zero or little output and a 'short
* read').
*
* On any normal error, the <*ret_bf> is returned (in an
* <eslBUFFER_UNSET> state) and <bf->errmsg> contains a
* user-directed error message.
*
* Throws: <eslESYS> on <*sprintf()> or <fread()> failure.
* <eslEMEM> on allocation failure.
*
* On any exception, <*ret_bf> is NULL.
*/
int
esl_buffer_OpenPipe(const char *filename, const char *cmdfmt, ESL_BUFFER **ret_bf)
{
ESL_BUFFER *bf = NULL;
char *cmd = NULL;
int status;
if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
if (filename && ! esl_FileExists(filename))
ESL_XFAIL(eslENOTFOUND, bf->errmsg, "couldn't read file %s", filename);
if (filename) { if ((status = esl_sprintf(&cmd, cmdfmt, filename)) != eslOK) goto ERROR; }
else { if ((status = esl_strdup(cmdfmt, -1, &cmd)) != eslOK) goto ERROR; }
if ((bf->fp = popen(cmd, "r")) == NULL)
ESL_XFAIL(eslENOTFOUND, bf->errmsg, "couldn't popen() the command: %s\n", cmd);
if ( (status = esl_strdup(cmd, -1, &(bf->cmdline))) != eslOK) goto ERROR;
if (filename && (status = esl_strdup(filename, -1, &(bf->filename))) != eslOK) goto ERROR;
ESL_ALLOC(bf->mem, sizeof(char) * bf->pagesize);
bf->balloc = bf->pagesize;
bf->n = fread(bf->mem, sizeof(char), bf->pagesize, bf->fp);
/* Now check for various errors on a short read. A short read can mean:
* - a small file; success, and we have the whole file in one page
* - popen() "succeeded" but the command failed
* - an fread() failure
* Sort it out. The trick here is that we don't get the exit status
* of <cmd> until we pclose(). So (assuming it isn't fread() itself
* that failed) we take advantage of the fact that we can set the
* ESL_BUFFER to a eslBUFFER_ALLFILE state on a short initial read;
* pclose() and check command exit status.
* This pretty much relies on what <stderr> from <cmd> looks like;
* it needs to either be redirected, or short enough to be a short read.
*/
if (bf->n < bf->pagesize)
{
/* Delayed exception throwing. If popen() failed, ferror() may be set too; evaluate what happened to popen() first. */
status = (ferror(bf->fp) ? eslESYS : eslOK);
if (pclose(bf->fp) != 0) {
bf->fp = NULL; /* error block is going to try to pclose() too */
ESL_XFAIL(eslFAIL, bf->errmsg, "pipe command '%s' did not succeed", cmd);
}
/* now deal with an fread() error. */
if (status != eslOK) ESL_XEXCEPTION(eslESYS, "fread() failed");
bf->fp = NULL;
bf->balloc = 0;
bf->mode_is = eslBUFFER_ALLFILE;
}
else
bf->mode_is = eslBUFFER_CMDPIPE;
free(cmd);
*ret_bf = bf;
return eslOK;
ERROR:
if (status != eslENOTFOUND && status != eslFAIL) { esl_buffer_Close(bf); bf = NULL; }
if (bf) { /* restore state to UNSET; w/ error message in errmsg */
if (bf->mem) { free(bf->mem); bf->mem = NULL; }
if (bf->fp) { pclose(bf->fp); bf->fp = NULL; }
if (bf->filename) { free(bf->filename); bf->filename = NULL; }
if (bf->cmdline) { free(bf->cmdline); bf->cmdline = NULL; }
bf->n = 0;
bf->balloc = 0;
}
if (cmd) free(cmd);
*ret_bf = bf;
return status;
}
/* Function: esl_buffer_OpenMem()
* Synopsis: "Open" an existing string for parsing.
*
* Purpose: Given a buffer or string <p> of length <n>, turn it into
* an <ESL_BUFFER>. Return the new buffer in <*ret_bf>.
*
* The memory for <p> is still managed by the caller.
* Caller should free it, if necessary, only after the
* <ESL_BUFFER> has been closed.
*
* As a special case, if <n> is -1, <p> is assumed to be a
* \verb+\0+-terminated string and its length is calculated with
* <strlen()>.
*
* Args: p - ptr to buffer or string
* n - length of buffer/string <p>, in bytes
* ret_bf - RETURN: new ESL_BUFFER
*
* Returns: <eslOK> on success, and <*ret_bf> points to new buffer.
*
* Throws: <eslEMEM> on allocation failure.
* On any exception, <*ret_bf> is <NULL>.
*/
int
esl_buffer_OpenMem(const char *p, esl_pos_t n, ESL_BUFFER **ret_bf)
{
ESL_BUFFER *bf = NULL;
int status;
if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
bf->mem = (char *) p; /* force discard of const qualifier; this is ok; mem won't be altered in eslBUFFER_STRING mode */
bf->n = (n == -1) ? strlen(p) : n;
bf->mode_is = eslBUFFER_STRING;
*ret_bf = bf;
return eslOK;
ERROR:
if (bf) { /* on error, restore to UNSET state */
bf->mem = NULL;
bf->n = 0;
bf->mode_is = eslBUFFER_UNSET;
}
*ret_bf = bf;
return status;
}
/* Function: esl_buffer_OpenStream()
* Synopsis: "Open" an existing stream for parsing.
*
* Purpose: Given an open stream <fp> for reading, create an
* <ESL_BUFFER> around it.
*
* <fp> is often <stdin>, for example.
*
* The caller remains responsible for closing <fp>, if it
* opened it.
*
* Args: fp - stream to associate with new ESL_BUFFER
* *ret_bf - RETURN: new ESL_BUFFER.
*
* Returns: <eslOK> on success, and <*ret_bf> points to a new <ESL_BUFFER>.
*
* Throws: <eslEINVAL>: <fp> is NULL, in error state, or already at eof before any reading occurs.
* <eslESYS> : fread() failed
* <eslEMEM> : an allocation failed
*/
int
esl_buffer_OpenStream(FILE *fp, ESL_BUFFER **ret_bf)
{
ESL_BUFFER *bf = NULL;
int status;
if ((status = buffer_create(&bf)) != eslOK) goto ERROR;
bf->mode_is = eslBUFFER_STREAM;
if (fp == NULL || ferror(fp) || feof(fp)) ESL_XEXCEPTION(eslEINVAL, "invalid stream");
bf->fp = fp; /* a copy of <fp>; caller is still responsible for it */
ESL_ALLOC(bf->mem, sizeof(char) * bf->pagesize);
bf->balloc = bf->pagesize;
bf->n = fread(bf->mem, sizeof(char), bf->pagesize, bf->fp);
if (bf->n < bf->pagesize && ferror(bf->fp))
ESL_XEXCEPTION(eslESYS, "failed to read first chunk of stream");
*ret_bf = bf;
return eslOK;
ERROR:
esl_buffer_Close(bf);
*ret_bf = NULL;
return status;
}
/* Function: esl_buffer_Close()
* Synopsis: Close an input buffer.
* Incept: SRE, Mon Feb 14 09:09:04 2011 [Janelia]
*
* Purpose: Close the input buffer <bf>, freeing all resources that it
* was responsible for.
*
* Args: bf - the input buffer
*
* Returns: <eslOK> on success.
*
* Throws: <eslESYS> on a system call failure such as <munmap()>, <pclose()>, or <fclose()>.
*
* Note: error handling here departs from usual idiom, because we try to tolerate errors
* and continue free'ing resources; only at the end do we return a failure code, if
* something went awry.
*/
int
esl_buffer_Close(ESL_BUFFER *bf)
{
if (bf)
{
if (bf->mem)
{
switch (bf->mode_is) {
case eslBUFFER_MMAP: if (munmap(bf->mem, bf->n) == -1) ESL_EXCEPTION(eslESYS, "munmap() failed"); break;
case eslBUFFER_STRING: break; /* caller provided and remains responsible for an input memory buffer */
default: free(bf->mem);
}
}
if (bf->fp)
{
switch (bf->mode_is) {
case eslBUFFER_CMDPIPE: if (pclose(bf->fp) == -1) ESL_EXCEPTION(eslESYS, "pclose() failed"); break;
case eslBUFFER_STREAM: break; /* caller provided and remains responsible for an open stream */
default: if (fclose(bf->fp) == -1) ESL_EXCEPTION(eslESYS, "fclose() failed"); break;
}
}
if (bf->filename) free(bf->filename);
if (bf->cmdline) free(bf->cmdline);
free(bf);
}
return eslOK;
}
/*--------------- end, ESL_BUFFER open/close --------------------*/
/*****************************************************************
*# 2. Positioning and anchoring an ESL_BUFFER
*****************************************************************/
/* Function: esl_buffer_GetOffset()
* Synopsis: Get the current position of parser in input buffer.
*
* Purpose: Returns the current offset position of the parser
* in the input buffer: <bf->baseoffset + bf->pos>.
*/
esl_pos_t
esl_buffer_GetOffset(ESL_BUFFER *bf)
{
return bf->baseoffset + bf->pos;
}
/* Function: esl_buffer_SetOffset()
* Synopsis: Reposition the input buffer to a new place.
* Incept: SRE, Mon Jan 31 13:14:09 2011 [Janelia]
*
* Purpose: Set the buffer's internal state (<bf->pos>) to position
* <offset> in the input. Load new data into the buffer if
* necessary.
*
* In modes where <bf->mem> contains the whole input
* (ALLFILE, MMAP, STRING), this always works.
*
* In modes where we're reading a
* nonrewindable/nonpositionable stream (STREAM, CMDPIPE),
* <offset> may be at or ahead of the current position, but
* rewinding to an offset behind the current position only
* works if <offset> is within the current buffer
* window. If the caller knows it wants to return to some
* <offset> later, it should set an anchor to make sure it
* stays in the buffer. New data may need to be read into
* <bf->mem> to assure <pagesize> bytes are available. If
* an anchor is set, this may require reoffset and/or
* reallocation of <bf->mem>.
*
* FILE mode is handled as above, but additionally, if no
* anchor is set and <offset> is not in the current buffer,
* <fseeko()> is used to reposition in the open file. If
* <fseeko()> is unavailable (non-POSIX compliant systems),
* FILE mode is handled like other streams, with limited
* rewind ability.
*
* Args: bf - input buffer being manipulated
* offset - new position in the input
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if <offset> is invalid, either because it
* would require rewinding the (nonrewindable) stream,
* or because it's beyond the end.
* <eslESYS> if a system call fails, such as fread().
* <eslEMEM> on allocation failure.
* <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
*/
int
esl_buffer_SetOffset(ESL_BUFFER *bf, esl_pos_t offset)
{
int status;
/* Case 1. We have the entire file in bf->mem (or an mmap of it);
* Then this is trivial; we just set bf->pos.
*/
if (bf->mode_is == eslBUFFER_ALLFILE ||
bf->mode_is == eslBUFFER_MMAP ||
bf->mode_is == eslBUFFER_STRING)
{
bf->baseoffset = 0; /* (redundant: just to assure you that state is correctly set) */
bf->pos = offset;
}
/* Case 2. We have an open stream.
* Then:
* - if offset is behind us, and in our current buffer window,
* rewind is always possible and trivial: set bf->pos; or
* - if we're a FILE, and we're on a POSIX system with fseeko(),
* and there's no anchor set -- then we can fseeko() to the
* desired offset (no matter where it is) and
* reinitialize the buffer; or
* - otherwise rewinding a stream is not possible, generating
* an <eslEINVAL> error; or
* - finally, the remaining possibility is that the offset is
* ahead of (or at) the current parser position; fread()
* (respecting any set anchor) until <offset> is in the
* current buffer window, put bf->pos on it, and call
* buffer_refill() to be sure that we either have at least
* <bf->pagesize> bytes to parse (inclusive of current pos)
* or the stream reaches EOF.
*/
else if (bf->mode_is == eslBUFFER_STREAM ||
bf->mode_is == eslBUFFER_CMDPIPE ||
bf->mode_is == eslBUFFER_FILE)
{
if (offset >= bf->baseoffset && offset < bf->baseoffset + bf->pos) /* offset is in our current window and behind our current pos; rewind is trivial */
{
bf->pos = offset-bf->baseoffset;
}
#ifdef _POSIX_VERSION
else if (bf->mode_is == eslBUFFER_FILE && bf->anchor == -1)
{ /* a posix-compliant system can always fseeko() on a file */
if (fseeko(bf->fp, offset, SEEK_SET) != 0) ESL_EXCEPTION(eslEINVAL, "fseeko() failed, probably bad offset");
bf->baseoffset = offset;
bf->n = 0;
bf->pos = 0;
status = buffer_refill(bf, 0);
if (status == eslEOF) ESL_EXCEPTION(eslEINVAL, "requested offset is beyond end of file");
else if (status != eslOK) return status;
}
#endif /*_POSIX_VERSION*/
else if (offset < bf->baseoffset) /* we've already streamed past the requested offset. */
ESL_EXCEPTION(eslEINVAL, "can't rewind stream past base offset");
else /* offset is ahead of pos (or on it); fast forward, put bf->pos on it, reloading bf->mem as needed, respecting any anchors */
{
while (offset >= bf->baseoffset + bf->n)
{
bf->pos = bf->n;
status = buffer_refill(bf, 0);
if (status == eslEOF) ESL_EXCEPTION(eslEINVAL, "requested offset is beyond end of stream");
else if (status != eslOK) return status;
}
bf->pos = offset - bf->baseoffset;
status = buffer_refill(bf, 0);
if (status != eslEOF && status != eslOK) return status;
}
}
else ESL_EXCEPTION(eslEINCONCEIVABLE, "attempting to manipulate an uninitialized buffer");
return eslOK;
}
/* Function: esl_buffer_SetAnchor()
* Synopsis: Sets an anchor in an input stream.
*
* Purpose: Set an anchor at byte <offset> (in input coords) in
* input <bf>: which means, keep everything from this byte
* on in buffer memory, until anchor is raised.
*
* The presence of an anchor affects new reads from <fp>;
* <mem[r..n-1]> are protected from overwrite, and may be
* moved to <mem[0..n-r-1]> as new data is read from the
* stream. Anchors are only needed for input streams that
* we read chunkwise. If entire input is already in <bf>,
* setting an anchor is a no-op.
*
* In general, the caller should remember what anchor(s) it
* sets, so it can raise them later with
* <esl_buffer_RaiseAnchor()>.
*
* Byte <offset> must be in the current buffer window. If
* not, an <eslEINVAL> exception is thrown.
*
* Only one anchor is active at a time. If an anchor is
* already set for <bf>, the most upstream one is used.
*
* Args: bf - input buffer
* offset - absolute position in input, <0..inputlen-1>
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if <offset> is not in current buffer window.
*/
int
esl_buffer_SetAnchor(ESL_BUFFER *bf, esl_pos_t offset)
{
if (! bf->fp) return eslOK; /* without an open stream, no-op */
if (offset < bf->baseoffset || offset > bf->baseoffset + bf->n)
ESL_EXCEPTION(eslEINVAL, "can't set an anchor outside current buffer");
if (bf->anchor == -1 || offset-bf->baseoffset < bf->anchor)
{ /* setting a new anchor */
bf->anchor = offset-bf->baseoffset;
bf->nanchor = 1;
}
else if (offset-bf->baseoffset == bf->anchor)
{ /* reinforcing an anchor */
bf->nanchor++;
}
return eslOK;
}
/* Function: esl_buffer_SetStableAnchor()
* Synopsis: Set a stable anchor.
*
* Purpose: Same as <esl_buffer_SetAnchor()>, except the anchor is
* such that all pointers returned by <_Get*()> functions
* (i.e. as opposed to just the last <_Get*> function)
* will remain valid at least until the anchor is raised.
*
* The main use of this is when the caller wants to get
* multiple lines or tokens in the input before parsing
* them.
*
* A stable anchor prevents buffer refills/reloads from
* moving the internal memory around while the anchor is
* in place.
*
* Args: bf - input buffer
* offset - absolute position in input, <0..inputlen-1>
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if <offset> is not in current buffer window.
*
* Notes: We make a special call for stable anchors, as opposed
* to most anchors, because the <memmove()> call here
* to rebaseline the buffer's <mem> is expensive.
*/
int
esl_buffer_SetStableAnchor(ESL_BUFFER *bf, esl_pos_t offset)
{
esl_pos_t ndel;
int status;
if (! bf->fp) return eslOK; /* without an open stream, no-op: everything is available */
if ( (status = esl_buffer_SetAnchor(bf, offset)) != eslOK) return status;
ndel = bf->anchor;
bf->anchor = 0;
bf->n -= ndel;
bf->pos -= ndel;
if (bf->n) memmove(bf->mem, bf->mem+ndel, bf->n);
bf->baseoffset += ndel;
return eslOK;
}
/* Function: esl_buffer_RaiseAnchor()
* Synopsis: Raise an anchor.
*
* Purpose: Declare that an anchor previously set at <offset>
* in buffer <bf> may be raised.
*
* <offset> is in absolute input coordinates (<0..len-1> for
* an input of length <len>). Because it's supposed to be
* anchored, this position ought to be in the current
* buffer window. If an anchor is in effect in <bf>,
* <offset> should be at or distal to that anchor.
*
* The buffer's memory and position are not changed yet. A
* caller can raise an anchor and still assume that the
* buffer contains all data from that anchor, until the
* next call to something that would alter the buffer.
*
* Args: bf - input buffer
* offset - absolute position in input, <0..len-1>
*
* Returns: <eslOK> on success.
*
* Throws: (none)
*/
int
esl_buffer_RaiseAnchor(ESL_BUFFER *bf, esl_pos_t offset)
{
ESL_DASSERT1(( offset >= bf->baseoffset && offset <= bf->baseoffset + bf->n ));
ESL_DASSERT1(( bf->anchor <= offset - bf->baseoffset ));
if (bf->anchor == offset - bf->baseoffset) {
bf->nanchor--;
if (bf->nanchor == 0) bf->anchor = -1;
}
return eslOK;
}
/*--------------- end, ESL_BUFFER manipulation ------------------*/
/*****************************************************************
*# 3. Raw access to the buffer
*****************************************************************/
/* Function: esl_buffer_Get()
* Synopsis: Get a pointer into the current buffer window.
* Incept: SRE, Mon Jan 31 20:45:22 2011 [Casa de Gatos]
*
* Purpose: Given a buffer <bf>, return a pointer to the current
* parsing position in <*ret_p>, and the number of valid
* bytes from that position in <*ret_n>.
*
* If buffer is at EOF (no valid bytes remain), returns
* <eslEOF> with <NULL> in <*ret_p> and 0 in <*ret_n>.
*
* The buffer's parsing position <bf->pos> is NOT
* changed. Another <Get()> call will return exactly
* the same <p> and <n>. Each <Get()> call is generally
* followed by a <Set()> call. It's the <Set()> call
* that moves <bf->pos> and refills the buffer.
*
* Assumes that the buffer <bf> is correctly loaded,
* with either at least <pagesize> bytes after the
* parser position, or near/at EOF.
*
* Args: bf - buffer to get ptr from
* ret_p - RETURN: pointer to current parser position, or NULL on EOF
* ret_n - RETURN: number of valid bytes at *ret_p, or 0 on EOF
*
* Returns: <eslOK> on success;
* <eslEOF> if no valid bytes remain in the input, or if
* <*ret_n> is less than <nrequest>.
*
* Throws: <eslEMEM> on allocation failure.
* <eslESYS> if fread() fails mysteriously.
* <eslEINCONCEIVABLE> if internal state of <bf> is corrupt.
*/
int
esl_buffer_Get(ESL_BUFFER *bf, char **ret_p, esl_pos_t *ret_n)
{
*ret_p = (bf->pos < bf->n ? bf->mem + bf->pos : NULL);
*ret_n = (bf->pos < bf->n ? bf->n - bf->pos : 0);
return (bf->pos < bf->n ? eslOK : eslEOF);
}
/* Function: esl_buffer_Set()
* Synopsis: Set position and correct state of the <ESL_BUFFER>.
* Incept: SRE, Sun Jan 2 11:56:00 2011 [Zaragoza]
*
* Purpose: Reset the state of buffer <bf>: we were recently
* given a pointer <p> by an <esl_buffer_Get()> call
* and we parsed <nused> bytes starting at <p[0]>.
*
* <bf->pos> is set to point at <p+nused>, and we
* reload the buffer (if necessary) to try to have at
* least <bf->pagesize> bytes of input following that
* position.
*
* One use is in raw parsing, where we stop parsing
* somewhere in the buffer:
* \begin{cchunk}
* esl_buffer_Get(bf, &p, &n);
* (do some stuff on p[0..n-1], using up <nused> bytes)
* esl_buffer_Set(bf, p, nused);
* \end{cchunk}
* This includes the case of nused=n, where we parse the
* whole buffer that Get() gave us, and the Set() call may
* be needed to load new input data before the next Get().
*
* Another use is an idiom for peeking at a token, line, or
* a number of bytes without moving the parser position:
* \begin{cchunk}
* esl_buffer_GetLine(bf, &p, &n);
* (do we like what we see in p[0..n-1]? no? then put it back)
* esl_buffer_Set(bf, p, 0);
* \end{cchunk}
*
* Because it is responsible for loading new input as
* needed, Set() may reoffset and reallocate <mem>. If the
* caller wants an anchor respected, it must make sure that
* anchor is still in effect; i.e., a caller that is
* restoring state to an <ESL_BUFFER> should call Set()
* BEFORE calling RaiseAnchor().
*
* As a special case, if <p> is NULL, then <nused> is
* ignored, <bf->pos> is left whereever it was, and the
* only thing the <Set()> attempts to do is to fulfill the
* pagesize guarantee from the current position. If a
* <NULL> <p> has been returned by a Get*() call because we
* reached EOF, for example in some parsing loop that the
* EOF has broken us out of, it is safe to call
* <esl_buffer_Set(bf, NULL, 0)>: this is a no-op on a
* buffer that is at EOF.
*
* Args: bf - buffer to set
* p - pointer that previous Get() gave us
* nused - number of bytes we used, starting at p[0]
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation failure.
* <eslESYS> if fread() fails mysteriously.
* <eslEINCONCEIVABLE> if internal state of <bf> is corrupt.
*/
int
esl_buffer_Set(ESL_BUFFER *bf, char *p, esl_pos_t nused)
{
int status;
if (p) bf->pos = (p - bf->mem) + nused;
status = buffer_refill(bf, 0);
if (status == eslOK || status == eslEOF) return eslOK;
else return status;
}
/*----------------- end, lowest level access --------------------*/
/*****************************************************************
*# 4. Line-based parsing
*****************************************************************/
/* Function: esl_buffer_GetLine()
* Synopsis: Get ptr to next line in buffer.
*
* Purpose: Get a pointer <*opt_p> to the next line in buffer <bf>,
* and the length of the line in <*opt_n> (in bytes, and
* exclusive of newline bytes). Advance buffer position
* past (one) newline, putting it on the next valid data
* byte. Thus <p[0..n-1]> is one data line. It is not
* NUL-terminated.
*
* <bf>'s buffer may be re(al)located as needed, to get
* the whole line into the current window.
*
* Because the caller only gets a pointer into <bf>'s
* internal state, no other <esl_buffer> functions
* should be called until the caller is done with <p>.
*
* To peek at next line, use Set to restore <bf>'s state:
* \begin{cchunk}
* esl_buffer_GetLine(bf, &p, &n);
* esl_buffer_Set(bf, p, 0);
* \end{cchunk}
*
* Args: bf - buffer to get line from
* *opt_p - optRETURN: pointer to next line
* *opt_n - optRETURN: line length, exclusive of newline.
*
* Returns: <eslOK> on success. <*opt_p> is a valid pointer into <bf>'s buffer,
* and <*opt_n> is >=0. (0 would be an empty line.)
*
* <eslEOF> if there's no line (even blank).
* On EOF, <*opt_p> is NULL and <*opt_n> is 0.
*
* Throws: <eslEMEM> if allocation fails.
* <eslESYS> if a system call such as fread() fails unexpectedly
* <eslEINCONCEIVABLE> if <bf> internal state is corrupt.
*/
int
esl_buffer_GetLine(ESL_BUFFER *bf, char **opt_p, esl_pos_t *opt_n)
{
int anch_set = FALSE;
esl_pos_t nc, nskip;
esl_pos_t anch;
int status;
/* The next line starts at offset <baseoffset + pos> */
anch = bf->baseoffset + bf->pos;
status = esl_buffer_SetAnchor(bf, anch);
if (status == eslEINVAL) { status = eslEINCONCEIVABLE; goto ERROR; } /* we know bf->pos is in current window */
else if (status != eslOK) { goto ERROR; }
anch_set = TRUE;