1 // htslib-1.9 bgzf.h as D module
2 // Changes include:
3 // Removed if(n)defs
4 // Changed #defines to const/immutable
5 // Removed all HTS_RESULT_USED (__attribute__ ((__warn_unused_result__)))
6 // HTS_DEPRECATED(message) to deprecated("message")
7 // Do not #include "hts_defs.h"
8 // Change numeric #defines to enum int
9 // typedef struct to alias
10 // modified bitfields in struct and aligned(1)
11 // removed redundant struct declarations when declaring struct pointers
12 // replace local definition with import kstring_t
13 // const TYPE * to const(TYPE) *
14 module dhtslib.htslib.bgzf;
15 
16 import std.bitmanip;
17 
18 extern (C):
19 
20 // @file htslib/bgzf.h
21 // Low-level routines for direct BGZF operations.
22 /*
23    Copyright (c) 2008 Broad Institute / Massachusetts Institute of Technology
24                  2011, 2012 Attractive Chaos <attractor@live.co.uk>
25    Copyright (C) 2009, 2013, 2014,2017 Genome Research Ltd
26 
27    Permission is hereby granted, free of charge, to any person obtaining a copy
28    of this software and associated documentation files (the "Software"), to deal
29    in the Software without restriction, including without limitation the rights
30    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
31    copies of the Software, and to permit persons to whom the Software is
32    furnished to do so, subject to the following conditions:
33 
34    The above copyright notice and this permission notice shall be included in
35    all copies or substantial portions of the Software.
36 
37    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
38    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
39    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
40    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
41    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
42    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
43    THE SOFTWARE.
44 */
45 
46 /* The BGZF library was originally written by Bob Handsaker from the Broad
47  * Institute. It was later improved by the SAMtools developers. */
48 
49 import core.stdc.stdint;
50 import core.stdc.stdio;
51 import etc.c.zlib;
52 import core.sys.posix.sys.types;
53 
54 // ssize_t doesn't exist in core.sys.posix.sys.types for windows builds
55 version(Windows){
56     version(Win32){
57         alias ssize_t = int;
58     }
59     version(Win64){
60         alias ssize_t = long;
61     }
62 }
63 
64 enum int BGZF_BLOCK_SIZE =     0xff00;  /// make sure compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE
65 enum int BGZF_MAX_BLOCK_SIZE = 0x10000; /// ditto
66 
67 enum int BGZF_ERR_ZLIB   = 1;   /// zlib error
68 enum int BGZF_ERR_HEADER = 2;   /// header format error
69 enum int BGZF_ERR_IO     = 4;   /// io error
70 enum int BGZF_ERR_MISUSE = 8;   /// misuse error: (a) writeable file (b) where not SEEK_SET (c) GZ (rather than BGZ) file
71 enum int BGZF_ERR_MT     = 16;  /// stream cannot be multi-threaded
72 enum int BGZF_ERR_CRC    = 32;  /// returned by inflate_block() when bgzf_uncompress() has CRC error
73 
74 /// see hts.d
75 struct hFILE; // @suppress(dscanner.style.phobos_naming_convention)
76 /// see thread_pool.d
77 struct hts_tpool; // @suppress(dscanner.style.phobos_naming_convention)
78 /// Memory pool for bgzf_job structs, to avoid many malloc/free, see htslib/bgzf.c
79 struct bgzf_mtaux_t; // @suppress(dscanner.style.phobos_naming_convention)
80 /// BGZF index
81 struct __bgzidx_t; // @suppress(dscanner.style.phobos_naming_convention)
82 alias bgzidx_t = __bgzidx_t;
83 /// bgzf cache
84 struct bgzf_cache_t; // @suppress(dscanner.style.phobos_naming_convention)
85 
86 /// Block Gzipped File
87 struct BGZF {
88     // Reserved bits should be written as 0; read as "don't care"
89     //unsigned errcode:16, reserved:1, is_write:1, no_eof_block:1, is_be:1;
90     //signed compress_level:9;
91     //unsigned last_block_eof:1, is_compressed:1, is_gzip:1;
92     mixin(bitfields!(
93         uint, "errcode", 16,
94         bool, "reserved", 1,
95         bool, "is_write", 1,
96         bool, "no_eof_block", 1,
97         bool, "is_be", 1,
98         int, "compress_level", 9,
99         bool, "last_block_eof", 1,
100         bool, "is_compressed",  1,
101         bool, "is_gzip",        1));
102     int cache_size;     /// cache size in bytes
103     int block_length;   /// ?
104     int block_clength;  /// ?
105     int block_offset;   /// ?
106     int64_t block_address;  /// ?
107     int64_t uncompressed_address; /// ?
108     void *uncompressed_block;   /// data ptr
109     void *compressed_block;     /// data ptr
110     bgzf_cache_t *cache;/// cache
111     hFILE *fp;          /// actual file handle
112     bgzf_mtaux_t *mt;   /// only used for multi-threading
113     bgzidx_t *idx;      /// BGZF index
114     int idx_build_otf;  /// build index on the fly, set by bgzf_index_build_init()
115     z_stream *gz_stream;/// for gzip-compressed files
116 }
117 
118 import dhtslib.htslib.kstring: __kstring_t, kstring_t;
119 
120     /******************
121      * Basic routines *
122      ******************/
123 
124     /**
125      * Open an existing file descriptor for reading or writing.
126      *
127      * @param fd    file descriptor
128      *              Note that the file must be opened in binary mode, or else
129      *              there will be problems on platforms that make a difference
130      *              between text and binary mode.
131      * @param mode  mode matching /[rwag][u0-9]+/: 'r' for reading, 'w' for
132      *              writing, 'a' for appending, 'g' for gzip rather than BGZF
133      *              compression (with 'w' only), and digit specifies the zlib
134      *              compression level.
135      *              Note that there is a distinction between 'u' and '0': the
136      *              first yields plain uncompressed output whereas the latter
137      *              outputs uncompressed data wrapped in the zlib format.
138      * @return      BGZF file handler; 0 on error
139      */
140     BGZF* bgzf_dopen(int fd, const(char) *mode);
141 
142     /// ditto
143     pragma(inline, true)
144     BGZF* bgzf_fdopen(int fd, const(char) *mode) { return bgzf_dopen(fd, mode); }    // for backward compatibility
145     
146     /**
147      * Open the specified file for reading or writing.
148      */
149     BGZF* bgzf_open(const(char)* path, const(char) *mode);
150 
151     /**
152      * Open an existing hFILE stream for reading or writing.
153      */
154     BGZF* bgzf_hopen(hFILE *fp, const(char) *mode);
155 
156     /**
157      * Close the BGZF and free all associated resources.
158      *
159      * @param fp    BGZF file handler
160      * @return      0 on success and -1 on error
161      */
162     int bgzf_close(BGZF *fp);
163 
164     /**
165      * Read up to _length_ bytes from the file storing into _data_.
166      *
167      * @param fp     BGZF file handler
168      * @param data   data array to read into
169      * @param length size of data to read
170      * @return       number of bytes actually read; 0 on end-of-file and -1 on error
171      */
172     ssize_t bgzf_read(BGZF *fp, void *data, size_t length);
173 
174     /**
175      * Write _length_ bytes from _data_ to the file.  If no I/O errors occur,
176      * the complete _length_ bytes will be written (or queued for writing).
177      *
178      * @param fp     BGZF file handler
179      * @param data   data array to write
180      * @param length size of data to write
181      * @return       number of bytes written (i.e., _length_); negative on error
182      */
183     ssize_t bgzf_write(BGZF *fp, const(void) *data, size_t length);
184 
185     /**
186      * Write _length_ bytes from _data_ to the file, the index will be used to
187      * decide the amount of uncompressed data to be writen to each bgzip block.
188      * If no I/O errors occur, the complete _length_ bytes will be written (or
189      * queued for writing).
190      * @param fp     BGZF file handler
191      * @param data   data array to write
192      * @param length size of data to write
193      * @return       number of bytes written (i.e., _length_); negative on error
194      */
195     ssize_t bgzf_block_write(BGZF *fp, const(void) *data, size_t length);
196 
197     /**
198      * Read up to _length_ bytes directly from the underlying stream without
199      * decompressing.  Bypasses BGZF blocking, so must be used with care in
200      * specialised circumstances only.
201      *
202      * @param fp     BGZF file handler
203      * @param data   data array to read into
204      * @param length number of raw bytes to read
205      * @return       number of bytes actually read; 0 on end-of-file and -1 on error
206      */
207     ssize_t bgzf_raw_read(BGZF *fp, void *data, size_t length);
208 
209     /**
210      * Write _length_ bytes directly to the underlying stream without
211      * compressing.  Bypasses BGZF blocking, so must be used with care
212      * in specialised circumstances only.
213      *
214      * @param fp     BGZF file handler
215      * @param data   data array to write
216      * @param length number of raw bytes to write
217      * @return       number of bytes actually written; -1 on error
218      */
219     ssize_t bgzf_raw_write(BGZF *fp, const(void) *data, size_t length);
220 
221     /**
222      * Write the data in the buffer to the file.
223      *
224      * @param fp     BGZF file handle
225      * @return       0 on success and -1 on error
226      */
227     int bgzf_flush(BGZF *fp);
228 
229     /**
230      * Return a virtual file pointer to the current location in the file.
231      * No interpretation of the value should be made, other than a subsequent
232      * call to bgzf_seek can be used to position the file at the same point.
233      * Return value is non-negative on success.
234      */
235     pragma(inline, true)
236     ulong bgzf_tell(BGZF *fp) { return ((*fp).block_address << 16) | ((*fp).block_offset & 0xFFFF); }
237     
238     /**
239      * Set the file to read from the location specified by _pos_.
240      *
241      * @param fp     BGZF file handler
242      * @param pos    virtual file offset returned by bgzf_tell()
243      * @param whence must be SEEK_SET
244      * @return       0 on success and -1 on error
245      */
246     int64_t bgzf_seek(BGZF *fp, int64_t pos, int whence);
247 
248     /**
249      * Check if the BGZF end-of-file (EOF) marker is present
250      *
251      * @param fp    BGZF file handler opened for reading
252      * @return      1 if the EOF marker is present and correct;
253      *              2 if it can't be checked, e.g., because fp isn't seekable;
254      *              0 if the EOF marker is absent;
255      *              -1 (with errno set) on error
256      */
257     int bgzf_check_EOF(BGZF *fp);
258 
259     /** Return the file's compression format
260      *
261      * @param fp  BGZF file handle
262      * @return    A small integer matching the corresponding
263      *            `enum htsCompression` value:
264      *   - 0 / `no_compression` if the file is uncompressed
265      *   - 1 / `gzip` if the file is plain GZIP-compressed
266      *   - 2 / `bgzf` if the file is BGZF-compressed
267      * @since 1.4
268      */
269     int bgzf_compression(BGZF *fp);
270 
271     /**
272      * Check if a file is in the BGZF format
273      *
274      * @param fn    file name
275      * @return      1 if _fn_ is BGZF; 0 if not or on I/O error
276      */
277     deprecated("Use bgzf_compression() or hts_detect_format() instead")
278     int bgzf_is_bgzf(const(char) *fn);
279 
280     /*********************
281      * Advanced routines *
282      *********************/
283 
284     /**
285      * Set the cache size. Only effective when compiled with -DBGZF_CACHE.
286      *
287      * @param fp    BGZF file handler
288      * @param size  size of cache in bytes; 0 to disable caching (default)
289      */
290     void bgzf_set_cache_size(BGZF *fp, int size);
291 
292     /**
293      * Flush the file if the remaining buffer size is smaller than _size_
294      * @return      0 if flushing succeeded or was not needed; negative on error
295      */
296     int bgzf_flush_try(BGZF *fp, ssize_t size);
297 
298     /**
299      * Read one byte from a BGZF file. It is faster than bgzf_read()
300      * @param fp     BGZF file handler
301      * @return       byte read; -1 on end-of-file or error
302      */
303     int bgzf_getc(BGZF *fp);
304 
305     /**
306      * Read one line from a BGZF file. It is faster than bgzf_getc()
307      *
308      * @param fp     BGZF file handler
309      * @param delim  delimitor
310      * @param str    string to write to; must be initialized
311      * @return       length of the string; -1 on end-of-file; <= -2 on error
312      */
313     int bgzf_getline(BGZF *fp, int delim, kstring_t *str);
314 
315     /**
316      * Read the next BGZF block.
317      */
318     int bgzf_read_block(BGZF *fp);
319 
320     /**
321      * Enable multi-threading (when compiled with -DBGZF_MT) via a shared
322      * thread pool.  This means both encoder and decoder can balance
323      * usage across a single pool of worker jobs.
324      *
325      * @param fp          BGZF file handler; must be opened for writing
326      * @param pool        The thread pool (see hts_create_threads)
327      */
328     int bgzf_thread_pool(BGZF *fp, hts_tpool *pool, int qsize);
329 
330     /**
331      * Enable multi-threading (only effective when the library was compiled
332      * with -DBGZF_MT)
333      *
334      * @param fp          BGZF file handler; must be opened for writing
335      * @param n_threads   #threads used for writing
336      * @param n_sub_blks  #blocks processed by each thread; a value 64-256 is recommended
337      */
338     int bgzf_mt(BGZF *fp, int n_threads, int n_sub_blks);
339 
340     /**
341      * Compress a single BGZF block.
342      *
343      * @param dst    output buffer (must have size >= BGZF_MAX_BLOCK_SIZE)
344      * @param dlen   size of output buffer; updated on return to the number
345      *               of bytes actually written to dst
346      * @param src    buffer to be compressed
347      * @param slen   size of data to compress (must be <= BGZF_BLOCK_SIZE)
348      * @param level  compression level
349      * @return       0 on success and negative on error
350      */
351     int bgzf_compress(void *dst, size_t *dlen, const(void) *src, size_t slen, int level);
352 
353     /*******************
354      * bgzidx routines *
355      *******************/
356 
357     /**
358      *  Position BGZF at the uncompressed offset
359      *
360      *  @param fp           BGZF file handler; must be opened for reading
361      *  @param uoffset      file offset in the uncompressed data
362      *  @param where        SEEK_SET supported atm
363      *
364      *  Returns 0 on success and -1 on error.
365      */
366     int bgzf_useek(BGZF *fp, long uoffset, int where);
367 
368     /**
369      *  Position in uncompressed BGZF
370      *
371      *  @param fp           BGZF file handler; must be opened for reading
372      *
373      *  Returns the current offset on success and -1 on error.
374      */
375     long bgzf_utell(BGZF *fp);
376 
377     /**
378      * Tell BGZF to build index while compressing.
379      *
380      * @param fp          BGZF file handler; can be opened for reading or writing.
381      *
382      * Returns 0 on success and -1 on error.
383      */
384     int bgzf_index_build_init(BGZF *fp);
385 
386     /// Load BGZF index
387     /**
388      * @param fp          BGZF file handler
389      * @param bname       base name
390      * @param suffix      suffix to add to bname (can be NULL)
391      * @return 0 on success and -1 on error.
392      */
393     int bgzf_index_load(BGZF *fp,
394                         const(char) *bname, const(char) *suffix);
395 
396     /// Load BGZF index from an hFILE
397     /**
398      * @param fp   BGZF file handle
399      * @param idx  hFILE to read from
400      * @param name file name (for error reporting only; can be NULL)
401      * @return 0 on success and -1 on error.
402      *
403      * Populates @p fp with index data read from the hFILE handle @p idx.
404      * The file pointer to @idx should point to the start of the index
405      * data when this function is called.
406      *
407      * The file name can optionally be passed in the @p name parameter.  This
408      * is only used for printing error messages; if NULL the word "index" is
409      * used instead.
410      */
411     int bgzf_index_load_hfile(BGZF *fp, hFILE *idx,
412                               const(char) *name);
413 
414     /// Save BGZF index
415     /**
416      * @param fp          BGZF file handler
417      * @param bname       base name
418      * @param suffix      suffix to add to bname (can be NULL)
419      * @return 0 on success and -1 on error.
420      */
421     int bgzf_index_dump(BGZF *fp,
422                         const(char) *bname, const(char) *suffix);
423 
424     /// Write a BGZF index to an hFILE
425     /**
426      * @param fp     BGZF file handle
427      * @param idx    hFILE to write to
428      * @param name   file name (for error reporting only, can be NULL)
429      * @return 0 on success and -1 on error.
430      *
431      * Write index data from @p fp to the file @p idx.
432      *
433      * The file name can optionally be passed in the @p name parameter.  This
434      * is only used for printing error messages; if NULL the word "index" is
435      * used instead.
436      */
437 
438     int bgzf_index_dump_hfile(BGZF *fp, hFILE *idx,
439                               const(char) *name);