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
use std::borrow::Cow;
use std::io;
use std::iter;
use std::slice;
use std::str;

use super::{write, write_iter, write_wrap, write_wrap_iter, LineStore};
use crate::core::{join_lines, PositionStore};
use crate::BaseRecord;
use serde::{Deserialize, Serialize};

/// FASTA record trait implemented by both `RefRecord` and `OwnedRecord`,
/// which adds more methods to [`BaseRecord`](crate::BaseRecord).
pub trait Record: BaseRecord {
    /// Writes the record to the given `io::Write` instance.
    /// The sequence is wrapped to produce multi-line FASTA with a maximum width
    /// specified by `wrap`.
    fn write_wrap<W>(&self, writer: W, wrap: usize) -> io::Result<()>
    where
        W: io::Write,
        Self: Sized;
}

impl<'a, R: Record> Record for &'a R {
    fn write_wrap<W>(&self, writer: W, wrap: usize) -> io::Result<()>
    where
        W: io::Write,
        Self: Sized,
    {
        (**self).write_wrap(writer, wrap)
    }
}

/// A FASTA 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 = LineStore>
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]> {
        join_lines(self.seq_lines(), self.num_seq_lines())
    }

    #[inline]
    fn full_seq_given<'s, F>(&'s self, owned_fn: F) -> Cow<'s, [u8]>
    where
        F: FnOnce() -> &'s mut Vec<u8>,
    {
        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 {
        false
    }

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

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

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

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

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

impl<'a, S> Record for RefRecord<'a, S>
where
    S: PositionStore,
{
    #[inline]
    fn write_wrap<W: io::Write>(&self, mut writer: W, wrap: usize) -> io::Result<()> {
        write_wrap_iter(&mut writer, self.head(), self.seq_lines(), wrap)
    }
}

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 the sequence as owned `Vec`. **Note**: This function
    /// must be called in order to obtain a sequence that does not contain
    /// line endings (as returned by `seq()`)
    #[inline]
    pub fn owned_seq(&self) -> Vec<u8> {
        let mut seq = Vec::new();
        for segment in self.seq_lines() {
            seq.extend(segment);
        }
        seq
    }

    /// 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.owned_seq(),
        }
    }

    /// 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);
    }

    /// 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];
        writer.write_all(data)?;
        if *data.last().unwrap() != b'\n' {
            writer.write_all(&[b'\n'])?;
        }
        Ok(())
    }
}

impl_fastx_from_refrecord!(RefRecord);

/// A FASTA record that ownes its data (requiring two allocations)
/// It implements the traits [`BaseRecord`](crate::BaseRecord) and
/// [`Record`](Record).
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OwnedRecord {
    pub head: Vec<u8>,
    pub seq: 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: FnOnce() -> &'s mut Vec<u8>>(&'s self, _: F) -> Cow<'s, [u8]> {
        (&self.seq).into()
    }

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

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

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

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

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

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

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

impl Record for OwnedRecord {
    #[inline]
    fn write_wrap<W: io::Write>(&self, mut writer: W, wrap: usize) -> io::Result<()> {
        write_wrap(&mut writer, &self.head, &self.seq, wrap)
    }
}

impl_recordset!(RefRecord, LineStore, "fasta", "fasta");