Coverage Report

Created: 2026-10-10 06:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/htslib/faidx.c
Line
Count
Source
1
/*  faidx.c -- FASTA and FASTQ random access.
2
3
    Copyright (C) 2008, 2009, 2013-2020, 2022, 2024, 2026 Genome Research Ltd.
4
    Portions copyright (C) 2011 Broad Institute.
5
6
    Author: Heng Li <lh3@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
#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
27
#include <config.h>
28
29
#include <ctype.h>
30
#include <string.h>
31
#include <stdlib.h>
32
#include <stdio.h>
33
#include <inttypes.h>
34
#include <errno.h>
35
#include <limits.h>
36
#include <unistd.h>
37
#include <assert.h>
38
39
#include "htslib/bgzf.h"
40
#include "htslib/faidx.h"
41
#include "htslib/hfile.h"
42
#include "htslib/hts_alloc.h"
43
#include "htslib/khash.h"
44
#include "htslib/kstring.h"
45
#include "hts_internal.h"
46
47
// Faster isgraph; assumes ASCII
48
3.52M
static inline int isgraph_(unsigned char c) {
49
3.52M
    return c > ' ' && c <= '~';
50
3.52M
}
51
52
#ifdef isgraph
53
#  undef isgraph
54
#endif
55
3.52M
#define isgraph isgraph_
56
57
// An optimised bgzf_getc.
58
// We could consider moving this to bgzf.h, but our own code uses it here only.
59
14.2M
static inline int bgzf_getc_(BGZF *fp) {
60
14.2M
    if (fp->block_offset+1 < fp->block_length) {
61
14.2M
        int c = ((unsigned char*)fp->uncompressed_block)[fp->block_offset++];
62
14.2M
        fp->uncompressed_address++;
63
14.2M
        return c;
64
14.2M
    }
65
66
3.19k
    return bgzf_getc(fp);
67
14.2M
}
68
14.2M
#define bgzf_getc bgzf_getc_
69
70
typedef struct {
71
    int id; // faidx_t->name[id] is for this struct.
72
    uint32_t line_extra;  // Bytes to skip at the end of each line
73
                          // Usually 1 for \n or 2 for \r\n ending
74
    uint64_t line_blen;   // Number of bases (or quality values) on each line
75
                          // Total line length = line_blen + line_extra
76
    uint64_t len;         // Length of entire sequence
77
    uint64_t seq_offset;  // File offset to start of sequence
78
    uint64_t qual_offset; // File offset to start of quality values (if fastq)
79
} faidx1_t;
80
0
KHASH_MAP_INIT_STR(s, faidx1_t)
81
0
82
0
struct faidx_t {
83
0
    BGZF *bgzf;
84
0
    uint32_t n, m;
85
0
    char **name;
86
0
    khash_t(s) *hash;
87
0
    enum fai_format_options format;
88
0
};
89
0
90
0
static int fai_name2id(void *v, const char *ref)
91
0
{
92
0
    faidx_t *fai = (faidx_t *)v;
93
0
    khint_t k = kh_get(s, fai->hash, ref);
94
0
    return k == kh_end(fai->hash) ? -1 : kh_val(fai->hash, k).id;
95
0
}
96
97
static inline int fai_insert_index(faidx_t *idx, const char *name, uint64_t len, uint64_t line_len, uint64_t line_blen, uint64_t seq_offset, uint64_t qual_offset)
98
28.7k
{
99
28.7k
    if (!name) {
100
0
        hts_log_error("Malformed line: no name");
101
0
        return -1;
102
0
    }
103
28.7k
    if (line_len > HTS_POS_MAX || line_blen > HTS_POS_MAX) {
104
0
        hts_log_error("Malformed line: length out of bounds");
105
0
        return -1;
106
0
    }
107
28.7k
    if (line_len < line_blen) {
108
0
        hts_log_error("Malformed line: width (%"PRIu64") less than base count (%"PRIu64")",
109
0
                      line_len, line_blen);
110
0
        return -1;
111
0
    }
112
28.7k
    if (line_len - line_blen > UINT32_MAX) {
113
0
        hts_log_error("Malformed line: difference between width (%"PRIu64") and base count (%"PRIu64") too large",
114
0
                      line_len, line_blen);
115
0
        return -1;
116
0
    }
117
118
28.7k
    if (idx->n == idx->m) {
119
643
        char **tmp;
120
643
        uint32_t new_m = idx->m ? idx->m << 1 : 16;
121
643
        if (new_m < idx->m
122
643
            || !(tmp = hts_realloc_p(idx->name, sizeof(char*), new_m))) {
123
0
            hts_log_error("Out of memory");
124
0
            return -1;
125
0
        }
126
643
        idx->m = new_m;
127
643
        idx->name = tmp;
128
643
    }
129
130
28.7k
    char *name_key = strdup(name);
131
28.7k
    if (!name_key) {
132
0
        hts_log_error("Couldn't duplicate name: %s", strerror(errno));
133
0
        return -1;
134
0
    }
135
136
28.7k
    int absent;
137
28.7k
    khint_t k = kh_put(s, idx->hash, name_key, &absent);
138
28.7k
    if (absent < 0) {
139
0
        hts_log_error("Couldn't add name to hash table: %s", strerror(errno));
140
0
        free(name_key);
141
0
        return -1;
142
0
    }
143
28.7k
    if (! absent) {
144
23.5k
        hts_log_warning("Ignoring duplicate sequence \"%s\" at byte offset %" PRIu64, name, seq_offset);
145
23.5k
        free(name_key);
146
23.5k
        return 0;
147
23.5k
    }
148
5.18k
    faidx1_t *v = &kh_value(idx->hash, k);
149
150
5.18k
    v->id = idx->n;
151
5.18k
    idx->name[idx->n++] = name_key;
152
5.18k
    v->len = len;
153
5.18k
    v->line_extra = (uint32_t) (line_len - line_blen);
154
5.18k
    v->line_blen = line_blen;
155
5.18k
    v->seq_offset = seq_offset;
156
5.18k
    v->qual_offset = qual_offset;
157
158
5.18k
    return 0;
159
28.7k
}
160
161
162
1.01k
static faidx_t *fai_build_core(BGZF *bgzf) {
163
1.01k
    kstring_t name = { 0, 0, NULL };
164
1.01k
    int c, read_done, line_num;
165
1.01k
    faidx_t *idx;
166
1.01k
    uint64_t seq_offset, qual_offset;
167
1.01k
    uint64_t seq_len, qual_len;
168
1.01k
    uint64_t char_len, cl, line_len, ll;
169
1.01k
    enum read_state {OUT_READ, IN_NAME, IN_SEQ, SEQ_END, IN_QUAL} state;
170
171
1.01k
    idx = (faidx_t*)calloc(1, sizeof(faidx_t));
172
1.01k
    idx->hash = kh_init(s);
173
1.01k
    idx->format = FAI_NONE;
174
175
1.01k
    state = OUT_READ, read_done = 0, line_num = 1;
176
1.01k
    seq_offset = qual_offset = seq_len = qual_len = char_len = cl = line_len = ll = 0;
177
178
129k
    while ((c = bgzf_getc(bgzf)) >= 0) {
179
129k
        switch (state) {
180
7.78k
            case OUT_READ:
181
7.78k
                switch (c) {
182
6.26k
                    case '>':
183
6.26k
                        if (idx->format == FAI_FASTQ) {
184
11
                            hts_log_error("Found '>' in a FASTQ file, error at line %d", line_num);
185
11
                            goto fail;
186
11
                        }
187
188
6.25k
                        idx->format = FAI_FASTA;
189
6.25k
                        state = IN_NAME;
190
6.25k
                    break;
191
192
408
                    case '@':
193
408
                        if (idx->format == FAI_FASTA) {
194
10
                            hts_log_error("Found '@' in a FASTA file, error at line %d", line_num);
195
10
                            goto fail;
196
10
                        }
197
198
398
                        idx->format = FAI_FASTQ;
199
398
                        state = IN_NAME;
200
398
                    break;
201
202
630
                    case '\r':
203
                        // Blank line with cr-lf ending?
204
630
                        if ((c = bgzf_getc(bgzf)) == '\n') {
205
613
                            line_num++;
206
613
                        } else {
207
17
                            hts_log_error("Format error, carriage return not followed by new line at line %d", line_num);
208
17
                            goto fail;
209
17
                        }
210
613
                    break;
211
212
613
                    case '\n':
213
                        // just move onto the next line
214
392
                        line_num++;
215
392
                    break;
216
217
97
                    default: {
218
97
                        char s[4] = { '"', c, '"', '\0' };
219
97
                        hts_log_error("Format error, unexpected %s at line %d", isprint(c) ? s : "character", line_num);
220
97
                        goto fail;
221
630
                    }
222
7.78k
                }
223
7.65k
            break;
224
225
45.5k
            case IN_NAME:
226
45.5k
                if (read_done) {
227
28.5k
                    if (fai_insert_index(idx, name.s, seq_len, line_len, char_len, seq_offset, qual_offset) != 0)
228
0
                        goto fail;
229
230
28.5k
                    read_done = 0;
231
28.5k
                }
232
233
45.5k
                name.l = 0;
234
235
7.23M
                do {
236
7.23M
                    if (!isspace(c)) {
237
7.18M
                        if (kputc_(c, &name) < 0)
238
0
                            goto fail;
239
7.18M
                    } else if (name.l > 0 || c == '\n') {
240
45.2k
                        break;
241
45.2k
                    }
242
7.23M
                } while ((c = bgzf_getc(bgzf)) >= 0);
243
244
45.5k
                if (kputsn("", 0, &name) < 0)
245
0
                    goto fail;
246
247
45.5k
                if (c < 0) {
248
305
                    hts_log_error("The last entry '%s' has no sequence at line %d", name.s, line_num);
249
305
                    goto fail;
250
305
                }
251
252
                // read the rest of the line if necessary
253
172k
                if (c != '\n') while ((c = bgzf_getc(bgzf)) >= 0 && c != '\n');
254
255
45.2k
                state = IN_SEQ; seq_len = qual_len = char_len = line_len = 0;
256
45.2k
                seq_offset = bgzf_utell(bgzf);
257
45.2k
                line_num++;
258
45.2k
            break;
259
260
74.3k
            case IN_SEQ:
261
74.3k
                if (idx->format == FAI_FASTA) {
262
73.2k
                    if (c == '\n') {
263
1.19k
                        state = OUT_READ;
264
1.19k
                        line_num++;
265
1.19k
                        continue;
266
72.0k
                    } else if (c == '>') {
267
38.7k
                        state = IN_NAME;
268
38.7k
                        continue;
269
38.7k
                    }
270
73.2k
                } else if (idx->format == FAI_FASTQ) {
271
1.06k
                    if (c == '+') {
272
70
                        state = IN_QUAL;
273
1.61M
                        if (c != '\n') while ((c = bgzf_getc(bgzf)) >= 0 && c != '\n');
274
70
                        qual_offset = bgzf_utell(bgzf);
275
70
                        line_num++;
276
70
                        continue;
277
995
                    } else if (c == '\n') {
278
17
                        hts_log_error("Inlined empty line is not allowed in sequence '%s' at line %d", name.s, line_num);
279
17
                        goto fail;
280
17
                    }
281
1.06k
                }
282
283
34.3k
                ll = cl = 0;
284
285
34.3k
                if (idx->format == FAI_FASTA) read_done = 1;
286
287
3.00M
                do {
288
3.00M
                    ll++;
289
3.00M
                    if (isgraph(c)) cl++;
290
3.00M
                } while ((c = bgzf_getc(bgzf)) >= 0 && c != '\n');
291
292
34.3k
                ll++; seq_len += cl;
293
294
34.3k
                if (line_len == 0) {
295
29.0k
                    line_len = ll;
296
29.0k
                    char_len = cl;
297
29.0k
                } else if (line_len > ll) {
298
299
5.02k
                    if (idx->format == FAI_FASTA)
300
4.60k
                        state = OUT_READ;
301
419
                    else
302
419
                        state = SEQ_END;
303
304
5.02k
                } else if (line_len < ll) {
305
45
                    hts_log_error("Different line length in sequence '%s' at line %d", name.s, line_num);
306
45
                    goto fail;
307
45
                }
308
309
34.2k
                line_num++;
310
34.2k
            break;
311
312
384
            case SEQ_END:
313
384
                if (c == '+') {
314
373
                    state = IN_QUAL;
315
1.66M
                    while ((c = bgzf_getc(bgzf)) >= 0 && c != '\n');
316
373
                    qual_offset = bgzf_utell(bgzf);
317
373
                    line_num++;
318
373
                } else {
319
11
                    hts_log_error("Format error, expecting '+', got '%c' at line %d", c, line_num);
320
11
                    goto fail;
321
11
                }
322
373
            break;
323
324
919
            case IN_QUAL:
325
919
                if (c == '\n') {
326
23
                    if (!read_done) {
327
12
                        hts_log_error("Inlined empty line is not allowed in quality of sequence '%s' at line %d", name.s, line_num);
328
12
                        goto fail;
329
12
                    }
330
331
11
                    state = OUT_READ;
332
11
                    line_num++;
333
11
                    continue;
334
896
                } else if (c == '@' && read_done) {
335
228
                    state = IN_NAME;
336
228
                    continue;
337
228
                }
338
339
668
                ll = cl = 0;
340
341
517k
                do {
342
517k
                    ll++;
343
517k
                    if (isgraph(c)) cl++;
344
517k
                } while ((c = bgzf_getc(bgzf)) >= 0 && c != '\n');
345
346
668
                ll++; qual_len += cl;
347
348
668
                if (line_len < ll) {
349
53
                    hts_log_error("Quality line length too long in '%s' at line %d", name.s, line_num);
350
53
                    goto fail;
351
615
                } else if (qual_len == seq_len) {
352
273
                    read_done = 1;
353
342
                } else if (qual_len > seq_len) {
354
30
                    hts_log_error("Quality length longer than sequence in '%s' at line %d", name.s, line_num);
355
30
                    goto fail;
356
312
                } else if (line_len > ll) {
357
18
                    hts_log_error("Quality line length too short in '%s' at line %d", name.s, line_num);
358
18
                    goto fail;
359
18
                }
360
361
567
                line_num++;
362
567
            break;
363
129k
        }
364
129k
    }
365
366
392
    if (read_done) {
367
187
        if (fai_insert_index(idx, name.s, seq_len, line_len, char_len, seq_offset, qual_offset) != 0)
368
0
            goto fail;
369
205
    } else {
370
205
        hts_log_error("File truncated at line %d", line_num);
371
205
        goto fail;
372
205
    }
373
374
187
    free(name.s);
375
187
    return idx;
376
377
831
fail:
378
831
    free(name.s);
379
831
    fai_destroy(idx);
380
831
    return NULL;
381
392
}
382
383
384
0
static int fai_save(const faidx_t *fai, hFILE *fp) {
385
0
    khint_t k;
386
0
    int i;
387
0
    char buf[96]; // Must be big enough for format below.
388
389
0
    for (i = 0; i < fai->n; ++i) {
390
0
        faidx1_t x;
391
0
        k = kh_get(s, fai->hash, fai->name[i]);
392
0
        assert(k < kh_end(fai->hash));
393
0
        x = kh_value(fai->hash, k);
394
395
0
        if (fai->format == FAI_FASTA) {
396
0
            snprintf(buf, sizeof(buf),
397
0
                 "\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\n",
398
0
                 x.len, x.seq_offset, x.line_blen, x.line_blen + x.line_extra);
399
0
        } else {
400
0
            snprintf(buf, sizeof(buf),
401
0
                 "\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\t%"PRIu64"\n",
402
0
                     x.len, x.seq_offset, x.line_blen,
403
0
                     x.line_blen + x.line_extra, x.qual_offset);
404
0
        }
405
406
0
        if (hputs(fai->name[i], fp) != 0) return -1;
407
0
        if (hputs(buf, fp) != 0) return -1;
408
0
    }
409
0
    return 0;
410
0
}
411
412
413
static faidx_t *fai_read(hFILE *fp, const char *fname, int format)
414
0
{
415
0
    faidx_t *fai;
416
0
    char *buf = NULL, *p;
417
0
    ssize_t l, lnum = 1;
418
419
0
    fai = (faidx_t*)calloc(1, sizeof(faidx_t));
420
0
    if (!fai) return NULL;
421
422
0
    fai->hash = kh_init(s);
423
0
    if (!fai->hash) goto fail;
424
425
0
    buf = (char*)calloc(0x10000, 1);
426
0
    if (!buf) goto fail;
427
428
0
    while ((l = hgetln(buf, 0x10000, fp)) > 0) {
429
0
        uint64_t line_len, line_blen;
430
0
        uint64_t len;
431
0
        uint64_t seq_offset;
432
0
        uint64_t qual_offset = 0;
433
0
        int n;
434
435
0
        for (p = buf; *p && !isspace_c(*p); ++p);
436
437
0
        if (p - buf < l) {
438
0
            *p = 0; ++p;
439
0
        }
440
441
0
        if (format == FAI_FASTA) {
442
0
            n = sscanf(p, "%"SCNu64"%"SCNu64"%"SCNu64"%"SCNu64, &len, &seq_offset, &line_blen, &line_len);
443
444
0
            if (n != 4) {
445
0
                hts_log_error("Could not understand FASTA index %s line %zd", fname, lnum);
446
0
                goto fail;
447
0
            }
448
0
        } else {
449
0
            n = sscanf(p, "%"SCNu64"%"SCNu64"%"SCNu64"%"SCNu64"%"SCNu64, &len, &seq_offset, &line_blen, &line_len, &qual_offset);
450
451
0
            if (n != 5) {
452
0
                if (n == 4) {
453
0
                    hts_log_error("Possibly this is a FASTA index, try using faidx.  Problem in %s line %zd", fname, lnum);
454
0
                } else {
455
0
                    hts_log_error("Could not understand FASTQ index %s line %zd", fname, lnum);
456
0
                }
457
458
0
                goto fail;
459
0
            }
460
0
        }
461
462
0
        if (fai_insert_index(fai, buf, len, line_len, line_blen, seq_offset, qual_offset) != 0) {
463
0
            goto fail;
464
0
        }
465
466
0
        if (buf[l - 1] == '\n') ++lnum;
467
0
    }
468
469
0
    if (l < 0) {
470
0
        hts_log_error("Error while reading %s: %s", fname, strerror(errno));
471
0
        goto fail;
472
0
    }
473
0
    free(buf);
474
0
    return fai;
475
476
0
 fail:
477
0
    free(buf);
478
0
    fai_destroy(fai);
479
0
    return NULL;
480
0
}
481
482
void fai_destroy(faidx_t *fai)
483
2.26k
{
484
2.26k
    int i;
485
2.26k
    if (!fai) return;
486
6.20k
    for (i = 0; i < fai->n; ++i) free(fai->name[i]);
487
1.01k
    free(fai->name);
488
1.01k
    kh_destroy(s, fai->hash);
489
1.01k
    if (fai->bgzf) bgzf_close(fai->bgzf);
490
1.01k
    free(fai);
491
1.01k
}
492
493
494
static int fai_build3_core(const char *fn, const char *fnfai, const char *fngzi)
495
1.43k
{
496
1.43k
    kstring_t fai_kstr = { 0, 0, NULL };
497
1.43k
    kstring_t gzi_kstr = { 0, 0, NULL };
498
1.43k
    BGZF *bgzf = NULL;
499
1.43k
    hFILE *fp = NULL;
500
1.43k
    faidx_t *fai = NULL;
501
1.43k
    int save_errno, res;
502
1.43k
    char *file_type;
503
504
1.43k
    bgzf = bgzf_open(fn, "r");
505
506
1.43k
    if ( !bgzf ) {
507
416
        hts_log_error("Failed to open the file %s : %s", fn, strerror(errno));
508
416
        goto fail;
509
416
    }
510
511
1.01k
    if ( bgzf->is_compressed ) {
512
9
        if (bgzf_index_build_init(bgzf) != 0) {
513
0
            hts_log_error("Failed to allocate bgzf index");
514
0
            goto fail;
515
0
        }
516
9
    }
517
518
1.01k
    fai = fai_build_core(bgzf);
519
520
1.01k
    if ( !fai ) {
521
831
        if (bgzf->is_compressed && bgzf->is_gzip) {
522
9
            hts_log_error("Cannot index files compressed with gzip, please use bgzip");
523
9
        }
524
831
        goto fail;
525
831
    }
526
527
187
    if (fai->format == FAI_FASTA) {
528
177
        file_type   = "FASTA";
529
177
    } else {
530
10
        file_type   = "FASTQ";
531
10
    }
532
533
187
    if (!fnfai) {
534
187
        if (ksprintf(&fai_kstr, "%s.fai", fn) < 0) goto fail;
535
187
        fnfai = fai_kstr.s;
536
187
    }
537
538
187
    if (!fngzi) {
539
187
        if (ksprintf(&gzi_kstr, "%s.gzi", fn) < 0) goto fail;
540
187
        fngzi = gzi_kstr.s;
541
187
    }
542
543
187
    if ( bgzf->is_compressed ) {
544
0
        if (bgzf_index_dump(bgzf, fngzi, NULL) < 0) {
545
0
            hts_log_error("Failed to make bgzf index %s", fngzi);
546
0
            goto fail;
547
0
        }
548
0
    }
549
550
187
    res = bgzf_close(bgzf);
551
187
    bgzf = NULL;
552
553
187
    if (res < 0) {
554
0
        hts_log_error("Error on closing %s : %s", fn, strerror(errno));
555
0
        goto fail;
556
0
    }
557
558
187
    fp = hopen(fnfai, "wb");
559
560
187
    if ( !fp ) {
561
187
        hts_log_error("Failed to open %s index %s : %s", file_type, fnfai, strerror(errno));
562
187
        goto fail;
563
187
    }
564
565
0
    if (fai_save(fai, fp) != 0) {
566
0
        hts_log_error("Failed to write %s index %s : %s", file_type, fnfai, strerror(errno));
567
0
        goto fail;
568
0
    }
569
570
0
    if (hclose(fp) != 0) {
571
0
        hts_log_error("Failed on closing %s index %s : %s", file_type, fnfai, strerror(errno));
572
0
        goto fail;
573
0
    }
574
575
0
    free(fai_kstr.s);
576
0
    free(gzi_kstr.s);
577
0
    fai_destroy(fai);
578
0
    return 0;
579
580
1.43k
 fail:
581
1.43k
    save_errno = errno;
582
1.43k
    free(fai_kstr.s);
583
1.43k
    free(gzi_kstr.s);
584
1.43k
    bgzf_close(bgzf);
585
1.43k
    fai_destroy(fai);
586
1.43k
    errno = save_errno;
587
1.43k
    return -1;
588
0
}
589
590
591
1.43k
int fai_build3(const char *fn, const char *fnfai, const char *fngzi) {
592
1.43k
    return fai_build3_core(fn, fnfai, fngzi);
593
1.43k
}
594
595
596
1.43k
int fai_build(const char *fn) {
597
1.43k
    return fai_build3(fn, NULL, NULL);
598
1.43k
}
599
600
601
static faidx_t *fai_load3_core(const char *fn, const char *fnfai, const char *fngzi,
602
                   int flags, int format)
603
0
{
604
0
    kstring_t fai_kstr = { 0, 0, NULL };
605
0
    kstring_t gzi_kstr = { 0, 0, NULL };
606
0
    hFILE *fp = NULL;
607
0
    faidx_t *fai = NULL;
608
0
    int res, gzi_index_needed = 0;
609
0
    char *file_type;
610
611
0
    if (format == FAI_FASTA) {
612
0
        file_type   = "FASTA";
613
0
    } else {
614
0
        file_type   = "FASTQ";
615
0
    }
616
617
0
    if (fn == NULL)
618
0
        return NULL;
619
620
0
    if (fnfai == NULL) {
621
0
        if (ksprintf(&fai_kstr, "%s.fai", fn) < 0) goto fail;
622
0
        fnfai = fai_kstr.s;
623
0
    }
624
0
    if (fngzi == NULL) {
625
0
        if (ksprintf(&gzi_kstr, "%s.gzi", fn) < 0) goto fail;
626
0
        fngzi = gzi_kstr.s;
627
0
    }
628
629
0
    fp = hopen(fnfai, "rb");
630
631
0
    if (fp) {
632
        // index file present, check if a compressed index is needed
633
0
        hFILE *gz = NULL;
634
0
        BGZF *bgzf = bgzf_open(fn, "rb");
635
636
0
        if (bgzf == 0) {
637
0
            hts_log_error("Failed to open %s file %s", file_type, fn);
638
0
            goto fail;
639
0
        }
640
641
0
        if (bgzf_compression(bgzf) == 2) { // BGZF compression
642
0
            if ((gz = hopen(fngzi, "rb")) == 0) {
643
644
0
                if (!(flags & FAI_CREATE) || errno != ENOENT) {
645
0
                    hts_log_error("Failed to open %s index %s: %s", file_type, fngzi, strerror(errno));
646
0
                    bgzf_close(bgzf);
647
0
                    goto fail;
648
0
                }
649
650
0
                gzi_index_needed = 1;
651
0
                res = hclose(fp); // closed as going to be re-indexed
652
653
0
                if (res < 0) {
654
0
                    hts_log_error("Failed on closing %s index %s : %s", file_type, fnfai, strerror(errno));
655
0
                    goto fail;
656
0
                }
657
0
            } else {
658
0
                res = hclose(gz);
659
660
0
                if (res < 0) {
661
0
                    hts_log_error("Failed on closing %s index %s : %s", file_type, fngzi, strerror(errno));
662
0
                    goto fail;
663
0
                }
664
0
            }
665
0
        }
666
667
0
        bgzf_close(bgzf);
668
0
    }
669
670
0
    if (fp == 0 || gzi_index_needed) {
671
0
        if (!(flags & FAI_CREATE) || errno != ENOENT) {
672
0
            hts_log_error("Failed to open %s index %s: %s", file_type, fnfai, strerror(errno));
673
0
            goto fail;
674
0
        }
675
676
0
        hts_log_info("Build %s index", file_type);
677
678
0
        if (fai_build3_core(fn, fnfai, fngzi) < 0) {
679
0
            goto fail;
680
0
        }
681
682
0
        fp = hopen(fnfai, "rb");
683
0
        if (fp == 0) {
684
0
            hts_log_error("Failed to open %s index %s: %s", file_type, fnfai, strerror(errno));
685
0
            goto fail;
686
0
        }
687
0
    }
688
689
0
    fai = fai_read(fp, fnfai, format);
690
0
    if (fai == NULL) {
691
0
        hts_log_error("Failed to read %s index %s", file_type, fnfai);
692
0
        goto fail;
693
0
    }
694
695
0
    res = hclose(fp);
696
0
    fp = NULL;
697
0
    if (res < 0) {
698
0
        hts_log_error("Failed on closing %s index %s : %s", file_type, fnfai, strerror(errno));
699
0
        goto fail;
700
0
    }
701
702
0
    fai->bgzf = bgzf_open(fn, "rb");
703
0
    if (fai->bgzf == 0) {
704
0
        hts_log_error("Failed to open %s file %s", file_type, fn);
705
0
        goto fail;
706
0
    }
707
708
0
    if ( fai->bgzf->is_compressed==1 ) {
709
0
        if ( bgzf_index_load(fai->bgzf, fngzi, NULL) < 0 ) {
710
0
            hts_log_error("Failed to load .gzi index: %s", fngzi);
711
0
            goto fail;
712
0
        }
713
0
    }
714
0
    free(fai_kstr.s);
715
0
    free(gzi_kstr.s);
716
0
    return fai;
717
718
0
 fail:
719
0
    if (fai) fai_destroy(fai);
720
0
    if (fp) hclose_abruptly(fp);
721
0
    free(fai_kstr.s);
722
0
    free(gzi_kstr.s);
723
0
    return NULL;
724
0
}
725
726
727
faidx_t *fai_load3(const char *fn, const char *fnfai, const char *fngzi,
728
0
                   int flags) {
729
0
    return fai_load3_core(fn, fnfai, fngzi, flags, FAI_FASTA);
730
0
}
731
732
733
faidx_t *fai_load(const char *fn)
734
0
{
735
0
    return fai_load3(fn, NULL, NULL, FAI_CREATE);
736
0
}
737
738
739
faidx_t *fai_load3_format(const char *fn, const char *fnfai, const char *fngzi,
740
0
                   int flags, enum fai_format_options format) {
741
0
    return fai_load3_core(fn, fnfai, fngzi, flags, format);
742
0
}
743
744
745
0
faidx_t *fai_load_format(const char *fn, enum fai_format_options format) {
746
0
    return fai_load3_format(fn, NULL, NULL, FAI_CREATE, format);
747
0
}
748
749
750
static char *fai_retrieve(const faidx_t *fai, const faidx1_t *val,
751
0
                          uint64_t offset, hts_pos_t beg, hts_pos_t end, hts_pos_t *len) {
752
0
    char *buffer, *s;
753
0
    ssize_t nread, remaining, firstline_len, firstline_blen;
754
0
    int ret;
755
756
0
    if ((uint64_t) end - (uint64_t) beg >= SIZE_MAX - 2) {
757
0
        hts_log_error("Range %"PRId64"..%"PRId64" too big", beg, end);
758
0
        *len = -1;
759
0
        return NULL;
760
0
    }
761
762
0
    if (val->line_blen <= 0) {
763
0
        hts_log_error("Invalid line length in index: %"PRIu64, val->line_blen);
764
0
        *len = -1;
765
0
        return NULL;
766
0
    }
767
768
0
    uint64_t line_len = val->line_blen + val->line_extra;
769
770
0
    ret = bgzf_useek(fai->bgzf,
771
0
                     offset
772
0
                     + beg / val->line_blen * line_len
773
0
                     + beg % val->line_blen, SEEK_SET);
774
775
0
    if (ret < 0) {
776
0
        *len = -1;
777
0
        hts_log_error("Failed to retrieve block. (Seeking in a compressed, .gzi unindexed, file?)");
778
0
        return NULL;
779
0
    }
780
781
    // Over-allocate so there is extra space for one end-of-line sequence
782
0
    buffer = hts_malloc(hts_add_sat3(end - beg, line_len - val->line_blen, 1));
783
0
    if (!buffer) {
784
0
        *len = -1;
785
0
        return NULL;
786
0
    }
787
788
0
    remaining = *len = end - beg;
789
0
    firstline_blen = val->line_blen - beg % val->line_blen;
790
791
    // Special case when the entire interval requested is within a single FASTA/Q line
792
0
    if (remaining <= firstline_blen) {
793
0
        nread = bgzf_read_small(fai->bgzf, buffer, remaining);
794
0
        if (nread < remaining) goto error;
795
0
        buffer[nread] = '\0';
796
0
        return buffer;
797
0
    }
798
799
0
    s = buffer;
800
0
    firstline_len = line_len - beg % val->line_blen;
801
802
    // Read the (partial) first line and its line terminator, but increment  s  past the
803
    // line contents only, so the terminator characters will be overwritten by the next line.
804
0
    nread = bgzf_read_small(fai->bgzf, s, firstline_len);
805
0
    if (nread < firstline_len) goto error;
806
0
    s += firstline_blen;
807
0
    remaining -= firstline_blen;
808
809
    // Similarly read complete lines and their line terminator characters, but overwrite the latter.
810
0
    while (remaining > val->line_blen) {
811
0
        nread = bgzf_read_small(fai->bgzf, s, line_len);
812
0
        if (nread < (ssize_t) line_len) goto error;
813
0
        s += val->line_blen;
814
0
        remaining -= val->line_blen;
815
0
    }
816
817
0
    if (remaining > 0) {
818
0
        nread = bgzf_read_small(fai->bgzf, s, remaining);
819
0
        if (nread < remaining) goto error;
820
0
        s += remaining;
821
0
    }
822
823
0
    *s = '\0';
824
0
    return buffer;
825
826
0
error:
827
0
    hts_log_error("Failed to retrieve block: %s",
828
0
                  (nread == 0)? "unexpected end of file" : "error reading file");
829
0
    free(buffer);
830
0
    *len = -1;
831
0
    return NULL;
832
0
}
833
834
static int fai_get_val(const faidx_t *fai, const char *str,
835
0
                       hts_pos_t *len, faidx1_t *val, hts_pos_t *fbeg, hts_pos_t *fend) {
836
0
    khiter_t iter;
837
0
    khash_t(s) *h;
838
0
    int id;
839
0
    hts_pos_t beg, end;
840
841
0
    if (!fai_parse_region(fai, str, &id, &beg, &end, 0)) {
842
0
        hts_log_warning("Reference %s not found in FASTA file, returning empty sequence", str);
843
0
        *len = -2;
844
0
        return 1;
845
0
    }
846
847
0
    h = fai->hash;
848
0
    iter = kh_get(s, h, faidx_iseq(fai, id));
849
0
    if (iter >= kh_end(h)) {
850
        // should have already been caught above
851
0
        abort();
852
0
    }
853
0
    *val = kh_value(h, iter);
854
855
0
    if (beg >= val->len) beg = val->len;
856
0
    if (end >= val->len) end = val->len;
857
0
    if (beg > end) beg = end;
858
859
0
    *fbeg = beg;
860
0
    *fend = end;
861
862
0
    return 0;
863
0
}
864
865
/*
866
 *  Returns hts_pos_t for historic reasons (line_blen was uint32_t,
867
 *  but this function returned a wider value in case it was expanded
868
 *  which has now happened).  It also needs to return a negative value
869
 *  on error.
870
 */
