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
use std::io::Read;

#[macro_use]
mod errors;
mod nom_parsers;
mod streaming_parser;
use self::streaming_parser::StreamParser;
use crate::errors::GbParserError;
use crate::seq::{Location, Seq};

#[derive(Debug)]
pub struct SeqReader<T: Read> {
    parser: StreamParser<T>,
}

impl<T: Read> Iterator for SeqReader<T> {
    type Item = Result<Seq, GbParserError>;

    fn next(&mut self) -> Option<Result<Seq, GbParserError>> {
        match self.parser.read_one_record() {
            Ok(Some(seq)) => Some(Ok(seq)),
            Ok(None) => None,
            Err(e) => Some(Err(e)),
        }
    }
}

const READ_BUF_SIZE: usize = 64 * 1024;

impl<T: Read> SeqReader<T> {
    /// Parse a stream one `Seq` at a time
    pub fn new(data: T) -> SeqReader<T> {
        SeqReader {
            parser: StreamParser::new(data, READ_BUF_SIZE),
        }
    }
}

/// Convenience method to parse an entire file at once. Uses the streaming parser.
pub fn parse_file<P: AsRef<::std::path::Path>>(path: P) -> Result<Vec<Seq>, GbParserError> {
    let file = ::std::fs::File::open(path)?;
    SeqReader::new(file).collect()
}

/// Parse an entire genbank file provided as a slice. Might be slightly faster
/// than the streaming parser used by `parse_file` and `SeqReader::from_stream` 
/// since less copying of data is required, however not as well tested. I recommend using
/// `SeqReader` instead. I've mainly left this here for benchmarking purposes.
pub fn parse_slice(data: &[u8]) -> Result<Vec<Seq>, GbParserError> {
    let res = nom_parsers::gb_records(data);
    match res {
        Ok((_, o)) => Ok(o),
        Err(e) => {
            Err(GbParserError::SyntaxError(
                format!("{:?}", e),
            ))
        }
    }
}

/// used by `Location::from_gb_format`
pub (crate) fn parse_location(data: &[u8]) -> Result<Location, GbParserError> {
    let res = nom_parsers::location(nom::types::CompleteByteSlice(data));
    match res {
        Ok((_, o)) => Ok(o),
        Err(e) => {
            Err(GbParserError::SyntaxError(
                format!("{:?}", e),
            ))
        }
    }
}