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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use crate::core::{trim_cr, trim_end, SimpleLines};
use std::clone::Clone;
use std::default::Default;
use std::fmt::Debug;
use std::io;
use std::slice;

/// Helper trait  used to allow supplying either the whole head or separate ID
/// and description parts to the  `write_...()` functions in the `fasta` and
/// `fastq` modules.
pub trait HeadWriter {
    /// Writes the header line to output.
    fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write;
}

impl<'a> HeadWriter for &'a [u8] {
    fn write_head<W>(&self, mut writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        write!(writer, "{}", start_byte as char)?;
        writer.write_all(self)?;
        writer.write_all(b"\n")
    }
}

macro_rules! impl_write_head {
    ($t:ty) => {
        impl HeadWriter for $t {
            fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
            where
                W: io::Write,
            {
                (&self[..]).write_head(writer, start_byte)
            }
        }
    };
}

impl_write_head!(&Vec<u8>);
impl_write_head!(&[u8; 1]);
impl_write_head!(&[u8; 2]);
impl_write_head!(&[u8; 3]);
impl_write_head!(&[u8; 4]);
impl_write_head!(&[u8; 5]);
impl_write_head!(&[u8; 6]);
impl_write_head!(&[u8; 7]);
impl_write_head!(&[u8; 8]);
impl_write_head!(&[u8; 9]);
impl_write_head!(&[u8; 10]);
impl_write_head!(&[u8; 11]);
impl_write_head!(&[u8; 12]);
impl_write_head!(&[u8; 13]);
impl_write_head!(&[u8; 14]);
impl_write_head!(&[u8; 15]);
impl_write_head!(&[u8; 16]);
impl_write_head!(&[u8; 17]);
impl_write_head!(&[u8; 18]);
impl_write_head!(&[u8; 19]);
impl_write_head!(&[u8; 20]);

impl<'a> HeadWriter for &'a str {
    fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        self.as_bytes().write_head(writer, start_byte)
    }
}

impl<'a> HeadWriter for &String {
    fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        self.as_str().write_head(writer, start_byte)
    }
}

impl<'a> HeadWriter for (&'a [u8], Option<&'a [u8]>) {
    fn write_head<W>(&self, mut writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        write!(writer, "{}", start_byte)?;
        writer.write_all(self.0)?;
        writer.write_all(b" ")?;
        if let Some(desc) = self.1 {
            writer.write_all(desc)?;
        }
        Ok(())
    }
}

impl<'a> HeadWriter for (&Vec<u8>, Option<&Vec<u8>>) {
    fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        (self.0.as_slice(), self.1.map(|d| d.as_slice())).write_head(writer, start_byte)
    }
}

impl<'a> HeadWriter for (&'a str, Option<&str>) {
    fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        (self.0.as_bytes(), self.1.map(|d| d.as_bytes())).write_head(writer, start_byte)
    }
}

impl<'a> HeadWriter for (&String, Option<&String>) {
    fn write_head<W>(&self, writer: W, start_byte: u8) -> io::Result<()>
    where
        W: io::Write,
    {
        (self.0.as_str(), self.1.map(|d| d.as_str())).write_head(writer, start_byte)
    }
}

/// Holds line number and byte offset of a FASTQ record
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Position {
    pub(crate) line: u64,
    pub(crate) byte: u64,
    pub(crate) record: u64,
}

impl Position {
    #[inline]
    pub fn new() -> Position {
        Position::default()
    }

    /// Line index (0-based)
    #[inline]
    pub fn line(&self) -> u64 {
        self.line
    }

    /// Byte offset within the input
    #[inline]
    pub fn byte(&self) -> u64 {
        self.byte
    }

    /// Record index (0-based) in the input
    #[inline]
    pub fn record(&self) -> u64 {
        self.record
    }

    /// Sets the line index (0-based)
    #[inline]
    pub fn set_line(&mut self, line: u64) -> &mut Self {
        self.line = line;
        self
    }

    /// Sets the byte offset
    #[inline]
    pub fn set_byte(&mut self, byte: u64) -> &mut Self {
        self.byte = byte;
        self
    }

    /// Sets the record index (0-based)
    #[inline]
    pub fn set_record(&mut self, idx: u64) -> &mut Self {
        self.record = idx;
        self
    }
}

