4 use std::iter::Iterator;
6 #[derive(Debug, PartialEq, Eq)]
12 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
13 input: std::iter::Enumerate<Input>,
14 row: Option<RowInput>,
16 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
18 fn new(input: Input) -> Self {
20 input: input.enumerate(),
25 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
26 type Item = Result<RowInput, std::io::Error>;
27 fn next(&mut self) -> Option<Self::Item> {
32 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
34 None => return Ok(std::mem::take(&mut self.row)).transpose(),
35 Some((_, Err(e))) => return Some(Err(e)),
36 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
37 return Ok(std::mem::take(&mut self.row)).transpose()
39 Some((_, Ok(line))) if line.is_empty() => {}
40 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
42 return Some(Err(std::io::Error::other(format!(
43 "{}: Entry with no header",
47 Some(ref mut row) => row.entries.push(String::from(line.trim())),
49 Some((_, Ok(line))) => {
50 let prev = std::mem::take(&mut self.row);
51 self.row = Some(RowInput {
56 return Ok(prev).transpose();
65 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
66 Reader::new(std::io::BufReader::new(input).lines())
69 pub fn tablify(_input: &impl std::io::Read) -> String {
70 String::from("Hello, world!")
80 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
82 label: String::from("foo"),
87 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
89 label: String::from("bar"),
94 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
97 label: String::from("foo"),
101 label: String::from("bar"),
107 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
109 label: String::from("foo"),
110 entries: vec![String::from("bar")]
114 read_rows(&b"foo\n bar\n baz\n"[..])
116 .collect::<Vec<_>>(),
118 label: String::from("foo"),
119 entries: vec![String::from("bar"), String::from("baz")]
123 read_rows(&b"foo\n\nbar\n"[..])
125 .collect::<Vec<_>>(),
128 label: String::from("foo"),
132 label: String::from("bar"),
138 read_rows(&b"foo\n \nbar\n"[..])
140 .collect::<Vec<_>>(),
143 label: String::from("foo"),
147 label: String::from("bar"),
153 read_rows(&b"foo \n bar \n"[..])
155 .collect::<Vec<_>>(),
157 label: String::from("foo"),
158 entries: vec![String::from("bar")]
162 let bad = read_rows(&b" foo"[..]).next().unwrap();
163 assert!(bad.is_err());
164 assert!(format!("{bad:?}").contains("1: Entry with no header"));
166 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
167 assert!(bad2.is_err());
168 assert!(format!("{bad2:?}").contains("3: Entry with no header"));