read_lines_into/buf_reader/
read_lines_into_vec_string_with_trim.rs

1use std::fs::File;
2use std::io::BufReader;
3use std::io::BufRead;
4use crate::traits::*;
5
6impl ReadLinesIntoStringsWithTrimOnSelf for BufReader<File> {
7
8    /// Read lines into Vec<String>; trim each line of whitespace.
9    /// 
10    /// ```
11    /// use std::fs::File;
12    /// use std::io::BufReader;
13    /// use read_lines_into::traits::*;
14    /// 
15    /// let file: File = File::open("example.txt").unwrap();
16    /// let mut buf_reader = BufReader::new(file);
17    /// let strings: Vec<String> = buf_reader.read_lines_into_vec_string_with_trim().unwrap();
18    /// ```
19    /// 
20    /// Any error will return immediately.
21    /// 
22    fn read_lines_into_vec_string_with_trim(self) -> ::std::io::Result<Vec<String>> {
23        let mut strings = Vec::<String>::new();
24        let lines = self.lines();
25        for line in lines {
26            let x = line?;
27            strings.push(String::from(x.trim()));
28        }
29        Ok(strings)
30    }
31
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    fn sut(path_str: &str) -> BufReader<File> {
39        BufReader::new(File::open(path_str).unwrap())
40    }
41
42    #[test]
43    fn with_lf() {
44        let buf_reader = sut("example.txt");
45        assert_eq!(
46            buf_reader.read_lines_into_vec_string_with_trim().unwrap(),
47            vec![String::from("lorem"), String::from("ipsum")]
48        );
49    }
50
51    #[test]
52    fn with_crlf() {
53        let buf_reader = sut("example-with-crlf.txt");
54        assert_eq!(
55            buf_reader.read_lines_into_vec_string_with_trim().unwrap(),
56            vec![String::from("lorem"), String::from("ipsum")]
57        );
58    }
59
60    #[test]
61    fn with_indent() {
62        let buf_reader = sut("example-with-indent.txt");
63        assert_eq!(
64            buf_reader.read_lines_into_vec_string_with_trim().unwrap(),
65            vec![String::from("lorem"), String::from("ipsum")]
66        );
67    }
68
69}