// /// Iterator over the lines of a text slice, whose positions
// /// have been searched before. Therefore, iterating is very fast.
// pub struct LinePositionIter<'a> {
//     data: &'a [u8],
//     len: usize,
//     pos_iter: iter::Zip<slice::Iter<'a, usize>, iter::Skip<slice::Iter<'a, usize>>>,
// }

// impl<'a> LinePositionIter<'a> {
//     /// Assumes that line_ends are sorted by position, and no duplicate
//     /// values are present.
//     #[inline]
//     pub fn new(buffer: &'a [u8], line_ends: &'a [usize]) -> Self {
//         let start_iter = line_ends.iter();
//         let end_iter = line_ends.iter().skip(1);
//         LinePositionIter {
//             data: buffer,
//             len: line_ends.len() - 1,
//             pos_iter: start_iter.zip(end_iter),
//         }
//     }
// }

// impl<'a> Iterator for LinePositionIter<'a> {
//     type Item = &'a [u8];

//     #[inline]
//     fn next(&mut self) -> Option<&'a [u8]> {
//         self.pos_iter
//             .next()
//             .map(|(&start, &next_start)| trim_cr(&self.data[start..next_start - 1]))
//     }

//     #[inline]
//     fn size_hint(&self) -> (usize, Option<usize>) {
//         (self.len, Some(self.len))
//     }
// }

// impl<'a> DoubleEndedIterator for LinePositionIter<'a> {
//     #[inline]
//     fn next_back(&mut self) -> Option<&'a [u8]> {
//         self.pos_iter
//             .next_back()
//             .map(|(start, next_start)| trim_cr(&self.data[*start + 1..*next_start]))
//     }
// }

// impl<'a> ExactSizeIterator for LinePositionIter<'a> {}

// TODO: compare with above version (performance)
/// Iterator over the lines of a text slice, whose positions have been searched
/// before and stored. Iterating is very fast.
pub struct LinePositionIter<'a> {
    data: &'a [u8],
    pos_iter: slice::Windows<'a, usize>,
}

impl<'a> LinePositionIter<'a> {
    /// Assumes that line_ends are sorted by position, and no duplicate
    /// values are present.
    #[inline]
    pub fn new(buffer: &'a [u8], positions: &'a [usize]) -> Self {
        LinePositionIter {
            data: buffer,
            pos_iter: positions.windows(2),
        }
    }
}

impl<'a> Iterator for LinePositionIter<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<&'a [u8]> {
        self.pos_iter
            .next()
            .map(|pos| trim_cr(&self.data[pos[0]..pos[1] - 1]))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.pos_iter.size_hint()
    }
}

impl<'a> DoubleEndedIterator for LinePositionIter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a [u8]> {
        self.pos_iter
            .next_back()
            .map(|pos| trim_cr(&self.data[pos[0]..pos[1] - 1]))
    }
}

impl<'a> ExactSizeIterator for LinePositionIter<'a> {}

#[derive(Debug)]
enum ParseType<'a> {
    One(Option<&'a [u8]>),
    Many(SimpleLines<'a>),
}

/// Iterator over the lines of a text slice. The line endings are searched in
/// the text while iterating, except for the case where it is known that there
/// is only one line.
///
/// Iterating `> 1` line is thus slow compared to `LinePositionIter`. In case,
/// of a single line, the two iterators should be equally fast.
// TODO: implement ExactSizeIterator?
#[derive(Debug)]
pub struct LineSearchIter<'a> {
    inner: ParseType<'a>,
}

impl<'a> LineSearchIter<'a> {
    #[inline]
    pub fn new(text: &'a [u8], one_line: bool) -> Self {
        let inner = if one_line {
            // trim_end also removes single \r, which should only be fed to this
            // constructor if at the end of the input.
            ParseType::One(Some(trim_end(text)))
        } else {
            // SimpleLines also trims orphan \r at the end of the input.
            // The reason for all this is consistency within the crate
            ParseType::Many(SimpleLines::new(text))
        };
        LineSearchIter { inner }
    }
}

impl<'a> Iterator for LineSearchIter<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self.inner {
            ParseType::One(ref mut l) => l.take(),
            ParseType::Many(ref mut parser) => parser.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match self.inner {
            ParseType::One(_) => (1, Some(1)),
            ParseType::Many(ref parser) => parser.size_hint(),
        }
    }
}

impl<'a> DoubleEndedIterator for LineSearchIter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        match self.inner {
            ParseType::One(ref mut l) => l.take(),
            ParseType::Many(ref mut parser) => parser.next_back(),
        }
    }
}