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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
mod cigar;
mod data;
mod quality_scores;
mod sequence;
pub use self::{cigar::Cigar, data::Data, quality_scores::QualityScores, sequence::Sequence};
use std::{
fmt, io, mem,
num::NonZeroUsize,
ops::{Range, RangeFrom},
};
use byteorder::{ByteOrder, LittleEndian};
use bytes::Buf;
use noodles_core::Position;
use noodles_sam as sam;
const REFERENCE_SEQUENCE_ID_RANGE: Range<usize> = 0..4;
const ALIGNMENT_START_RANGE: Range<usize> = 4..8;
const MAPPING_QUALITY_RANGE: Range<usize> = 9..10;
const FLAGS_RANGE: Range<usize> = 14..16;
const MATE_REFERENCE_SEQUENCE_ID_RANGE: Range<usize> = 20..24;
const MATE_ALIGNMENT_START_RANGE: Range<usize> = 24..28;
const TEMPLATE_LENGTH_RANGE: Range<usize> = 28..32;
#[derive(Clone, Debug, Eq, PartialEq)]
struct Bounds {
read_name_end: usize,
cigar_end: usize,
sequence_end: usize,
quality_scores_end: usize,
}
impl Bounds {
fn read_name_range(&self) -> Range<usize> {
TEMPLATE_LENGTH_RANGE.end..self.read_name_end
}
fn cigar_range(&self) -> Range<usize> {
self.read_name_end..self.cigar_end
}
fn sequence_range(&self) -> Range<usize> {
self.cigar_end..self.sequence_end
}
fn quality_scores_range(&self) -> Range<usize> {
self.sequence_end..self.quality_scores_end
}
fn data_range(&self) -> RangeFrom<usize> {
self.quality_scores_end..
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Record {
pub(crate) buf: Vec<u8>,
bounds: Bounds,
}
impl Record {
pub fn reference_sequence_id(&self) -> io::Result<Option<usize>> {
use crate::reader::record::get_reference_sequence_id;
let mut src = &self.buf[REFERENCE_SEQUENCE_ID_RANGE];
get_reference_sequence_id(&mut src)
}
pub fn alignment_start(&self) -> io::Result<Option<Position>> {
use crate::reader::record::get_position;
let mut src = &self.buf[ALIGNMENT_START_RANGE];
get_position(&mut src)
}
pub fn mapping_quality(&self) -> io::Result<Option<sam::record::MappingQuality>> {
use crate::reader::record::get_mapping_quality;
let mut src = &self.buf[MAPPING_QUALITY_RANGE];
get_mapping_quality(&mut src)
}
pub fn flags(&self) -> io::Result<sam::record::Flags> {
use crate::reader::record::get_flags;
let mut src = &self.buf[FLAGS_RANGE];
get_flags(&mut src)
}
pub fn mate_reference_sequence_id(&self) -> io::Result<Option<usize>> {
use crate::reader::record::get_reference_sequence_id;
let mut src = &self.buf[MATE_REFERENCE_SEQUENCE_ID_RANGE];
get_reference_sequence_id(&mut src)
}
pub fn mate_alignment_start(&self) -> io::Result<Option<Position>> {
use crate::reader::record::get_position;
let mut src = &self.buf[MATE_ALIGNMENT_START_RANGE];
get_position(&mut src)
}
pub fn template_length(&self) -> i32 {
let src = &self.buf[TEMPLATE_LENGTH_RANGE];
LittleEndian::read_i32(src)
}
pub fn read_name(&self) -> io::Result<Option<sam::record::ReadName>> {
use crate::reader::record::get_read_name;
let mut src = &self.buf[self.bounds.read_name_range()];
let mut read_name = None;
let len = NonZeroUsize::try_from(src.len())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
get_read_name(&mut src, &mut read_name, len)?;
Ok(read_name)
}
pub fn cigar(&self) -> Cigar<'_> {
let src = &self.buf[self.bounds.cigar_range()];
Cigar::new(src)
}
pub fn sequence(&self) -> Sequence<'_> {
let src = &self.buf[self.bounds.sequence_range()];
let quality_scores_range = self.bounds.quality_scores_range();
let base_count = quality_scores_range.end - quality_scores_range.start;
Sequence::new(src, base_count)
}
pub fn quality_scores(&self) -> QualityScores<'_> {
let src = &self.buf[self.bounds.quality_scores_range()];
QualityScores::new(src)
}
pub fn data(&self) -> Data {
let src = &self.buf[self.bounds.data_range()];
Data::new(src)
}
pub(crate) fn index(&mut self) -> io::Result<()> {
index(&self.buf[..], &mut self.bounds)
}
}
impl fmt::Debug for Record {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Record")
.field("reference_sequence_id", &self.reference_sequence_id())
.field("alignment_start", &self.alignment_start())
.field("mapping_quality", &self.mapping_quality())
.field("flags", &self.flags())
.field(
"mate_reference_sequence_id",
&self.mate_reference_sequence_id(),
)
.field("mate_alignment_start", &self.mate_alignment_start())
.field("template_length", &self.template_length())
.field("read_name", &self.read_name())
.field("cigar", &self.cigar())
.field("sequence", &self.sequence())
.field("quality_scores", &self.quality_scores())
.field("data", &self.data())
.finish()
}
}
impl AsRef<[u8]> for Record {
fn as_ref(&self) -> &[u8] {
&self.buf
}
}
impl TryFrom<Vec<u8>> for Record {
type Error = io::Error;
fn try_from(buf: Vec<u8>) -> Result<Self, Self::Error> {
let mut bounds = Bounds {
read_name_end: 0,
cigar_end: 0,
sequence_end: 0,
quality_scores_end: 0,
};
index(&buf, &mut bounds)?;
Ok(Record { buf, bounds })
}
}
impl Default for Record {
fn default() -> Self {
let buf = vec![
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0xff, 0x48, 0x12, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, b'*', 0x00, ];
let bounds = Bounds {
read_name_end: buf.len(),
cigar_end: buf.len(),
sequence_end: buf.len(),
quality_scores_end: buf.len(),
};
Self { buf, bounds }
}
}
fn index(buf: &[u8], bounds: &mut Bounds) -> io::Result<()> {
const MIN_BUF_LENGTH: usize = TEMPLATE_LENGTH_RANGE.end;
const READ_NAME_LENGTH_RANGE: Range<usize> = 8..9;
const CIGAR_OP_COUNT_RANGE: Range<usize> = 12..14;
const READ_LENGTH_RANGE: Range<usize> = 16..20;
if buf.len() < MIN_BUF_LENGTH {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
}
let mut src = &buf[READ_NAME_LENGTH_RANGE];
let l_read_name = NonZeroUsize::new(usize::from(src.get_u8()))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid l_read_name"))?;
let mut src = &buf[CIGAR_OP_COUNT_RANGE];
let n_cigar_op = usize::from(src.get_u16_le());
let mut src = &buf[READ_LENGTH_RANGE];
let l_seq = usize::try_from(src.get_u32_le())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let mut i = TEMPLATE_LENGTH_RANGE.end;
i += usize::from(l_read_name);
bounds.read_name_end = i;
i += mem::size_of::<u32>() * n_cigar_op;
bounds.cigar_end = i;
i += (l_seq + 1) / 2;
bounds.sequence_end = i;
i += l_seq;
bounds.quality_scores_end = i;
if buf.len() < i {
Err(io::Error::from(io::ErrorKind::UnexpectedEof))
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
static DATA: &[u8] = &[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0xff, 0x48, 0x12, 0x01, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, b'*', 0x00, 0x40, 0x00, 0x00, 0x00, 0x12, 0x48, b'N', b'D', b'L', b'S', ];
#[test]
fn test_index() -> io::Result<()> {
let mut record = Record::default();
record.buf.clear();
record.buf.extend(DATA);
record.index()?;
assert_eq!(record.bounds.read_name_range(), 32..34);
assert_eq!(record.bounds.cigar_range(), 34..38);
assert_eq!(record.bounds.sequence_range(), 38..40);
assert_eq!(record.bounds.quality_scores_range(), 40..44);
assert_eq!(record.bounds.data_range(), 44..);
Ok(())
}
#[test]
fn test_try_from_vec_u8_for_record() -> io::Result<()> {
let record = Record::try_from(DATA.to_vec())?;
assert_eq!(record.buf, DATA);
assert_eq!(record.bounds.read_name_range(), 32..34);
assert_eq!(record.bounds.cigar_range(), 34..38);
assert_eq!(record.bounds.sequence_range(), 38..40);
assert_eq!(record.bounds.quality_scores_range(), 40..44);
assert_eq!(record.bounds.data_range(), 44..);
Ok(())
}
}