1
//! The width rules of grid columns and how a line's columns share its room.
2

            
3
use super::Item;
4

            
5
const GAP: u16 = 1;
6

            
7
/// How wide an item's column wants to be: its content, a fixed count of cells, or a share of
8
/// what the line leaves over, kept within `min..=max`.
9
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10
pub enum Width {
11
    Fit,
12
    Fixed(u16),
13
    Flex { min: u16, max: u16 },
14
}
15

            
16
/// Where the shifting columns start: right after the `frozen` leading ones, if any.
17
3977
pub(super) fn frozen_edge(spans: &[(u16, u16)], frozen: usize) -> u16 {
18
3977
    match frozen {
19
2499
        0 => 0,
20
1478
        _ => spans.get(frozen).map_or(0, |(left, _)| *left),
21
    }
22
3977
}
23

            
24
21166
pub(super) fn gap(width: u16) -> u16 {
25
21166
    if width > 0 { GAP } else { 0 }
26
21166
}
27

            
28
/// What the items of one column ask for.
29
#[derive(Debug, Clone, Copy, Default)]
30
pub(super) struct Column {
31
    floor: u16,
32
    want: u16,
33
    flex: bool,
34
}
35

            
36
impl Column {
37
16285
    pub(super) fn absorb(&mut self, item: &Item<'_>) {
38
16285
        self.floor = self.floor.max(item.floor());
39
16285
        self.want = self.want.max(item.width());
40
16285
        self.flex |= matches!(item.rule, Width::Flex { .. });
41
16285
    }
42
}
43

            
44
/// The widths of `columns` in `room` cells: fixed ones as asked, flexible ones sharing the
45
/// rest, the spare cells going to the first ones.
46
1876
pub(super) fn resolve(columns: &[Column], room: Option<u16>) -> Vec<u16> {
47
1876
    let Some(room) = room else {
48
3417
        return columns.iter().map(|column| column.want).collect();
49
    };
50
9237
    let shown = columns.iter().filter(|c| c.floor > 0).count();
51
9237
    let floors = columns.iter().map(|c| c.floor).fold(0, u16::saturating_add);
52
1348
    let gaps = u16::try_from(shown.saturating_sub(1)).unwrap_or(u16::MAX);
53
1348
    let left = room.saturating_sub(floors.saturating_add(gaps));
54
9237
    let flexes = u16::try_from(columns.iter().filter(|c| c.flex).count()).unwrap_or(u16::MAX);
55
1348
    let share = left.checked_div(flexes).unwrap_or(0);
56
1348
    let spare = left.checked_rem(flexes).unwrap_or(0);
57
1348
    let mut seen = 0;
58
9237
    let mut width = |column: &Column| {
59
9237
        if !column.flex {
60
7746
            return column.want;
61
1491
        }
62
1491
        let extra = share + u16::from(seen < spare);
63
1491
        seen += 1;
64
1491
        column.floor.saturating_add(extra).min(column.want)
65
9237
    };
66
1348
    columns.iter().map(&mut width).collect()
67
1876
}
68

            
69
#[cfg(test)]
70
mod tests;