//! Tiny formatting helpers shared by the table-printing subcommands.

/// Returns the width a column should reserve to fit every row plus a minimum.
///
/// `key` extracts a cell's rendered width (in bytes) from each row, `min`
/// is the floor. Useful when the column has a header label that is wider
/// than any value (e.g. `NAME` over a list of 2-char worktree names).
pub fn col_width<T, F>(rows: &[T], key: F, min: usize) -> usize
where
    F: Fn(&T) -> usize,
{
    rows.iter().map(key).max().unwrap_or(min).max(min)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn respects_min_when_shorter() {
        let rows = vec!["a".to_string()];
        assert_eq!(col_width(&rows, String::len, 5), 5);
    }

    #[test]
    fn picks_max_when_longer() {
        let rows = vec!["abcdef".to_string(), "xy".to_string()];
        assert_eq!(col_width(&rows, String::len, 3), 6);
    }

    #[test]
    fn returns_min_for_empty() {
        let rows: Vec<String> = vec![];
        assert_eq!(col_width(&rows, String::len, 4), 4);
    }
}
