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> {
29 .map(|r| r.map(|line| String::from(line.trim_end())))
31 None => return Ok(std::mem::take(&mut self.row)).transpose(),
32 Some(Err(e)) => return Some(Err(e)),
33 Some(Ok(line)) if line.is_empty() && self.row.is_some() => {
34 return Ok(std::mem::take(&mut self.row)).transpose()
36 Some(Ok(line)) if line.is_empty() => {}
37 Some(Ok(line)) if line.starts_with(' ') => match &mut self.row {
38 None => return Some(Err(std::io::Error::other("Entry with no header"))),
39 Some(ref mut row) => row.entries.push(String::from(line.trim())),
42 let prev = std::mem::take(&mut self.row);
43 self.row = Some(RowInput {
48 return Ok(prev).transpose();
57 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
58 Reader::new(std::io::BufReader::new(input).lines())
61 pub fn tablify(_input: &impl std::io::Read) -> String {
62 String::from("Hello, world!")
72 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
74 label: String::from("foo"),
79 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
81 label: String::from("bar"),
86 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
89 label: String::from("foo"),
93 label: String::from("bar"),
99 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
101 label: String::from("foo"),
102 entries: vec![String::from("bar")]
106 read_rows(&b"foo\n bar\n baz\n"[..])
108 .collect::<Vec<_>>(),
110 label: String::from("foo"),
111 entries: vec![String::from("bar"), String::from("baz")]
115 read_rows(&b"foo\n\nbar\n"[..])
117 .collect::<Vec<_>>(),
120 label: String::from("foo"),
124 label: String::from("bar"),
130 read_rows(&b"foo\n \nbar\n"[..])
132 .collect::<Vec<_>>(),
135 label: String::from("foo"),
139 label: String::from("bar"),
145 read_rows(&b"foo \n bar \n"[..])
147 .collect::<Vec<_>>(),
149 label: String::from("foo"),
150 entries: vec![String::from("bar")]
154 let bad = read_rows(&b" foo"[..]).next().unwrap();
155 assert!(bad.is_err());
156 assert!(format!("{bad:?}").contains("Entry with no header"));
158 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
159 assert!(bad2.is_err());
160 assert!(format!("{bad2:?}").contains("Entry with no header"));