871
hts_pos_t fai_line_length(const faidx_t *fai, const char *str)
872
0
{
873
0
    faidx1_t val;
874
0
    int64_t beg, end;
875
0
    hts_pos_t len;
876
877
0
    if (fai_get_val(fai, str, &len, &val, &beg, &end))
878
0
        return -1;
879
0
    else
880
0
        return (val.line_blen <= HTS_POS_MAX
881
0
                ? (hts_pos_t) val.line_blen
882
0
                : (hts_pos_t) -1);
883
0
}
884
885
char *fai_fetch64(const faidx_t *fai, const char *str, hts_pos_t *len)
886
0
{
887
0
    faidx1_t val;
888
0
    int64_t beg, end;
889
890
0
    if (fai_get_val(fai, str, len, &val, &beg, &end)) {
891
0
        return NULL;
892
0
    }
893
894
    // now retrieve the sequence
895
0
    return fai_retrieve(fai, &val, val.seq_offset, beg, end, len);
896
0
}
897
898
char *fai_fetch(const faidx_t *fai, const char *str, int *len)
899
0
{
900
0
    hts_pos_t len64;
901
0
    char *ret = fai_fetch64(fai, str, &len64);
902
0
    *len = len64 < INT_MAX ? len64 : INT_MAX; // trunc
903
0
    return ret;
904
0
}
905
906
0
char *fai_fetchqual64(const faidx_t *fai, const char *str, hts_pos_t *len) {
907
0
    faidx1_t val;
908
0
    int64_t beg, end;
909
910
0
    if (fai_get_val(fai, str, len, &val, &beg, &end)) {
911
0
        return NULL;
912
0
    }
913
914
    // now retrieve the sequence
915
0
    return fai_retrieve(fai, &val, val.qual_offset, beg, end, len);
916
0
}
917
918
0
char *fai_fetchqual(const faidx_t *fai, const char *str, int *len) {
919
0
    hts_pos_t len64;
920
0
    char *ret = fai_fetchqual64(fai, str, &len64);
921
0
    *len = len64 < INT_MAX ? len64 : INT_MAX; // trunc
922
0
    return ret;
923
0
}
924
925
int faidx_fetch_nseq(const faidx_t *fai)
926
0
{
927
0
    return fai->n;
928
0
}
929
930
int faidx_nseq(const faidx_t *fai)
931
0
{
932
0
    return fai->n;
933
0
}
934
935
const char *faidx_iseq(const faidx_t *fai, int i)
936
0
{
937
0
    return fai->name[i];
938
0
}
939
940
hts_pos_t faidx_seq_len64(const faidx_t *fai, const char *seq)
941
0
{
942
0
    khint_t k = kh_get(s, fai->hash, seq);
943
0
    if ( k == kh_end(fai->hash) ) return -1;
944
0
    return kh_val(fai->hash, k).len;
945
0
}
946
947
int faidx_seq_len(const faidx_t *fai, const char *seq)
948
0
{
949
0
    hts_pos_t len = faidx_seq_len64(fai, seq);
950
0
    return len < INT_MAX ? len : INT_MAX;
951
0
}
952
953
static int faidx_adjust_position(const faidx_t *fai, int end_adjust,
954
                                 faidx1_t *val_out, const char *c_name,
955
                                 hts_pos_t *p_beg_i, hts_pos_t *p_end_i,
956
0
                                 hts_pos_t *len) {
957
0
    khiter_t iter;
958
0
    faidx1_t *val;
959
960
    // Adjust position
961
0
    iter = kh_get(s, fai->hash, c_name);
962
963
0
    if (iter == kh_end(fai->hash)) {
964
0
        if (len)
965
0
            *len = -2;
966
0
        hts_log_error("The sequence \"%s\" was not found", c_name);
967
0
        return 1;
968
0
    }
969
970
0
    val = &kh_value(fai->hash, iter);
971
972
0
    if (val_out)
973
0
        *val_out = *val;
974
975
0
    if(*p_end_i < *p_beg_i)
976
0
        *p_beg_i = *p_end_i;
977
978
0
    if(*p_beg_i < 0)
979
0
        *p_beg_i = 0;
980
0
    else if(val->len <= *p_beg_i)
981
0
        *p_beg_i = val->len;
982
983
0
    if(*p_end_i < 0)
984
0
        *p_end_i = 0;
985
0
    else if(val->len <= *p_end_i)
986
0
        *p_end_i = val->len - end_adjust;
987
988
0
    return 0;
989
0
}
990
991
int fai_adjust_region(const faidx_t *fai, int tid,
992
                      hts_pos_t *beg, hts_pos_t *end)
