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::{self, BufRead},
    ops::Not,
};

pub(super) struct Reader<R> {
    lines: io::Lines<io::BufReader<R>>,
    should_trim: bool,
}

impl<R: io::Read> Reader<R> {
    pub fn new(reader: R, should_trim: bool) -> Self {
        let lines = io::BufReader::new(reader).lines();
        Self { lines, should_trim }
    }

    pub fn next_block(&mut self) -> io::Result<Option<Vec<String>>> {
        let trim = |s: &str| (if self.should_trim { s.trim() } else { s }).to_string();
        let block: Vec<_> = self
            .lines
            .by_ref()
            .map(|line| Ok(trim(&line?)))
            .skip_while(|res| matches!(res, Ok(line) if line.is_empty()))
            .take_while(|res| matches!(res, Ok(line) if !line.is_empty()))
            .collect::<io::Result<_>>()?;
        Ok(block.is_empty().not().then(|| block))
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_normal() {
        let text = [
            "",
            "",
            "block 1, line 1",
            "block 1, line 2",
            " ",
            "",
            "",
            " ",
            "",
            "block 2, line 1",
            "",
            "",
        ]
        .join("\n");
        let mut reader = Reader::new(io::Cursor::new(text), false);
        assert_eq!(
            reader.next_block().unwrap().unwrap(),
            vec!["block 1, line 1", "block 1, line 2", " "]
        );
        assert_eq!(reader.next_block().unwrap().unwrap(), vec![" "]);
        assert_eq!(
            reader.next_block().unwrap().unwrap(),
            vec!["block 2, line 1"]
        );
        assert_eq!(reader.next_block().unwrap(), None);
    }

    #[test]
    fn test_trimmed() {
        let text = [" ", "block", " ", "", " ", ""].join("\n");
        let mut reader = Reader::new(io::Cursor::new(text), true);
        assert_eq!(reader.next_block().unwrap().unwrap(), vec!["block"]);
        assert_eq!(reader.next_block().unwrap(), None);
    }
}