Skip to main content

read_lines_with_blank/
lib.rs

1use std::env::consts::OS;
2use std::fs::File;
3use std::error::Error;
4use std::io::{self, Read};
5
6const NEW_LINE_WINDOWS: &str = "\r\n";
7const NEW_LINE_LINUX: &str = "\n";
8
9/// Read lines with blank lines included
10///
11/// # Example
12/// ```norun
13/// use read_lines_with_blank::read_lines_with_blank;
14///
15/// let lines = match read_lines_with_blank("foo_bar.txt") {
16///     Ok(x) => x,
17///     Err(e) => return Err(e),
18/// };
19/// ```
20pub fn read_lines_with_blank(file: &str) -> Result<Vec<String>, Box<dyn Error>> {
21    let mut ret: Vec<String> = Vec::new();
22    let new_line = match OS {
23        "linux" => NEW_LINE_LINUX,
24        "windows" => NEW_LINE_WINDOWS,
25        _ => return Err(Box::from(io::Error::new(io::ErrorKind::Unsupported, "Unsupported OS"))),
26    };
27
28    let f = File::open(file)?;
29    let mut reader = std::io::BufReader::new(f);
30
31    let mut data: Vec<u8> = Vec::new();
32    reader.read_to_end(&mut data)?;
33    let str: String = match String::from_utf8(data) {
34        Ok(s) => s,
35        Err(e) => return Err(Box::from(e)),
36    };
37
38    for v in str.split(new_line) {
39        ret.push(v.to_string());
40    }
41    Ok(ret)
42}
43
44/// Read lines with blank lines included
45///
46/// # Example
47/// ```norun
48/// use read_lines_with_blank::read_lines_with_blank_from_str;
49///
50/// let str: &str = "line1\n\n\nline2\n";
51/// let lines = match read_lines_with_blank_from_str(str) {
52///     Ok(x) => x,
53///     Err(e) => return Err(e),
54/// };
55/// ```
56pub fn read_lines_with_blank_from_str(str: &str) -> Result<Vec<String>, io::Error> {
57    let mut ret: Vec<String> = Vec::new();
58    let new_line = match OS {
59        "linux" => NEW_LINE_LINUX,
60        "windows" => NEW_LINE_WINDOWS,
61        _ => return Err(io::Error::new(io::ErrorKind::Unsupported, "Unsupported OS")),
62    };
63
64    for v in str.split(new_line) {
65        ret.push(v.to_string());
66    }
67    Ok(ret)
68}