]> git.scottworley.com Git - tablify/blob - src/lib.rs
fcf5dc822e790b15b377e6c154669f6b07524c71
[tablify] / src / lib.rs
1 #[cfg(test)]
2 use std::collections::{HashMap, HashSet};
3 #[cfg(test)]
4 use std::io::BufRead;
5 #[cfg(test)]
6 use std::iter::Iterator;
7
8 #[derive(Debug, PartialEq, Eq)]
9 struct RowInput {
10 label: String,
11 entries: Vec<String>,
12 }
13
14 struct Reader<Input: Iterator<Item = Result<String, std::io::Error>>> {
15 input: std::iter::Enumerate<Input>,
16 row: Option<RowInput>,
17 }
18 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Reader<Input> {
19 #[cfg(test)]
20 fn new(input: Input) -> Self {
21 Self {
22 input: input.enumerate(),
23 row: None,
24 }
25 }
26 }
27 impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<Input> {
28 type Item = Result<RowInput, std::io::Error>;
29 fn next(&mut self) -> Option<Self::Item> {
30 loop {
31 match self
32 .input
33 .next()
34 .map(|(n, r)| (n, r.map(|line| String::from(line.trim_end()))))
35 {
36 None => return Ok(std::mem::take(&mut self.row)).transpose(),
37 Some((_, Err(e))) => return Some(Err(e)),
38 Some((_, Ok(line))) if line.is_empty() && self.row.is_some() => {
39 return Ok(std::mem::take(&mut self.row)).transpose()
40 }
41 Some((_, Ok(line))) if line.is_empty() => {}
42 Some((n, Ok(line))) if line.starts_with(' ') => match &mut self.row {
43 None => {
44 return Some(Err(std::io::Error::other(format!(
45 "{}: Entry with no header",
46 n + 1
47 ))))
48 }
49 Some(ref mut row) => row.entries.push(String::from(line.trim())),
50 },
51 Some((_, Ok(line))) => {
52 let prev = std::mem::take(&mut self.row);
53 self.row = Some(RowInput {
54 label: line,
55 entries: vec![],
56 });
57 if prev.is_some() {
58 return Ok(prev).transpose();
59 }
60 }
61 }
62 }
63 }
64 }
65
66 #[cfg(test)]
67 fn read_rows(input: impl std::io::Read) -> impl Iterator<Item = Result<RowInput, std::io::Error>> {
68 Reader::new(std::io::BufReader::new(input).lines())
69 }
70
71 #[cfg(test)]
72 fn column_counts(rows: &[RowInput]) -> Vec<(usize, String)> {
73 let mut counts: Vec<_> = rows
74 .iter()
75 .flat_map(|r| r.entries.iter().collect::<HashSet<_>>().into_iter())
76 .fold(HashMap::new(), |mut cs, e| {
77 cs.entry(String::from(e))
78 .and_modify(|n| *n += 1)
79 .or_insert(1);
80 cs
81 })
82 .into_iter()
83 .map(|(col, n)| (n, col))
84 .collect();
85 counts.sort();
86 counts
87 }
88
89 pub fn tablify(_input: &impl std::io::Read) -> String {
90 String::from("Hello, world!")
91 }
92
93 #[cfg(test)]
94 mod tests {
95 use super::*;
96
97 #[test]
98 fn test_read_rows() {
99 assert_eq!(
100 read_rows(&b"foo"[..]).flatten().collect::<Vec<_>>(),
101 vec![RowInput {
102 label: String::from("foo"),
103 entries: vec![]
104 }]
105 );
106 assert_eq!(
107 read_rows(&b"bar"[..]).flatten().collect::<Vec<_>>(),
108 vec![RowInput {
109 label: String::from("bar"),
110 entries: vec![]
111 }]
112 );
113 assert_eq!(
114 read_rows(&b"foo\nbar\n"[..]).flatten().collect::<Vec<_>>(),
115 vec![
116 RowInput {
117 label: String::from("foo"),
118 entries: vec![]
119 },
120 RowInput {
121 label: String::from("bar"),
122 entries: vec![]
123 }
124 ]
125 );
126 assert_eq!(
127 read_rows(&b"foo\n bar\n"[..]).flatten().collect::<Vec<_>>(),
128 vec![RowInput {
129 label: String::from("foo"),
130 entries: vec![String::from("bar")]
131 }]
132 );
133 assert_eq!(
134 read_rows(&b"foo\n bar\n baz\n"[..])
135 .flatten()
136 .collect::<Vec<_>>(),
137 vec![RowInput {
138 label: String::from("foo"),
139 entries: vec![String::from("bar"), String::from("baz")]
140 }]
141 );
142 assert_eq!(
143 read_rows(&b"foo\n\nbar\n"[..])
144 .flatten()
145 .collect::<Vec<_>>(),
146 vec![
147 RowInput {
148 label: String::from("foo"),
149 entries: vec![]
150 },
151 RowInput {
152 label: String::from("bar"),
153 entries: vec![]
154 }
155 ]
156 );
157 assert_eq!(
158 read_rows(&b"foo\n \nbar\n"[..])
159 .flatten()
160 .collect::<Vec<_>>(),
161 vec![
162 RowInput {
163 label: String::from("foo"),
164 entries: vec![]
165 },
166 RowInput {
167 label: String::from("bar"),
168 entries: vec![]
169 }
170 ]
171 );
172 assert_eq!(
173 read_rows(&b"foo \n bar \n"[..])
174 .flatten()
175 .collect::<Vec<_>>(),
176 vec![RowInput {
177 label: String::from("foo"),
178 entries: vec![String::from("bar")]
179 }]
180 );
181
182 let bad = read_rows(&b" foo"[..]).next().unwrap();
183 assert!(bad.is_err());
184 assert!(format!("{bad:?}").contains("1: Entry with no header"));
185
186 let bad2 = read_rows(&b"foo\n\n bar"[..]).nth(1).unwrap();
187 assert!(bad2.is_err());
188 assert!(format!("{bad2:?}").contains("3: Entry with no header"));
189 }
190
191 #[test]
192 fn test_column_counts() {
193 assert_eq!(
194 column_counts(
195 &read_rows(&b"foo\n bar\n baz\n"[..])
196 .collect::<Result<Vec<_>, _>>()
197 .unwrap()
198 ),
199 vec![(1, String::from("bar")), (1, String::from("baz"))]
200 );
201 assert_eq!(
202 column_counts(
203 &read_rows(&b"foo\n bar\n baz\nquux\n baz"[..])
204 .collect::<Result<Vec<_>, _>>()
205 .unwrap()
206 ),
207 vec![(1, String::from("bar")), (2, String::from("baz"))]
208 );
209 assert_eq!(
210 column_counts(
211 &read_rows(&b"foo\n bar\n bar\n baz\n bar\nquux\n baz"[..])
212 .collect::<Result<Vec<_>, _>>()
213 .unwrap()
214 ),
215 vec![(1, String::from("bar")), (2, String::from("baz"))]
216 );
217 }
218 }