/
fasta.rs
1793 lines (1602 loc) · 54.1 KB
/
fasta.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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014-2018 Johannes Köster, Christopher Schröder, Henning Timm.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Structs and trait to read and write files in FASTA format.
//!
//! # Example
//!
//! ## Read
//!
//! In this example, we parse a fasta file from stdin and compute some statistics
//!
//! ```no_run
//! use bio::io::fasta;
//! use std::io;
//!
//! let mut reader = fasta::Reader::new(io::stdin());
//!
//! let mut nb_reads = 0;
//! let mut nb_bases = 0;
//!
//! for result in reader.records() {
//! let record = result.expect("Error during fasta record parsing");
//! println!("{}", record.id());
//!
//! nb_reads += 1;
//! nb_bases += record.seq().len();
//! }
//!
//! println!("Number of reads: {}", nb_reads);
//! println!("Number of bases: {}", nb_bases);
//! ```
//!
//! We can also use a `while` loop to iterate over records.
//! This is slightly faster than the `for` loop.
//! ```no_run
//! use bio::io::fasta;
//! use std::io;
//! let mut records = fasta::Reader::new(io::stdin()).records();
//!
//! let mut nb_reads = 0;
//! let mut nb_bases = 0;
//!
//! while let Some(Ok(record)) = records.next() {
//! nb_reads += 1;
//! nb_bases += record.seq().len();
//! }
//!
//! println!("Number of reads: {}", nb_reads);
//! println!("Number of bases: {}", nb_bases);
//! ```
//!
//! ## Write
//!
//! In this example we generate 10 random sequences with length 100 and write them to stdout.
//!
//! ```
//! use std::io;
//! use bio::io::fasta;
//!
//! let mut seed = 42;
//!
//! let nucleotides = [b'A', b'C', b'G', b'T'];
//!
//! let mut writer = fasta::Writer::new(io::stdout());
//!
//! for _ in 0..10 {
//! let seq = (0..100).map(|_| {
//! seed = ((seed ^ seed << 13) ^ seed >> 7) ^ seed << 17; // don't use this random generator
//! nucleotides[seed % 4]
//! }).collect::<Vec<u8>>();
//!
//! writer.write("random", None, seq.as_slice()).expect("Error writing record.");
//! }
//! ```
//!
//! ## Read and Write
//!
//! In this example we filter reads from stdin on sequence length and write them to stdout
//!
//! ```no_run
//! use bio::io::fasta;
//! use bio::io::fasta::FastaRead;
//! use std::io;
//!
//! let mut reader = fasta::Reader::new(io::stdin());
//! let mut writer = fasta::Writer::new(io::stdout());
//! let mut record = fasta::Record::new();
//!
//! while let Ok(()) = reader.read(&mut record) {
//! if record.is_empty() {
//! break;
//! }
//!
//! if record.seq().len() > 100 {
//! writer
//! .write_record(&record)
//! .ok()
//! .expect("Error writing record.");
//! }
//! }
//! ```
//!
//! ## Index
//!
//! Random access to FASTA files is facilitated by [`Index`] and [`IndexedReader`]. The FASTA files
//! must already be indexed with [`samtools faidx`](https://www.htslib.org/doc/faidx.html).
//!
//! In this example, we read in the first 10 bases of the sequence named "chr1".
//!
//! ```rust
//! use bio::io::fasta::IndexedReader;
//! // create dummy files
//! const FASTA_FILE: &[u8] = b">chr1\nGTAGGCTGAAAA\nCCCC";
//! const FAI_FILE: &[u8] = b"chr1\t16\t6\t12\t13";
//!
//! let seq_name = "chr1";
//! let start: u64 = 0; // start is 0-based, inclusive
//! let stop: u64 = 10; // stop is 0-based, exclusive
//! // load the index
//! let mut faidx = IndexedReader::new(std::io::Cursor::new(FASTA_FILE), FAI_FILE).unwrap();
//! // move the pointer in the index to the desired sequence and interval
//! faidx
//! .fetch(seq_name, start, stop)
//! .expect("Couldn't fetch interval");
//! // read the subsequence defined by the interval into a vector
//! let mut seq = Vec::new();
//! faidx.read(&mut seq).expect("Couldn't read the interval");
//! assert_eq!(seq, b"GTAGGCTGAA");
//! ```
use std::cmp::min;
use std::collections;
use std::convert::AsRef;
use std::fs;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use crate::utils::{Text, TextSlice};
use anyhow::Context;
use std::fmt;
/// Maximum size of temporary buffer used for reading indexed FASTA files.
const MAX_FASTA_BUFFER_SIZE: usize = 512;
/// Trait for FASTA readers.
pub trait FastaRead {
fn read(&mut self, record: &mut Record) -> io::Result<()>;
}
/// A FASTA reader.
#[derive(Default, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct Reader<B> {
reader: B,
line: String,
}
impl Reader<io::BufReader<fs::File>> {
/// Read FASTA from given file path.
pub fn from_file<P: AsRef<Path> + std::fmt::Debug>(path: P) -> anyhow::Result<Self> {
fs::File::open(&path)
.map(Reader::new)
.with_context(|| format!("Failed to read fasta from {:#?}", path))
}
/// Read FASTA from give file path and a capacity
pub fn from_file_with_capacity<P: AsRef<Path> + std::fmt::Debug>(
capacity: usize,
path: P,
) -> anyhow::Result<Self> {
fs::File::open(&path)
.map(|file| Reader::with_capacity(capacity, file))
.with_context(|| format!("Failed to read fasta from {:#?}", path))
}
}
impl<R> Reader<io::BufReader<R>>
where
R: io::Read,
{
/// Create a new Fasta reader given an instance of `io::Read`.
///
/// # Example
/// ```rust
/// # use std::io;
/// # use bio::io::fasta::Reader;
/// # fn main() {
/// # const fasta_file: &'static [u8] = b">id desc
/// # AAAA
/// # ";
/// let reader = Reader::new(fasta_file);
/// # }
/// ```
pub fn new(reader: R) -> Self {
Reader {
reader: io::BufReader::new(reader),
line: String::new(),
}
}
/// Create a new Fasta reader given a capacity and an instance of `io::Read`.
///
/// # Example
/// ```rust
/// # use std::io;
/// # use bio::io::fasta::Reader;
/// # fn main() {
/// # const fasta_file: &'static [u8] = b">id desc
/// # AAAA
/// # ";
/// let reader = Reader::with_capacity(16384, fasta_file);
/// # }
/// ```
pub fn with_capacity(capacity: usize, reader: R) -> Self {
Reader {
reader: io::BufReader::with_capacity(capacity, reader),
line: String::new(),
}
}
}
impl<B> Reader<B>
where
B: io::BufRead,
{
/// Create a new Fasta reader with an object that implements `io::BufRead`.
///
/// # Example
/// ```rust
/// # use std::io;
/// # use bio::io::fasta::Reader;
/// # fn main() {
/// # const fasta_file: &'static [u8] = b">id desc
/// # AAAA
/// # ";
/// let buffer = io::BufReader::with_capacity(16384, fasta_file);
/// let reader = Reader::from_bufread(buffer);
/// # }
/// ```
pub fn from_bufread(bufreader: B) -> Self {
Reader {
reader: bufreader,
line: String::new(),
}
}
/// Return an iterator over the records of this Fasta file.
///
/// # Example
/// ```rust
/// # use std::io;
/// # use bio::io::fasta::Reader;
/// # use bio::io::fasta::Record;
/// # fn main() {
/// # const fasta_file: &'static [u8] = b">id desc
/// # AAAA
/// # ";
/// # let reader = Reader::new(fasta_file);
/// for record in reader.records() {
/// let record = record.unwrap();
/// assert_eq!(record.id(), "id");
/// assert_eq!(record.desc().unwrap(), "desc");
/// assert_eq!(record.seq().to_vec(), b"AAAA");
/// }
/// # }
/// ```
pub fn records(self) -> Records<B> {
Records {
reader: self,
error_has_occured: false,
}
}
}
impl<B> FastaRead for Reader<B>
where
B: io::BufRead,
{
/// Read the next FASTA record into the given `Record`.
/// An empty record indicates that no more records can be read.
///
/// Use this method when you want to read records as fast as
/// possible because it allows the reuse of a `Record` allocation.
///
/// The [records](Reader::records) iterator provides a more ergonomic
/// approach to accessing FASTA records.
///
/// # Errors
///
/// This function will return an error if the record is incomplete,
/// syntax is violated or any form of I/O error is encountered.
///
/// # Example
///
/// ```rust
/// use bio::io::fasta::Record;
/// use bio::io::fasta::{FastaRead, Reader};
///
/// const fasta_file: &'static [u8] = b">id desc
/// AAAA
/// ";
/// let mut reader = Reader::new(fasta_file);
/// let mut record = Record::new();
///
/// // Check for errors parsing the record
/// reader
/// .read(&mut record)
/// .expect("fasta reader: got an io::Error or could not read_line()");
///
/// assert_eq!(record.id(), "id");
/// assert_eq!(record.desc().unwrap(), "desc");
/// assert_eq!(record.seq().to_vec(), b"AAAA");
/// ```
fn read(&mut self, record: &mut Record) -> io::Result<()> {
record.clear();
if self.line.is_empty() {
self.reader.read_line(&mut self.line)?;
if self.line.is_empty() {
return Ok(());
}
}
if !self.line.starts_with('>') {
return Err(io::Error::new(
io::ErrorKind::Other,
"Expected > at record start.",
));
}
let mut header_fields = self.line[1..].trim_end().splitn(2, char::is_whitespace);
record.id = header_fields.next().map(|s| s.to_owned()).unwrap();
record.desc = header_fields.next().map(|s| s.to_owned());
loop {
self.line.clear();
self.reader.read_line(&mut self.line)?;
if self.line.is_empty() || self.line.starts_with('>') {
break;
}
record.seq.push_str(self.line.trim_end());
}
Ok(())
}
}
/// A FASTA index as created by SAMtools (.fai).
#[derive(Default, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub struct Index {
inner: Vec<IndexRecord>,
name_to_rid: collections::HashMap<String, usize>,
}
impl Index {
/// Open a FASTA index from a given `io::Read` instance.
pub fn new<R: io::Read>(fai: R) -> csv::Result<Self> {
let mut inner = vec![];
let mut name_to_rid = collections::HashMap::new();
let mut fai_reader = csv::ReaderBuilder::new()
.delimiter(b'\t')
.has_headers(false)
.from_reader(fai);
for (rid, row) in fai_reader.deserialize().enumerate() {
let record: IndexRecord = row?;
name_to_rid.insert(record.name.clone(), rid);
inner.push(record);
}
Ok(Index { inner, name_to_rid })
}
/// Open a FASTA index from a given file path.
pub fn from_file<P: AsRef<Path> + std::fmt::Debug>(path: &P) -> anyhow::Result<Self> {
fs::File::open(&path)
.map_err(csv::Error::from)
.and_then(Self::new)
.with_context(|| format!("Failed to read fasta index from {:#?}", path))
}
/// Open a FASTA index given the corresponding FASTA file path.
/// That is, for ref.fasta we expect ref.fasta.fai.
pub fn with_fasta_file<P: AsRef<Path>>(fasta_path: &P) -> anyhow::Result<Self> {
let mut fai_path = fasta_path.as_ref().as_os_str().to_owned();
fai_path.push(".fai");
Self::from_file(&fai_path)
}
/// Return a vector of sequences described in the index.
pub fn sequences(&self) -> Vec<Sequence> {
// sort kv pairs by rid to preserve order
self.inner
.iter()
.map(|record| Sequence {
name: record.name.clone(),
len: record.len,
})
.collect()
}
}
/// A FASTA reader with an index as created by SAMtools (.fai).
#[derive(Debug)]
pub struct IndexedReader<R: io::Read + io::Seek> {
reader: io::BufReader<R>,
pub index: Index,
fetched_idx: Option<IndexRecord>,
start: Option<u64>,
stop: Option<u64>,
}
impl IndexedReader<fs::File> {
/// Read from a given file path. This assumes the index ref.fasta.fai to be
/// present for FASTA ref.fasta.
pub fn from_file<P: AsRef<Path> + std::fmt::Debug>(path: &P) -> anyhow::Result<Self> {
let index = Index::with_fasta_file(path)?;
fs::File::open(&path)
.map(|f| Self::with_index(f, index))
.map_err(csv::Error::from)
.with_context(|| format!("Failed to read fasta from {:#?}", path))
}
}
impl<R: io::Read + io::Seek> IndexedReader<R> {
/// Read from a FASTA and its index, both given as `io::Read`. FASTA has to
/// be `io::Seek` in addition.
pub fn new<I: io::Read>(fasta: R, fai: I) -> csv::Result<Self> {
let index = Index::new(fai)?;
Ok(IndexedReader {
reader: io::BufReader::new(fasta),
index,
fetched_idx: None,
start: None,
stop: None,
})
}
/// Read from a FASTA and its index, the first given as `io::Read`, the
/// second given as index object.
pub fn with_index(fasta: R, index: Index) -> Self {
IndexedReader {
reader: io::BufReader::new(fasta),
index,
fetched_idx: None,
start: None,
stop: None,
}
}
/// Fetch an interval from the sequence with the given name for reading.
///
/// `start` and `stop` are 0-based and `stop` is exclusive - i.e. `[start, stop)`
///
/// # Example
///
/// ```rust
/// use bio::io::fasta::IndexedReader;
/// // create dummy files
/// const FASTA_FILE: &[u8] = b">chr1\nGTAGGCTGAAAA\nCCCC";
/// const FAI_FILE: &[u8] = b"chr1\t16\t6\t12\t13";
///
/// let seq_name = "chr1";
/// let start: u64 = 0; // start is 0-based, inclusive
/// let stop: u64 = 10; // stop is 0-based, exclusive
/// // load the index
/// let mut faidx = IndexedReader::new(std::io::Cursor::new(FASTA_FILE), FAI_FILE).unwrap();
/// // move the pointer in the index to the desired sequence and interval
/// faidx
/// .fetch(seq_name, start, stop)
/// .expect("Couldn't fetch interval");
/// // read the subsequence defined by the interval into a vector
/// let mut seq = Vec::new();
/// faidx.read(&mut seq).expect("Couldn't read the interval");
/// assert_eq!(seq, b"GTAGGCTGAA");
/// ```
///
/// # Errors
/// If the `seq_name` does not exist within the index.
pub fn fetch(&mut self, seq_name: &str, start: u64, stop: u64) -> io::Result<()> {
let idx = self.idx(seq_name)?;
self.start = Some(start);
self.stop = Some(stop);
self.fetched_idx = Some(idx);
Ok(())
}
/// Fetch an interval from the sequence with the given record index for reading.
///
/// `start` and `stop` are 0-based and `stop` is exclusive - i.e. `[start, stop)`
///
/// # Example
///
/// ```rust
/// use bio::io::fasta::IndexedReader;
/// // create dummy files
/// const FASTA_FILE: &[u8] = b">chr1\nGTAGGCTGAAAA\nCCCC";
/// const FAI_FILE: &[u8] = b"chr1\t16\t6\t12\t13";
///
/// let rid: usize = 0;
/// let start: u64 = 0; // start is 0-based, inclusive
/// let stop: u64 = 10; // stop is 0-based, exclusive
/// // load the index
/// let mut faidx = IndexedReader::new(std::io::Cursor::new(FASTA_FILE), FAI_FILE).unwrap();
/// // move the pointer in the index to the desired sequence and interval
/// faidx
/// .fetch_by_rid(rid, start, stop)
/// .expect("Couldn't fetch interval");
/// // read the subsequence defined by the interval into a vector
/// let mut seq = Vec::new();
/// faidx.read(&mut seq).expect("Couldn't read the interval");
/// assert_eq!(seq, b"GTAGGCTGAA");
/// ```
///
/// # Errors
/// If `rid` does not exist within the index.
pub fn fetch_by_rid(&mut self, rid: usize, start: u64, stop: u64) -> io::Result<()> {
let idx = self.idx_by_rid(rid)?;
self.start = Some(start);
self.stop = Some(stop);
self.fetched_idx = Some(idx);
Ok(())
}
/// Fetch the whole sequence with the given name for reading.
pub fn fetch_all(&mut self, seq_name: &str) -> io::Result<()> {
let idx = self.idx(seq_name)?;
self.start = Some(0);
self.stop = Some(idx.len);
self.fetched_idx = Some(idx);
Ok(())
}
/// Fetch the whole sequence with the given record index for reading.
pub fn fetch_all_by_rid(&mut self, rid: usize) -> io::Result<()> {
let idx = self.idx_by_rid(rid)?;
self.start = Some(0);
self.stop = Some(idx.len);
self.fetched_idx = Some(idx);
Ok(())
}
/// Read the fetched sequence into the given vector.
pub fn read(&mut self, seq: &mut Text) -> io::Result<()> {
let idx = self.fetched_idx.clone();
match (idx, self.start, self.stop) {
(Some(idx), Some(start), Some(stop)) => self.read_into_buffer(idx, start, stop, seq),
_ => Err(io::Error::new(
io::ErrorKind::Other,
"No sequence fetched for reading.",
)),
}
}
/// Return an iterator yielding the fetched sequence.
pub fn read_iter(&mut self) -> io::Result<IndexedReaderIterator<'_, R>> {
let idx = self.fetched_idx.clone();
match (idx, self.start, self.stop) {
(Some(idx), Some(start), Some(stop)) => self.read_into_iter(idx, start, stop),
_ => Err(io::Error::new(
io::ErrorKind::Other,
"No sequence fetched for reading.",
)),
}
}
fn read_into_buffer(
&mut self,
idx: IndexRecord,
start: u64,
stop: u64,
seq: &mut Text,
) -> io::Result<()> {
if stop > idx.len {
return Err(io::Error::new(
io::ErrorKind::Other,
"FASTA read interval was out of bounds",
));
} else if start > stop {
return Err(io::Error::new(
io::ErrorKind::Other,
"Invalid query interval",
));
}
let mut bases_left = stop - start;
let mut line_offset = self.seek_to(&idx, start)?;
seq.clear();
while bases_left > 0 {
bases_left -= self.read_line(&idx, &mut line_offset, bases_left, seq)?;
}
Ok(())
}
fn read_into_iter(
&mut self,
idx: IndexRecord,
start: u64,
stop: u64,
) -> io::Result<IndexedReaderIterator<'_, R>> {
if stop > idx.len {
return Err(io::Error::new(
io::ErrorKind::Other,
"FASTA read interval was out of bounds",
));
} else if start > stop {
return Err(io::Error::new(
io::ErrorKind::Other,
"Invalid query interval",
));
}
let bases_left = stop - start;
let line_offset = self.seek_to(&idx, start)?;
let capacity = min(
MAX_FASTA_BUFFER_SIZE,
min(bases_left, idx.line_bases) as usize,
);
Ok(IndexedReaderIterator {
reader: self,
record: idx,
bases_left,
line_offset,
buf: Vec::with_capacity(capacity),
buf_idx: 0,
})
}
/// Return the IndexRecord for the given sequence name or io::Result::Err
fn idx(&self, seqname: &str) -> io::Result<IndexRecord> {
match self.index.name_to_rid.get(seqname) {
Some(rid) => self.idx_by_rid(*rid),
None => Err(io::Error::new(
io::ErrorKind::Other,
format!("Unknown sequence name: {}.", seqname),
)),
}
}
/// Return the IndexRecord for the given record index or io::Result::Err
fn idx_by_rid(&self, rid: usize) -> io::Result<IndexRecord> {
match self.index.inner.get(rid) {
Some(record) => Ok(record.clone()),
None => Err(io::Error::new(
io::ErrorKind::Other,
"Invalid record index in fasta file.",
)),
}
}
/// Seek to the given position in the specified FASTA record. The position
/// of the cursor on the line that the seek ended on is returned.
fn seek_to(&mut self, idx: &IndexRecord, start: u64) -> io::Result<u64> {
assert!(start <= idx.len);
let line_offset = start % idx.line_bases;
let line_start = start / idx.line_bases * idx.line_bytes;
let offset = idx.offset + line_start + line_offset;
self.reader.seek(io::SeekFrom::Start(offset))?;
Ok(line_offset)
}
/// Tries to read up to `bases_left` bases from the current line into `buf`,
/// returning the actual number of bases read. Depending on the amount of
/// whitespace per line, the current `line_offset`, and the amount of bytes
/// returned from `BufReader::fill_buf`, this function may return Ok(0)
/// multiple times in a row.
fn read_line(
&mut self,
idx: &IndexRecord,
line_offset: &mut u64,
bases_left: u64,
buf: &mut Vec<u8>,
) -> io::Result<u64> {
let (bytes_to_read, bytes_to_keep) = {
let src = self.reader.fill_buf()?;
if src.is_empty() {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"FASTA file is truncated.",
));
}
let bases_on_line = idx.line_bases - min(idx.line_bases, *line_offset);
let bases_in_buffer = min(src.len() as u64, bases_on_line);
let (bytes_to_read, bytes_to_keep) = if bases_in_buffer <= bases_left {
let bytes_to_read = min(src.len() as u64, idx.line_bytes - *line_offset);
(bytes_to_read, bases_in_buffer)
} else {
(bases_left, bases_left)
};
buf.extend_from_slice(&src[..bytes_to_keep as usize]);
(bytes_to_read, bytes_to_keep)
};
self.reader.consume(bytes_to_read as usize);
assert!(bytes_to_read > 0);
*line_offset += bytes_to_read;
if *line_offset >= idx.line_bytes {
*line_offset = 0;
}
Ok(bytes_to_keep)
}
}
/// Record of a FASTA index.
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
struct IndexRecord {
name: String,
len: u64,
offset: u64,
line_bases: u64,
line_bytes: u64,
}
/// A sequence record returned by the FASTA index.
#[derive(Default, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct Sequence {
pub name: String,
pub len: u64,
}
#[derive(Debug)]
pub struct IndexedReaderIterator<'a, R: io::Read + io::Seek> {
reader: &'a mut IndexedReader<R>,
record: IndexRecord,
bases_left: u64,
line_offset: u64,
buf: Vec<u8>,
buf_idx: usize,
}
impl<'a, R: io::Read + io::Seek + 'a> IndexedReaderIterator<'a, R> {
fn fill_buffer(&mut self) -> io::Result<()> {
assert!(self.bases_left > 0);
self.buf.clear();
let bases_to_read = min(self.buf.capacity() as u64, self.bases_left);
// May loop one or more times; see IndexedReader::read_line.
while self.buf.is_empty() {
self.bases_left -= self.reader.read_line(
&self.record,
&mut self.line_offset,
bases_to_read,
&mut self.buf,
)?;
}
self.buf_idx = 0;
Ok(())
}
}
impl<'a, R: io::Read + io::Seek + 'a> Iterator for IndexedReaderIterator<'a, R> {
type Item = io::Result<u8>;
fn next(&mut self) -> Option<Self::Item> {
if self.buf_idx < self.buf.len() {
let item = Some(Ok(self.buf[self.buf_idx]));
self.buf_idx += 1;
item
} else if self.bases_left > 0 {
if let Err(e) = self.fill_buffer() {
self.bases_left = 0;
self.buf_idx = self.buf.len();
return Some(Err(e));
}
self.buf_idx = 1;
Some(Ok(self.buf[0]))
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let hint = self.bases_left as usize + (self.buf.len() - self.buf_idx);
(hint, Some(hint))
}
}
/// A Fasta writer.
#[derive(Debug)]
pub struct Writer<W: io::Write> {
writer: io::BufWriter<W>,
}
impl Writer<fs::File> {
/// Write to the given file path.
#[allow(clippy::wrong_self_convention)]
pub fn to_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
fs::File::create(path).map(Writer::new)
}
/// Write to the given file path and a buffer capacity
pub fn to_file_with_capacity<P: AsRef<Path>>(capacity: usize, path: P) -> io::Result<Self> {
fs::File::create(path).map(|file| Writer::with_capacity(capacity, file))
}
}
impl<W: io::Write> Writer<W> {
/// Create a new Fasta writer.
pub fn new(writer: W) -> Self {
Writer {
writer: io::BufWriter::new(writer),
}
}
/// Create a new Fasta writer with a capacity of write buffer
pub fn with_capacity(capacity: usize, writer: W) -> Self {
Writer {
writer: io::BufWriter::with_capacity(capacity, writer),
}
}
/// Create a new Fasta writer with a given BufWriter
pub fn from_bufwriter(bufwriter: io::BufWriter<W>) -> Self {
Writer { writer: bufwriter }
}
/// Directly write a [`fasta::Record`](struct.Record.html).
///
/// # Errors
/// If there is an issue writing to the `Writer`.
///
/// # Examples
/// ```rust
/// use bio::io::fasta::{Record, Writer};
/// use std::fs;
/// use std::io;
/// use std::path::Path;
///
/// let path = Path::new("test.fa");
/// let file = fs::File::create(path).unwrap();
/// {
/// let handle = io::BufWriter::new(file);
/// let mut writer = Writer::new(handle);
/// let record = Record::with_attrs("id", Some("desc"), b"ACGT");
///
/// let write_result = writer.write_record(&record);
/// assert!(write_result.is_ok());
/// }
///
/// let actual = fs::read_to_string(path).unwrap();
/// let expected = ">id desc\nACGT\n";
///
/// assert!(fs::remove_file(path).is_ok());
/// assert_eq!(actual, expected)
/// ```
pub fn write_record(&mut self, record: &Record) -> io::Result<()> {
self.write(record.id(), record.desc(), record.seq())
}
/// Write a Fasta record with given id, optional description and sequence.
pub fn write(&mut self, id: &str, desc: Option<&str>, seq: TextSlice<'_>) -> io::Result<()> {
self.writer.write_all(b">")?;
self.writer.write_all(id.as_bytes())?;
if let Some(desc) = desc {
self.writer.write_all(b" ")?;
self.writer.write_all(desc.as_bytes())?;
}
self.writer.write_all(b"\n")?;
self.writer.write_all(seq)?;
self.writer.write_all(b"\n")?;
Ok(())
}
/// Flush the writer, ensuring that everything is written.
pub fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
/// A FASTA record.
#[derive(Default, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct Record {
id: String,
desc: Option<String>,
seq: String,
}
impl Record {
/// Create a new instance.
pub fn new() -> Self {
Record {
id: String::new(),
desc: None,
seq: String::new(),
}
}
/// Create a new `Record` from given attributes.
///
/// # Examples
/// ```rust
/// use bio::io::fasta::Record;
///
/// let read_id = "read1";
/// let description = Some("sampleid=foobar");
/// let sequence = b"ACGT";
/// let record = Record::with_attrs(read_id, description, sequence);
///
/// assert_eq!(">read1 sampleid=foobar\nACGT\n", record.to_string())
/// ```
pub fn with_attrs(id: &str, desc: Option<&str>, seq: TextSlice<'_>) -> Self {
let desc = desc.map(|desc| desc.to_owned());
Record {
id: id.to_owned(),
desc,
seq: String::from_utf8(seq.to_vec()).unwrap(),
}
}
/// Check if record is empty.
pub fn is_empty(&self) -> bool {
self.id.is_empty() && self.desc.is_none() && self.seq.is_empty()
}
/// Check validity of Fasta record.
pub fn check(&self) -> Result<(), &str> {
if self.id().is_empty() {
return Err("Expecting id for Fasta record.");
}
if !self.seq.is_ascii() {
return Err("Non-ascii character found in sequence.");
}
Ok(())
}
/// Return the id of the record.
pub fn id(&self) -> &str {
self.id.as_ref()
}
/// Return descriptions if present.
pub fn desc(&self) -> Option<&str> {
match self.desc.as_ref() {
Some(desc) => Some(desc),
None => None,
}
}
/// Return the sequence of the record.
pub fn seq(&self) -> TextSlice<'_> {
self.seq.as_bytes()
}
/// Clear the record.
fn clear(&mut self) {
self.id.clear();
self.desc = None;
self.seq.clear();
}
}
impl fmt::Display for Record {
/// Allows for using `Record` in a given formatter `f`. In general this is for
/// creating a `String` representation of a `Record` and, optionally, writing it to
/// a file.
///
/// # Errors
/// Returns [`std::fmt::Error`](https://doc.rust-lang.org/std/fmt/struct.Error.html)
/// if there is an issue formatting to the stream.
///
/// # Examples
///
/// Read in a Fasta `Record` and create a `String` representation of it.
///
/// ```rust
/// use bio::io::fasta::Reader;
/// use std::fmt::Write;
/// // create a "fake" fasta file
/// let fasta: &'static [u8] = b">id comment1 comment2\nACGT\n";
/// let mut records = Reader::new(fasta).records().map(|r| r.unwrap());
/// let record = records.next().unwrap();
///
/// let mut actual = String::new();
/// // populate `actual` with a string representation of our record
/// write!(actual, "{}", record).unwrap();
///
/// let expected = std::str::from_utf8(fasta).unwrap();
///
/// assert_eq!(actual, expected)
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
let header = match self.desc() {
Some(d) => format!("{} {}", self.id().to_owned(), d),