1 /// @file htslib/hfile.h
2 /// Buffered low-level input/output streams.
3 /*
4     Copyright (C) 2013-2016 Genome Research Ltd.
5 
6     Author: John Marshall <jm18@sanger.ac.uk>
7 
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14 
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17 
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE.  */
25 
26 #ifndef HTSLIB_HFILE_H
27 #define HTSLIB_HFILE_H
28 
29 #include <string.h>
30 
31 #include <sys/types.h>
32 
33 #include "hts_defs.h"
34 
35 #ifdef __cplusplus
36 extern "C" {
37 #endif
38 
39 struct hFILE_backend;
40 /// Low-level input/output stream handle
41 /** The fields of this structure are declared here solely for the benefit
42 of the hFILE-related inline functions.  They may change in future releases.
43 User code should not use them directly; you should imagine that hFILE is an
44 opaque incomplete type.
45 */
46 typedef struct hFILE {
47     // @cond internal
48     char *buffer, *begin, *end, *limit;
49     const struct hFILE_backend *backend;
50     off_t offset;
51     unsigned at_eof:1, mobile:1, readonly:1;
52     int has_errno;
53     // @endcond
54 } hFILE;
55 
56 /// Open the named file or URL as a stream
57 /** @return An hFILE pointer, or `NULL` (with _errno_ set) if an error occurred.
58 
59 The usual `fopen(3)` _mode_ letters are supported: one of
60 `r` (read), `w` (write), `a` (append), optionally followed by any of
61 `+` (update), `e` (close on `exec(2)`), `x` (create exclusively),
62 `:` (indicates scheme-specific variable arguments follow).
63 */
64 hFILE *hopen(const char *filename, const char *mode, ...) HTS_RESULT_USED;
65 
66 /// Associate a stream with an existing open file descriptor
67 /** @return An hFILE pointer, or `NULL` (with _errno_ set) if an error occurred.
68 
69 For socket descriptors (on Windows), _mode_ should contain `s`.
70 */
71 hFILE *hdopen(int fd, const char *mode) HTS_RESULT_USED;
72 
73 /// Report whether the file name or URL denotes remote storage
74 /** @return  0 if local, 1 if remote.
75 
76 "Remote" means involving e.g. explicit network access, with the implication
77 that callers may wish to cache such files' contents locally.
78 */
79 int hisremote(const char *filename) HTS_RESULT_USED;
80 
81 /// Flush (for output streams) and close the stream
82 /** @return  0 if successful, or `EOF` (with _errno_ set) if an error occurred.
83 */
84 int hclose(hFILE *fp) HTS_RESULT_USED;
85 
86 /// Close the stream, without flushing or propagating errors
87 /** For use while cleaning up after an error only.  Preserves _errno_.
88 */
89 void hclose_abruptly(hFILE *fp);
90 
91 /// Return the stream's error indicator
92 /** @return  Non-zero (in fact, an _errno_ value) if an error has occurred.
93 
94 This would be called `herror()` and return true/false to parallel `ferror(3)`,
95 but a networking-related `herror(3)` function already exists.
96 */
herrno(hFILE * fp)97 static inline int herrno(hFILE *fp)
98 {
99     return fp->has_errno;
100 }
101 
102 /// Clear the stream's error indicator
hclearerr(hFILE * fp)103 static inline void hclearerr(hFILE *fp)
104 {
105     fp->has_errno = 0;
106 }
107 
108 /// Reposition the read/write stream offset
109 /** @return  The resulting offset within the stream (as per `lseek(2)`),
110     or negative if an error occurred.
111 */
112 off_t hseek(hFILE *fp, off_t offset, int whence) HTS_RESULT_USED;
113 
114 /// Report the current stream offset
115 /** @return  The offset within the stream, starting from zero.
116 */
htell(hFILE * fp)117 static inline off_t htell(hFILE *fp)
118 {
119     return fp->offset + (fp->begin - fp->buffer);
120 }
121 
122 /// Read one character from the stream
123 /** @return  The character read, or `EOF` on end-of-file or error.
124 */
hgetc(hFILE * fp)125 static inline int hgetc(hFILE *fp)
126 {
127     extern int hgetc2(hFILE *);
128     return (fp->end > fp->begin)? (unsigned char) *(fp->begin++) : hgetc2(fp);
129 }
130 
131 /// Read from the stream until the delimiter, up to a maximum length
132 /** @param buffer  The buffer into which bytes will be written
133     @param size    The size of the buffer
134     @param delim   The delimiter (interpreted as an `unsigned char`)
135     @param fp      The file stream
136     @return  The number of bytes read, or negative on error.
137     @since   1.4
138 
139 Bytes will be read into the buffer up to and including a delimiter, until
140 EOF is reached, or _size-1_ bytes have been written, whichever comes first.
141 The string will then be terminated with a NUL byte (`\0`).
142 */
143 ssize_t hgetdelim(char *buffer, size_t size, int delim, hFILE *fp)
144     HTS_RESULT_USED;
145 
146 /// Read a line from the stream, up to a maximum length
147 /** @param buffer  The buffer into which bytes will be written
148     @param size    The size of the buffer
149     @param fp      The file stream
150     @return  The number of bytes read, or negative on error.
151     @since   1.4
152 
153 Specialization of hgetdelim() for a `\n` delimiter.
154 */
155 static inline ssize_t HTS_RESULT_USED
hgetln(char * buffer,size_t size,hFILE * fp)156 hgetln(char *buffer, size_t size, hFILE *fp)
157 {
158     return hgetdelim(buffer, size, '\n', fp);
159 }
160 
161 /// Read a line from the stream, up to a maximum length
162 /** @param buffer  The buffer into which bytes will be written
163     @param size    The size of the buffer (must be > 1 to be useful)
164     @param fp      The file stream
165     @return  _buffer_ on success, or `NULL` if an error occurred.
166     @since   1.4
167 
168 This function can be used as a replacement for `fgets(3)`, or together with
169 kstring's `kgetline()` to read arbitrarily-long lines into a _kstring_t_.
170 */
171 char *hgets(char *buffer, int size, hFILE *fp) HTS_RESULT_USED;
172 
173 /// Peek at characters to be read without removing them from buffers
174 /** @param fp      The file stream
175     @param buffer  The buffer to which the peeked bytes will be written
176     @param nbytes  The number of bytes to peek at; limited by the size of the
177                    internal buffer, which could be as small as 4K.
178     @return  The number of bytes peeked, which may be less than _nbytes_
179              if EOF is encountered; or negative, if there was an I/O error.
180 
181 The characters peeked at remain in the stream's internal buffer, and will be
182 returned by later hread() etc calls.
183 */
184 ssize_t hpeek(hFILE *fp, void *buffer, size_t nbytes) HTS_RESULT_USED;
185 
186 /// Read a block of characters from the file
187 /** @return  The number of bytes read, or negative if an error occurred.
188 
189 The full _nbytes_ requested will be returned, except as limited by EOF
190 or I/O errors.
191 */
192 static inline ssize_t HTS_RESULT_USED
hread(hFILE * fp,void * buffer,size_t nbytes)193 hread(hFILE *fp, void *buffer, size_t nbytes)
194 {
195     extern ssize_t hread2(hFILE *, void *, size_t, size_t);
196 
197     size_t n = fp->end - fp->begin;
198     if (n > nbytes) n = nbytes;
199     memcpy(buffer, fp->begin, n);
200     fp->begin += n;
201     return (n == nbytes)? (ssize_t) n : hread2(fp, buffer, nbytes, n);
202 }
203 
204 /// Write a character to the stream
205 /** @return  The character written, or `EOF` if an error occurred.
206 */
hputc(int c,hFILE * fp)207 static inline int hputc(int c, hFILE *fp)
208 {
209     extern int hputc2(int, hFILE *);
210     if (fp->begin < fp->limit) *(fp->begin++) = c;
211     else c = hputc2(c, fp);
212     return c;
213 }
214 
215 /// Write a string to the stream
216 /** @return  0 if successful, or `EOF` if an error occurred.
217 */
hputs(const char * text,hFILE * fp)218 static inline int hputs(const char *text, hFILE *fp)
219 {
220     extern int hputs2(const char *, size_t, size_t, hFILE *);
221 
222     size_t nbytes = strlen(text), n = fp->limit - fp->begin;
223     if (n > nbytes) n = nbytes;
224     memcpy(fp->begin, text, n);
225     fp->begin += n;
226     return (n == nbytes)? 0 : hputs2(text, nbytes, n, fp);
227 }
228 
229 /// Write a block of characters to the file
230 /** @return  Either _nbytes_, or negative if an error occurred.
231 
232 In the absence of I/O errors, the full _nbytes_ will be written.
233 */
234 static inline ssize_t HTS_RESULT_USED
hwrite(hFILE * fp,const void * buffer,size_t nbytes)235 hwrite(hFILE *fp, const void *buffer, size_t nbytes)
236 {
237     extern ssize_t hwrite2(hFILE *, const void *, size_t, size_t);
238 
239     size_t n = fp->limit - fp->begin;
240     if (n > nbytes) n = nbytes;
241     memcpy(fp->begin, buffer, n);
242     fp->begin += n;
243     return (n==nbytes)? (ssize_t) n : hwrite2(fp, buffer, nbytes, n);
244 }
245 
246 /// For writing streams, flush buffered output to the underlying stream
247 /** @return  0 if successful, or `EOF` if an error occurred.
248 
249 This includes low-level flushing such as via `fdatasync(2)`.
250 */
251 int hflush(hFILE *fp) HTS_RESULT_USED;
252 
253 #ifdef __cplusplus
254 }
255 #endif
256 
257 #endif
258