Skip to main content

stern4rust/reporting/
column_widths.rs

1// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
2// Licensed under the MIT License
3// SPDX-License-Identifier: MIT
4
5use crate::reporting::offence::Offence;
6
7// How wide each column of the table has to be.
8//
9// Sized to the contents rather than fixed, so a rule name or a path that grows
10// widens its column instead of overflowing it -- and never narrower than its own
11// heading, which is what keeps the header row aligned with a report of one short
12// offence.
13pub struct ColumnWidths {
14    pub file: usize,
15    pub line: usize,
16    pub rule: usize,
17    pub description: usize,
18}
19
20impl ColumnWidths {
21    pub fn of(offences: &[Offence]) -> Self {
22        Self {
23            file: Self::widest(offences.iter().map(|offence| offence.file.len()), "file"),
24            line: Self::widest(
25                offences
26                    .iter()
27                    .map(|offence| offence.line.to_string().len()),
28                "line",
29            ),
30            rule: Self::widest(offences.iter().map(|offence| offence.rule.len()), "rule"),
31            description: Self::widest(
32                offences.iter().map(|offence| offence.description.len()),
33                "offence",
34            ),
35        }
36    }
37
38    fn widest<I: Iterator<Item = usize>>(lengths: I, heading: &str) -> usize {
39        lengths.max().unwrap_or(0).max(heading.len())
40    }
41}