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
// [[file:~/Workspace/Programming/gchemol-rs/parser/parser.note::*imports][imports:1]]
use gut::fs::*;
use gut::prelude::*;

use std::io::Cursor;
// imports:1 ends here

// [[file:~/Workspace/Programming/gchemol-rs/parser/parser.note::*reader][reader:1]]
type FileReader = BufReader<File>;

fn text_file_reader<P: AsRef<Path>>(p: P) -> Result<FileReader> {
    let p = p.as_ref();
    debug!("Reader for file: {}", p.display());
    let f = File::open(p).with_context(|| format!("Failed to open file {:?}", p))?;

    let reader = BufReader::new(f);
    Ok(reader)
}

#[derive(Debug)]
/// A stream reader for large text file
pub struct TextReader<R: BufRead> {
    inner: R,
}

impl TextReader<FileReader> {
    /// Build a text reader for file from path `p`.
    pub fn from_path<P: AsRef<Path>>(p: P) -> Result<Self> {
        let reader = text_file_reader(p)?;
        let parser = Self { inner: reader };
        Ok(parser)
    }
}

impl<'a> TextReader<Cursor<&'a str>> {
    /// Build a text reader for string slice.
    pub fn from_str(s: &'a str) -> Self {
        let r = Cursor::new(s);
        TextReader { inner: r }
    }
}

impl<R: Read> TextReader<BufReader<R>> {
    /// Build a text reader from a struct implementing Read trait.
    pub fn new(r: R) -> Self {
        Self {
            inner: BufReader::new(r),
        }
    }
}

impl<R: BufRead + Seek> TextReader<R> {
    /// Skip reading until finding a matched line. Return the position before
    /// the matched line.
    pub fn seek_line<F>(&mut self, f: F) -> Result<u64>
    where
        F: Fn(&str) -> bool,
    {
        let mut line = String::new();
        let mut m = 0u64;
        loop {
            let n = self.inner.read_line(&mut line)?;
            if n == 0 {
                // EOF
                break;
            } else {
                // reverse the reading of the line
                if f(&line) {
                    // self.reader.seek(std::io::SeekFrom::Start(0));
                    // let mut s = vec![0; m];
                    // self.reader.read_exact(&mut s)?;
                    // return Ok(String::from_utf8(s).unwrap());
                    let _ = self.inner.seek(std::io::SeekFrom::Start(m))?;
                    return Ok(m);
                }
            }
            m += n as u64;
            line.clear();
        }

        Ok(m)
    }
}

impl<R: BufRead> TextReader<R> {
    /// Read a new line into buf. Note: the new line is forced to use unix style
    /// line ending.
    ///
    /// This function will return the total number of bytes read.
    ///
    /// If this function returns None, the stream has reached EOF.
    pub fn read_line(&mut self, buf: &mut String) -> Option<usize> {
        match self.inner.read_line(buf) {
            Ok(0) => {
                return None;
            }
            Err(e) => {
                // discard any read in buf
                error!("Read line failure: {:?}", e);
                return None;
            }
            Ok(mut n) => {
                // force to use Unix line ending
                if buf.ends_with("\r\n") {
                    let i = buf.len() - 2;
                    buf.remove(i);
                    n -= 1;
                }
                return Some(n);
            }
        }
    }

    /// Returns an iterator over the lines of this reader. Each string returned
    /// will not have a line ending.
    pub fn lines(self) -> impl Iterator<Item = String> {
        // silently ignore UTF-8 error
        self.inner
            .lines()
            .filter_map(|s| if let Ok(line) = s { Some(line) } else { None })
    }

    /// Read all text into string `buf` (Note: out of memory issue for large
    /// file)
    pub fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
        let n = self.inner.read_to_string(buf)?;
        Ok(n)
    }
}
// reader:1 ends here

// [[file:~/Workspace/Programming/gchemol-rs/parser/parser.note::*test][test:1]]
#[test]
fn test_reader() -> Result<()> {
    // test lines
    let f = "./tests/files/multi.xyz";
    let reader = TextReader::from_path(f)?;
    let line = reader.lines().skip(1).next().unwrap();
    assert_eq!(line, " Configuration number :        7");

    // test seeking
    let f = "./tests/files/ch3f.mol2";
    let mut reader = TextReader::from_path(f)?;
    let _ = reader.seek_line(|line| line.starts_with("@<TRIPOS>"))?;
    let line = reader.lines().next().expect("ch3f test");
    assert_eq!(line, "@<TRIPOS>MOLECULE");

    // test from_str
    let s = "abc\nabcd\r\nabcde\n";
    let reader = TextReader::from_str(s);
    let line = reader.lines().next().unwrap();
    assert_eq!(line, "abc");

    Ok(())
}
// test:1 ends here