Lines
100 %
Functions
50 %
Branches
//! The width rules of grid columns and how a line's columns share its room.
use super::Item;
const GAP: u16 = 1;
/// How wide an item's column wants to be: its content, a fixed count of cells, or a share of
/// what the line leaves over, kept within `min..=max`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Width {
Fit,
Fixed(u16),
Flex { min: u16, max: u16 },
}
/// Where the shifting columns start: right after the `frozen` leading ones, if any.
pub(super) fn frozen_edge(spans: &[(u16, u16)], frozen: usize) -> u16 {
match frozen {
0 => 0,
_ => spans.get(frozen).map_or(0, |(left, _)| *left),
pub(super) fn gap(width: u16) -> u16 {
if width > 0 { GAP } else { 0 }
/// What the items of one column ask for.
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct Column {
floor: u16,
want: u16,
flex: bool,
impl Column {
pub(super) fn absorb(&mut self, item: &Item<'_>) {
self.floor = self.floor.max(item.floor());
self.want = self.want.max(item.width());
self.flex |= matches!(item.rule, Width::Flex { .. });
/// The widths of `columns` in `room` cells: fixed ones as asked, flexible ones sharing the
/// rest, the spare cells going to the first ones.
pub(super) fn resolve(columns: &[Column], room: Option<u16>) -> Vec<u16> {
let Some(room) = room else {
return columns.iter().map(|column| column.want).collect();
};
let shown = columns.iter().filter(|c| c.floor > 0).count();
let floors = columns.iter().map(|c| c.floor).fold(0, u16::saturating_add);
let gaps = u16::try_from(shown.saturating_sub(1)).unwrap_or(u16::MAX);
let left = room.saturating_sub(floors.saturating_add(gaps));
let flexes = u16::try_from(columns.iter().filter(|c| c.flex).count()).unwrap_or(u16::MAX);
let share = left.checked_div(flexes).unwrap_or(0);
let spare = left.checked_rem(flexes).unwrap_or(0);
let mut seen = 0;
let mut width = |column: &Column| {
if !column.flex {
return column.want;
let extra = share + u16::from(seen < spare);
seen += 1;
column.floor.saturating_add(extra).min(column.want)
columns.iter().map(&mut width).collect()
#[cfg(test)]
mod tests;