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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use std::borrow::Cow;
use std::io;
use std::iter;
use std::slice;
use std::str;

use super::{write, write_iter, Error, ErrorKind, RangeStore};
use crate::core::PositionStore;
use crate::{BaseRecord, ErrorPosition};
use serde::{Deserialize, Serialize};

/// FASTQ record trait implemented by both `RefRecord` and `OwnedRecord`
/// which adds more methods to [`BaseRecord`](crate::BaseRecord).
pub trait Record: BaseRecord {
    /// Return the FASTQ quality line as byte slice
    fn qual(&self) -> &[u8];

    fn full_qual(&self) -> Cow<[u8]>;

    fn full_qual_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
        Self: Sized;

    doc_record_check_lengths!(
        "use seq_io::fastq::Reader;",
        fn check_lengths(&self) -> Result<&Self, Error>;
    );
}

// TODO: necessary?

// impl<'a, R: Record> Record for &'a R {
//     fn qual(&self) -> &[u8] {
//         (**self).qual()
//     }

//     fn full_qual(&self) -> Cow<[u8]> {
//         (**self).full_qual()
//     }

//     fn full_qual_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]>
//     where
//         F: FnOnce() -> &'s mut Vec<u8>,
//         Self: Sized
//     {
//         (**self).full_qual_given(owned_fn)
//     }

//     fn check_lengths(&self) -> Result<&Self, Error> {
//         (**self).check_lengths()
//     }
// }

/// A FASTQ record that borrows data from a buffer
/// It implements the traits [`BaseRecord`](crate::BaseRecord) and
/// [`Record`](Record).
#[derive(Debug, Clone)]
pub struct RefRecord<'a, S = RangeStore>
where
    S: PositionStore,
{
    pub(crate) buffer: &'a [u8],
    pub(crate) buf_pos: &'a S,
}

impl<'a, S> BaseRecord for RefRecord<'a, S>
where
    S: PositionStore,
{
    #[inline]
    fn head(&self) -> &[u8] {
        self.buf_pos.head(self.buffer)
    }

    #[inline]
    fn seq(&self) -> &[u8] {
        self.buf_pos.seq(self.buffer)
    }

    #[inline]
    fn full_seq(&self) -> Cow<[u8]> {
        self.buf_pos.join_seq(self.buffer)
    }

    #[inline]
    fn full_seq_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
        Self: Sized,
    {
        self.buf_pos.join_seq_given(self.buffer, owned_fn)
    }

    #[inline]
    fn num_seq_lines(&self) -> usize {
        self.buf_pos.num_seq_lines()
    }

    #[inline]
    fn has_quality(&self) -> bool {
        true
    }

    #[inline]
    fn opt_qual(&self) -> Option<&[u8]> {
        Some(self.qual())
    }

    #[inline]
    fn opt_full_qual(&self) -> Option<Cow<[u8]>> {
        Some(self.full_qual())
    }

    #[inline]
    fn opt_full_qual_given<'s, F>(&'s self, owned_fn: F) -> Option<Cow<'s, [u8]>>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
    {
        Some(self.full_qual_given(owned_fn))
    }

    #[inline]
    fn num_qual_lines(&self) -> usize {
        self.buf_pos.num_qual_lines()
    }

    #[inline]
    fn write<W>(&self, writer: W) -> io::Result<()>
    where
        W: io::Write,
        Self: Sized,
    {
        write_iter(writer, self.head(), self.seq_lines(), self.qual_lines())
    }
}

impl<'a, S> Record for RefRecord<'a, S>
where
    S: PositionStore,
{
    #[inline]
    fn qual(&self) -> &[u8] {
        self.buf_pos.qual(self.buffer)
    }

    #[inline]
    fn full_qual(&self) -> Cow<[u8]> {
        self.buf_pos.join_qual(self.buffer)
    }

    #[inline]
    fn full_qual_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
    {
        self.buf_pos.join_qual_given(self.buffer, owned_fn)
    }

    #[inline]
    fn check_lengths(&self) -> Result<&Self, Error> {
        self._check_lengths(false)
    }
}

