noodles_fasta/io/reader/
sequence.rs

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
//! Sequence reader.

use std::io::{self, BufRead, Read};

use super::DEFINITION_PREFIX;

const LINE_FEED: u8 = b'\n';
const CARRIAGE_RETURN: u8 = b'\r';

/// A sequence reader.
///
/// This is used for lower-level reading of the sequence. It implements [`Read`] and [`BufRead`] to
/// return raw bases sans newlines. It reads up to the next record definition or EOF.
///
/// This is created by calling [`super::Reader::sequence_reader`].
pub struct Reader<'r, R> {
    inner: &'r mut R,
}

impl<'r, R> Reader<'r, R>
where
    R: BufRead,
{
    pub(super) fn new(inner: &'r mut R) -> Self {
        Self { inner }
    }
}

impl<'r, R> Read for Reader<'r, R>
where
    R: BufRead,
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut src = self.fill_buf()?;
        let amt = src.read(buf)?;
        self.consume(amt);
        Ok(amt)
    }
}

impl<'r, R> BufRead for Reader<'r, R>
where
    R: BufRead,
{
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        use memchr::memchr;

        consume_empty_lines(&mut self.inner)?;

        let src = self.inner.fill_buf()?;

        let is_eof = src.is_empty();
        let is_end_of_sequence = || src[0] == DEFINITION_PREFIX;

        if is_eof || is_end_of_sequence() {
            return Ok(&[]);
        }

        let line = match memchr(LINE_FEED, src) {
            Some(i) => &src[..i],
            None => src,
        };

        if line.ends_with(&[CARRIAGE_RETURN]) {
            let end = line.len() - 1;
            Ok(&line[..end])
        } else {
            Ok(line)
        }
    }

    fn consume(&mut self, amt: usize) {
        self.inner.consume(amt);
    }
}

fn consume_empty_lines<R>(reader: &mut R) -> io::Result<()>
where
    R: BufRead,
{
    loop {
        let mut is_newline = false;

        if reader.fill_buf()?.starts_with(&[CARRIAGE_RETURN]) {
            is_newline = true;
            reader.consume(1);
        }

        if reader.fill_buf()?.starts_with(&[LINE_FEED]) {
            is_newline = true;
            reader.consume(1);
        }

        if !is_newline {
            break;
        }
    }

    Ok(())
}

pub(super) fn read_sequence<R>(reader: &mut R, buf: &mut Vec<u8>) -> io::Result<usize>
where
    R: BufRead,
{
    let mut reader = Reader::new(reader);
    reader.read_to_end(buf)
}

pub(super) fn read_sequence_limit<R>(
    reader: &mut R,
    max_bases: usize,
    buf: &mut Vec<u8>,
) -> io::Result<usize>
where
    R: BufRead,
{
    let mut reader = Reader::new(reader);
    let mut len = 0;

    while buf.len() < max_bases {
        let src = reader.fill_buf()?;

        if src.is_empty() {
            break;
        }

        let remaining_bases = max_bases - buf.len();
        let i = remaining_bases.min(src.len());

        let bases = &src[..i];
        buf.extend(bases);

        reader.consume(i);

        len += i;
    }

    Ok(len)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_read_sequence() -> io::Result<()> {
        fn t(buf: &mut Vec<u8>, mut reader: &[u8], expected: &[u8]) -> io::Result<()> {
            buf.clear();
            read_sequence(&mut reader, buf)?;
            assert_eq!(buf, expected);
            Ok(())
        }

        let mut buf = Vec::new();

        t(&mut buf, b"ACGT\n", b"ACGT")?;
        t(&mut buf, b"ACGT\n>sq1\n", b"ACGT")?;
        t(&mut buf, b"ACGT\n\nACGT\nAC\n\n", b"ACGTACGTAC")?;

        t(&mut buf, b"ACGT\r\n", b"ACGT")?;
        t(&mut buf, b"ACGT\r\n>sq1\r\n", b"ACGT")?;
        t(&mut buf, b"ACGT\r\n\r\nACGT\r\nAC\r\n\r\n", b"ACGTACGTAC")?;

        Ok(())
    }

    #[test]
    fn test_read_sequence_limit() -> io::Result<()> {
        fn t(
            buf: &mut Vec<u8>,
            mut reader: &[u8],
            max_bases: usize,
            expected: &[u8],
        ) -> io::Result<()> {
            buf.clear();
            read_sequence_limit(&mut reader, max_bases, buf)?;
            assert_eq!(buf, expected);
            Ok(())
        }

        let mut buf = Vec::new();

        t(&mut buf, b"ACGT\n", 4, b"ACGT")?;
        t(&mut buf, b"ACGT\n>sq0\n", 4, b"ACGT")?;
        t(&mut buf, b"ACGT\nACGT\nAC\n", 10, b"ACGTACGTAC")?;

        t(&mut buf, b"ACGT\n", 2, b"AC")?;
        t(&mut buf, b"ACGT\n>sq0\n", 2, b"AC")?;
        t(&mut buf, b"ACGT\nACGT\nAC", 2, b"AC")?;

        t(&mut buf, b"ACGT\n", 5, b"ACGT")?;
        t(&mut buf, b"ACGT\n>sq0\n", 5, b"ACGT")?;
        t(&mut buf, b"ACGT\nACGT\nAC", 5, b"ACGTA")?;

        t(&mut buf, b"ACGT\n", 5, b"ACGT")?;
        t(&mut buf, b"ACGT\r\n>sq0\r\n", 5, b"ACGT")?;
        t(&mut buf, b"ACGT\r\nACGT\r\nAC\r\n", 5, b"ACGTA")?;

        Ok(())
    }
}