993
0
{
994
0
    hts_pos_t orig_beg, orig_end;
995
996
0
    if (!fai || !beg || !end || tid < 0 || tid >= fai->n)
997
0
        return -1;
998
999
0
    orig_beg = *beg;
1000
0
    orig_end = *end;
1001
0
    if (faidx_adjust_position(fai, 0, NULL, fai->name[tid], beg, end, NULL) != 0) {
1002
0
        hts_log_error("Inconsistent faidx internal state - couldn't find \"%s\"",
1003
0
                      fai->name[tid]);
1004
0
        return -1;
1005
0
    }
1006
1007
0
    return ((orig_beg != *beg ? 1 : 0) |
1008
0
            (orig_end != *end && orig_end < HTS_POS_MAX ? 2 : 0));
1009
0
}
1010
1011
char *faidx_fetch_seq64(const faidx_t *fai, const char *c_name, hts_pos_t p_beg_i, hts_pos_t p_end_i, hts_pos_t *len)
1012
0
{
1013
0
    faidx1_t val;
1014
1015
    // Adjust position
1016
0
    if (faidx_adjust_position(fai, 1, &val, c_name, &p_beg_i, &p_end_i, len)) {
1017
0
        return NULL;
1018
0
    }
1019
1020
    // Now retrieve the sequence
1021
0
    return fai_retrieve(fai, &val, val.seq_offset, p_beg_i, p_end_i + 1, len);
1022
0
}
1023
1024
char *faidx_fetch_seq(const faidx_t *fai, const char *c_name, int p_beg_i, int p_end_i, int *len)
1025
0
{
1026
0
    hts_pos_t len64;
1027
0
    char *ret = faidx_fetch_seq64(fai, c_name, p_beg_i, p_end_i, &len64);
1028
0
    *len = len64 < INT_MAX ? len64 : INT_MAX;  // trunc
1029
0
    return ret;
1030
0
}
1031
1032
char *faidx_fetch_qual64(const faidx_t *fai, const char *c_name, hts_pos_t p_beg_i, hts_pos_t p_end_i, hts_pos_t *len)
1033
0
{
1034
0
    faidx1_t val;
1035
1036
    // Adjust position
1037
0
    if (faidx_adjust_position(fai, 1, &val, c_name, &p_beg_i, &p_end_i, len)) {
1038
0
        return NULL;
1039
0
    }
1040
1041
    // Now retrieve the sequence
1042
0
    return fai_retrieve(fai, &val, val.qual_offset, p_beg_i, p_end_i + 1, len);
1043
0
}
1044
1045
char *faidx_fetch_qual(const faidx_t *fai, const char *c_name, int p_beg_i, int p_end_i, int *len)
1046
0
{
1047
0
    hts_pos_t len64;
1048
0
    char *ret = faidx_fetch_qual64(fai, c_name, p_beg_i, p_end_i, &len64);
1049
0
    *len = len64 < INT_MAX ? len64 : INT_MAX;  // trunc
1050
0
    return ret;
1051
0
}
1052
1053
int faidx_has_seq(const faidx_t *fai, const char *seq)
1054
0
{
1055
0
    khiter_t iter = kh_get(s, fai->hash, seq);
1056
0
    if (iter == kh_end(fai->hash)) return 0;
1057
0
    return 1;
1058
0
}
1059
1060
const char *fai_parse_region(const faidx_t *fai, const char *s,
1061
                             int *tid, hts_pos_t *beg, hts_pos_t *end,
1062
                             int flags)
