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
//! FASTA I/O.

pub mod indexed_reader;
mod indexer;
pub mod reader;
pub mod writer;

use std::{
    fs::File,
    io::{self, BufRead, Read, Seek, SeekFrom},
    path::Path,
};

use noodles_bgzf as bgzf;

pub use self::{indexed_reader::IndexedReader, indexer::Indexer, reader::Reader, writer::Writer};
use super::fai;

/// A buffered FASTA reader.
pub enum BufReader<R> {
    /// bgzip-compressed.
    Bgzf(bgzf::IndexedReader<R>),
    /// Uncompressed.
    Uncompressed(std::io::BufReader<R>),
}

impl<R> Read for BufReader<R>
where
    R: Read,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            Self::Bgzf(reader) => reader.read(buf),
            Self::Uncompressed(reader) => reader.read(buf),
        }
    }
}

impl<R> BufRead for BufReader<R>
where
    R: Read,
{
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        match self {
            Self::Bgzf(reader) => reader.fill_buf(),
            Self::Uncompressed(reader) => reader.fill_buf(),
        }
    }

    fn consume(&mut self, amt: usize) {
        match self {
            Self::Bgzf(reader) => reader.consume(amt),
            Self::Uncompressed(reader) => reader.consume(amt),
        }
    }
}

impl<R> Seek for BufReader<R>
where
    R: Read + Seek,
{
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        match self {
            Self::Bgzf(reader) => reader.seek(pos),
            Self::Uncompressed(reader) => reader.seek(pos),
        }
    }
}

/// Indexes a FASTA file.
///
/// # Examples
///
/// ```no_run
/// # use std::io;
/// use noodles_fasta as fasta;
/// let index = fasta::io::index("reference.fa")?;
/// # Ok::<(), io::Error>(())
/// ```
pub fn index<P>(src: P) -> io::Result<fai::Index>
where
    P: AsRef<Path>,
{
    let mut indexer = File::open(src).map(io::BufReader::new).map(Indexer::new)?;
    let mut index = Vec::new();

    while let Some(i) = indexer.index_record()? {
        index.push(i);
    }

    Ok(index)
}