+#[derive(Debug, PartialEq, Eq)]
+enum Rowlike {
+ Row(Row),
+ Spacer,
+}
+
+struct Reader<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> {
+ input: std::iter::Enumerate<Input>,
+ row: Option<Row>,
+ config: &'cfg mut Config,
+}
+impl<'cfg, Input: Iterator<Item = Result<String, std::io::Error>>> Reader<'cfg, Input> {
+ fn new(config: &'cfg mut Config, input: Input) -> Self {
+ Self {
+ input: input.enumerate(),
+ row: None,
+ config,
+ }
+ }
+}
+impl<Input: Iterator<Item = Result<String, std::io::Error>>> Iterator for Reader<'_, Input> {
+ type Item = Result<Rowlike, std::io::Error>;
+ fn next(&mut self) -> Option<Self::Item> {
+ loop {
+ match self.input.next() {
+ None => return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose(),
+ Some((_, Err(e))) => return Some(Err(e)),
+ Some((n, Ok(line))) => match InputLine::from(line.as_ref()) {
+ InputLine::Command(cmd) => {
+ if let Err(e) = self.config.apply_command(n + 1, cmd) {
+ return Some(Err(e));
+ }
+ }
+ InputLine::Blank if self.row.is_some() => {
+ return Ok(std::mem::take(&mut self.row).map(Rowlike::Row)).transpose()
+ }
+ InputLine::Blank => return Some(Ok(Rowlike::Spacer)),
+ InputLine::Entry(col, instance) => match self.row {
+ None => {
+ return Some(Err(std::io::Error::other(format!(
+ "line {}: Entry with no header",
+ n + 1
+ ))))
+ }
+ Some(ref mut row) => {
+ row.entries
+ .entry(col.to_owned())
+ .and_modify(|is| is.push(instance.map(ToOwned::to_owned)))
+ .or_insert_with(|| vec![instance.map(ToOwned::to_owned)]);
+ }
+ },
+ InputLine::RowHeader(row) => {
+ let prev = std::mem::take(&mut self.row);
+ self.row = Some(Row {
+ label: row.to_owned(),
+ entries: HashMap::new(),
+ });
+ if prev.is_some() {
+ return Ok(prev.map(Rowlike::Row)).transpose();
+ }
+ }
+ },
+ }
+ }
+ }
+}
+
+fn read_input(input: impl std::io::Read) -> Result<(Vec<Rowlike>, Config), std::io::Error> {
+ let mut config = Config::default();
+ let reader = Reader::new(&mut config, std::io::BufReader::new(input).lines());
+ reader
+ .collect::<Result<Vec<_>, _>>()
+ .map(|rows| (rows, config))
+}
+
+fn column_counts(rows: &[Rowlike]) -> Vec<(usize, String)> {
+ let empty = HashMap::new();
+ let mut counts: Vec<_> = rows
+ .iter()
+ .flat_map(|rl| match *rl {
+ Rowlike::Row(ref r) => r.entries.keys(),
+ Rowlike::Spacer => empty.keys(),
+ })
+ .fold(HashMap::new(), |mut cs, col| {
+ cs.entry(col.to_owned())
+ .and_modify(|n| *n += 1)
+ .or_insert(1);
+ cs
+ })
+ .into_iter()
+ .map(|(col, n)| (n, col))
+ .collect();
+ counts.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
+ counts
+}
+fn column_order(config: &Config, rows: &[Rowlike]) -> Vec<String> {
+ let static_columns: HashSet<&str> = config
+ .static_columns
+ .iter()
+ .flatten()
+ .map(std::string::String::as_str)
+ .collect();
+ column_counts(rows)
+ .into_iter()
+ .filter_map(|(n, col)| {
+ (n >= config.column_threshold
+ && !static_columns.contains(col.as_str())
+ && !config.hidden_columns.contains(&col))
+ .then_some(col)
+ })
+ .collect()
+}
+
+fn render_instances(instances: &[Option<String>], mark: Option<&str>) -> HTML {
+ let mut tally = 0;
+ let mut out = vec![];
+ for ins in instances {
+ match *ins {
+ None => tally += 1,
+ Some(ref content) => {
+ if tally > 0 {
+ out.push(tally_marks(tally, mark));
+ tally = 0;
+ }
+ out.push(HTML::escape(content));
+ }
+ }
+ }
+ if tally > 0 {
+ out.push(tally_marks(tally, mark));
+ }
+ HTML(
+ out.into_iter()
+ .map(|html| html.0)
+ .collect::<Vec<_>>()
+ .join(" "),
+ )
+}
+
+fn render_cell(config: &Config, col: &str, row: &mut Row) -> HTML {
+ let row_label = HTML::escape(row.label.as_ref());
+ let col_label = HTML::escape(
+ config
+ .substitute_labels
+ .get(col)
+ .map_or(col, std::string::String::as_str),
+ );
+ let instances: Option<&Vec<Option<String>>> = row.entries.get(col);
+ let is_empty = match instances {
+ None => true,
+ Some(is) => is.iter().all(|ins| match *ins {
+ None => false,
+ Some(ref content) => content == "×",
+ }),
+ };
+ let class = HTML::from(if is_empty { "" } else { r#" class="yes""# });
+ let contents = match instances {
+ None => HTML::from(""),
+ Some(is) => render_instances(is, config.mark.get(col).map(String::as_str)),
+ };
+ row.entries.remove(col);
+ HTML(format!(
+ r#"<td{class} onmouseover="h2('{row_label}','{col_label}')" onmouseout="ch2('{row_label}','{col_label}')">{contents}</td>"#
+ ))
+}
+
+fn render_leftover(config: &Config, notcol: &str, instances: &[Option<String>]) -> HTML {
+ let label = HTML::escape(notcol);
+ if instances.len() == 1 && instances[0].is_none() {
+ HTML(format!("{label}"))
+ } else {
+ let rest = render_instances(instances, config.mark.get(notcol).map(String::as_str));
+ HTML(format!("{label}: {rest}"))
+ }
+}
+
+fn render_all_leftovers(config: &Config, row: &Row) -> HTML {
+ let mut order: Vec<_> = row
+ .entries
+ .keys()
+ .filter(|&col| !config.hidden_columns.contains(col))
+ .collect();
+ order.sort_unstable();
+ HTML(
+ order
+ .into_iter()
+ .map(|notcol| {
+ render_leftover(
+ config,
+ notcol,
+ row.entries.get(notcol).expect("Key vanished?!"),
+ )
+ })
+ .map(|html| html.0)
+ .collect::<Vec<_>>()
+ .join(", "),
+ )
+}
+
+fn render_row(config: &Config, columns: &[String], rowlike: &mut Rowlike) -> HTML {
+ match *rowlike {
+ Rowlike::Spacer => HTML::from("<tr><th class=\"spacer_row\"></th></tr>\n"),
+ Rowlike::Row(ref mut row) => {
+ let row_label = HTML::escape(row.label.as_ref());
+ let static_cells = config
+ .static_columns
+ .iter()
+ .map(|ocol| match *ocol {
+ Some(ref col) if config.hidden_columns.contains(col) => HTML::from(""),
+ Some(ref col) => render_cell(config, col, row),
+ None => HTML::from(r#"<td class="spacer_col"></td>"#),
+ })
+ .collect::<HTML>();
+ let dynamic_cells = columns
+ .iter()
+ .filter(|&col| !config.hidden_columns.contains(col))
+ .map(|col| render_cell(config, col, row))
+ .collect::<HTML>();
+ let leftovers = render_all_leftovers(config, row);
+ HTML(format!(
+ "<tr><th id=\"{row_label}\">{row_label}</th>{static_cells}{dynamic_cells}<td class=\"leftover\" onmouseover=\"highlight('{row_label}')\" onmouseout=\"clear_highlight('{row_label}')\">{leftovers}</td></tr>\n"
+ ))
+ }
+ }
+}
+
+fn column_header_labels<'a>(
+ config: &'a Config,
+ columns: &'a [String],
+) -> impl Iterator<Item = Option<&'a String>> {
+ let static_columns = config.static_columns.iter().map(|oc| oc.as_ref());
+ let dynamic_columns = columns.iter().map(Some);
+ static_columns
+ .chain(dynamic_columns)
+ .filter(|ocol| ocol.is_none_or(|col| !config.hidden_columns.contains(col)))
+ .map(|ocol| {
+ ocol.map(|col| match config.substitute_labels.get(col) {
+ None => col,
+ Some(substitute) => substitute,
+ })
+ })
+}
+
+fn render_column_headers(config: &Config, columns: &[String]) -> HTML {
+ HTML(
+ String::from(r#"<tr class="key"><th></th>"#)
+ + &column_header_labels(config, columns).fold(String::new(), |mut acc, ocol| {
+ match ocol {
+ Some(col) => {
+ let col_header = HTML::escape(col);
+ write!(
+ &mut acc,
+ r#"<th id="{col_header}"><div><div>{col_header}</div></div></th>"#
+ )
+ }
+ None => write!(&mut acc, r#"<th class="col_spacer"></th>"#),
+ }
+ .unwrap();
+ acc
+ })
+ + "</tr>\n",
+ )