4 use std::iter::Iterator;
6 #[derive(Debug, PartialEq, Eq)]
12 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
14 row: Option<RowInput>,
16 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
18 fn new(input: Input) -> Self {
19 Self { input, row: None }
22 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
23 type Item = Result<RowInput, std::io::Error>;
24 fn next(&mut self) -> Option<Self::Item> {
26 match self.input.next() {
27 None => return Ok(std::mem::take(&mut self.row)).transpose(),
28 Some(Err(e)) => return Some(Err(e)),
29 Some(Ok(line)) if line.is_empty() && self.row.is_some() => {
30 return Ok(std::mem::take(&mut self.row)).transpose()
32 Some(Ok(line)) if line.is_empty() => {}
33 Some(Ok(line)) if line.starts_with(' ') => match &mut self.row {
34 None => return Some(Err(std::io::Error::other("Entry with no header"))),
35 Some(ref mut row) => row.entries.push(String::from(line.trim())),
38 let prev = std::mem::take(&mut self.row);
39 self.row = Some(RowInput {
44 return Ok(prev).transpose();
53 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
54 Reader::new(std::io::BufReader::new(input).lines())
57 pub fn tablify(_input: &impl std::io::Read) -> String {
58 String::from("Hello, world!")
68 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
70 label: String::from("foo"),
75 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
77 label: String::from("bar"),
82 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
85 label: String::from("foo"),
89 label: String::from("bar"),
95 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
97 label: String::from("foo"),
98 entries: vec![String::from("bar")]
102 read_rows(&b"foo\n bar\n baz\n"[..])
104 .collect::<Vec<_>>(),
106 label: String::from("foo"),
107 entries: vec![String::from("bar"), String::from("baz")]
111 read_rows(&b"foo\n\nbar\n"[..])
113 .collect::<Vec<_>>(),
116 label: String::from("foo"),
120 label: String::from("bar"),
126 let bad = read_rows(&b" foo"[..]).next().unwrap();
127 assert!(bad.is_err());
128 assert!(format!("{bad:?}").contains("Entry with no header"));
130 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
131 assert!(bad2.is_err());
132 assert!(format!("{bad2:?}").contains("Entry with no header"));