1063
0
{
1064
0
    return hts_parse_region(s, tid, beg, end, fai_name2id, (void *)fai, flags);
1065
0
}
1066
1067
0
void fai_set_cache_size(faidx_t *fai, int cache_size) {
1068
0
    bgzf_set_cache_size(fai->bgzf, cache_size);
1069
0
}
1070
1071
// Adds a thread pool to the underlying BGZF layer.
1072
0
int fai_thread_pool(faidx_t *fai, struct hts_tpool *pool, int qsize) {
1073
0
    return bgzf_thread_pool(fai->bgzf, pool, qsize);
1074
0
}
1075
1076
0
char *fai_path(const char *fa) {
1077
0
    char *fai = NULL;
1078
0
    if (!fa) {
1079
0
        hts_log_error("No reference file specified");
1080
0
    } else {
1081
0
        const char *fai_tmp = strstr(fa, HTS_IDX_DELIM);
1082
0
        if (fai_tmp) {
1083
0
            fai_tmp += strlen(HTS_IDX_DELIM);
1084
0
            fai = strdup(fai_tmp);
1085
0
            if (!fai)
1086
0
                hts_log_error("Failed to allocate memory");
1087
0
        } else {
1088
0
            if (hisremote(fa)) {
1089
0
                fai = hts_idx_locatefn(fa, ".fai");       // get the remote fai file name, if any, but do not download the file
1090
0
                if (!fai)
1091
0
                    hts_log_error("Failed to locate index file for remote reference file '%s'", fa);
1092
0
            } else{
1093
0
                if (hts_idx_check_local(fa, HTS_FMT_FAI, &fai) == 0 && fai) {
1094
0
                    if (fai_build3(fa, fai, NULL) == -1) {      // create local fai file by indexing local fasta
1095
0
                        hts_log_error("Failed to build index file for reference file '%s'", fa);
1096
0
                        free(fai);
1097
0
                        fai = NULL;
1098
0
                    }
1099
0
                }
1100
0
            }
1101
0
        }
1102
0
    }
1103
1104
0
    return fai;
1105
0
}