impl<'a, S> RefRecord<'a, S>
where
    S: PositionStore,
{
    #[inline]
    pub(crate) fn new(buffer: &'a [u8], buf_pos: &'a S) -> Self {
        RefRecord { buffer, buf_pos }
    }

    /// Returns an iterator over all sequence lines in the data. The exact
    /// type of the iterator depends on the generic parameter `S`.
    #[inline]
    pub fn seq_lines(&self) -> impl Iterator<Item = &'a [u8]> + DoubleEndedIterator {
        self.buf_pos.seq_lines(self.buffer)
    }

    /// Returns an iterator over all quality lines in the data. The exact
    /// type of the iterator depends on the generic parameter `S`.
    #[inline]
    pub fn qual_lines(&self) -> impl Iterator<Item = &'a [u8]> + DoubleEndedIterator {
        self.buf_pos.qual_lines(self.buffer)
    }

    #[inline]
    fn _check_lengths(&self, strict: bool) -> Result<&Self, Error> {
        self.buf_pos
            .check_lengths(self.buffer, strict)
            .map(|_| self)
            .map_err(|(seq, qual)| {
                let id = String::from_utf8_lossy(self.id_bytes()).into();
                let pos = ErrorPosition::new(None, None, Some(id));
                Error::new(ErrorKind::UnequalLengths { pos, seq, qual })
            })
    }

    doc_refrecord_check_lengths_strict!(
        #[inline]
        pub fn check_lengths_strict(&self) -> Result<&Self, Error> {
            self._check_lengths(true)
        }
    );

    /// Returns a new [`OwnedRecord`](OwnedRecord) with the same
    /// data.
    #[inline]
    pub fn to_owned_record(&self) -> OwnedRecord {
        OwnedRecord {
            head: self.head().to_vec(),
            seq: self.full_seq().to_vec(),
            qual: self.full_qual().to_vec(),
        }
    }

    /// Copies the data of the record into an [`OwnedRecord`](OwnedRecord)
    /// instance.
    #[inline]
    pub fn clone_into_owned(&self, rec: &mut OwnedRecord) {
        rec.head.clear();
        rec.head.extend(self.head());
        rec.seq.clear();
        self.full_seq_given(|| &mut rec.seq);
        rec.qual.clear();
        self.full_qual_given(|| &mut rec.qual);
    }

    /// Writes a record to the given `io::Write` instance
    /// by just writing the unmodified input, which is faster than `BaseRecord::write`
    #[inline]
    pub fn write_unchanged<W: io::Write>(&self, mut writer: W) -> io::Result<()> {
        let data = &self.buffer
            [self.buf_pos.record_start() as usize..self.buf_pos.record_end() as usize - 1];
        writer.write_all(data)?;
        writer.write_all(b"\n")
    }
}

impl_fastx_from_refrecord!(RefRecord);

/// A FASTQ record that ownes its data (requires allocations)
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OwnedRecord {
    pub head: Vec<u8>,
    pub seq: Vec<u8>,
    pub qual: Vec<u8>,
}

impl BaseRecord for OwnedRecord {
    #[inline]
    fn head(&self) -> &[u8] {
        &self.head
    }
    #[inline]
    fn seq(&self) -> &[u8] {
        &self.seq
    }

    #[inline]
    fn full_seq(&self) -> Cow<[u8]> {
        (&self.seq).into()
    }

    #[inline]
    fn full_seq_given<'s, F>(&'s self, _: F) -> Cow<'s, [u8]>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
    {
        (&self.seq).into()
    }

    #[inline]
    fn num_seq_lines(&self) -> usize {
        1
    }

    #[inline]
    fn has_quality(&self) -> bool {
        true
    }

    #[inline]
    fn opt_qual(&self) -> Option<&[u8]> {
        Some(self.qual())
    }

    #[inline]
    fn opt_full_qual(&self) -> Option<Cow<[u8]>> {
        Some(self.full_qual())
    }

    #[inline]
    fn opt_full_qual_given<'s, F>(&'s self, _: F) -> Option<Cow<'s, [u8]>>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
    {
        Some((&self.qual).into())
    }

    #[inline]
    fn num_qual_lines(&self) -> usize {
        1
    }

    #[inline]
    fn write<W>(&self, writer: W) -> io::Result<()>
    where
        W: io::Write,
    {
        write(writer, self.head(), self.seq(), self.qual())
    }
}

impl Record for OwnedRecord {
    #[inline]
    fn qual(&self) -> &[u8] {
        &self.qual
    }

    #[inline]
    fn full_qual(&self) -> Cow<[u8]> {
        (&self.qual).into()
    }

    #[inline]
    fn full_qual_given<'s, F>(&'s self, _: F) -> Cow<'s, [u8]>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
    {
        (&self.qual).into()
    }

    #[inline]
    fn check_lengths(&self) -> Result<&Self, Error> {
        if self.seq.len() == self.qual.len() {
            return Ok(self);
        }
        let id = String::from_utf8_lossy(self.id_bytes()).into();
        let pos = ErrorPosition::new(None, None, Some(id));
        return Err(Error::new(ErrorKind::UnequalLengths {
            pos,
            seq: self.seq.len(),
            qual: self.qual.len(),
        }));
    }
}

impl_recordset!(RefRecord, RangeStore, "fastq", "fastq");