use std::num::NonZeroU16;
use crate::text::{PrintableLines, PrintableText};
use crate::{BlockStyle, Length, Sides};
use super::geometry::{Constraint, Size};
pub(super) fn tighter(left: Option<usize>, right: Option<usize>) -> Option<usize> {
match (left, right) {
(Some(left), Some(right)) => Some(left.min(right)),
(bound, None) | (None, bound) => bound,
}
}
pub(super) fn clamp_size(base: usize, cap: Option<usize>, floor: usize) -> usize {
cap.map_or(base, |cap| base.min(cap)).max(floor)
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Axis {
pub frame: usize,
pub length: Option<Length>,
pub min: Option<u16>,
pub max: Option<u16>,
}
impl Axis {
pub fn used(&self, constraint: Constraint, intrinsic: usize, min_content: usize) -> usize {
let base = match self.length {
Some(Length::Cells(cells)) => usize::from(cells),
Some(Length::Fill(_)) => constraint.reference.unwrap_or(self.frame + intrinsic),
None => self.frame + intrinsic,
};
clamp_size(
base,
tighter(self.max.map(usize::from), constraint.cap),
self.min
.map_or(0, usize::from)
.max(self.frame + min_content),
)
}
pub fn content_constraint(&self, constraint: Constraint) -> Constraint {
let stated = match self.length {
Some(Length::Cells(cells)) => Some(usize::from(cells)),
Some(Length::Fill(_)) => constraint.reference,
None => None,
};
let local = tighter(stated, self.max.map(usize::from));
Constraint {
reference: tighter(local, constraint.reference)
.map(|bound| bound.saturating_sub(self.frame)),
cap: tighter(local, constraint.cap).map(|bound| bound.saturating_sub(self.frame)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
Fill(NonZeroU16),
Auto,
Cells,
}
impl Kind {
pub(crate) const fn fill(weight: u16) -> Self {
match NonZeroU16::new(weight) {
Some(weight) => Self::Fill(weight),
None => panic!("internal fill weight must be greater than zero"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Claim {
pub kind: Kind,
pub demand: usize,
pub floor: usize,
}
pub(crate) fn distribute(area: usize, claims: &[Claim]) -> Vec<usize> {
distribute_constraints(Some(area), Some(area), claims)
}
pub(super) fn distribute_constraints(
reference: Option<usize>,
cap: Option<usize>,
claims: &[Claim],
) -> Vec<usize> {
let Some(reference) = reference else {
return claims
.iter()
.map(|claim| claim.demand.max(claim.floor))
.collect();
};
let stated: usize = claims
.iter()
.filter(|claim| !matches!(claim.kind, Kind::Fill(_)))
.map(|claim| claim.demand)
.sum();
let weights: usize = claims.iter().map(|claim| claim.weight()).sum();
let remaining = reference.saturating_sub(stated);
let mut assigned = Vec::with_capacity(claims.len());
let (mut weighted, mut given) = (0, 0);
for claim in claims {
assigned.push(match claim.kind {
Kind::Fill(_) => {
weighted += claim.weight();
let upto = remaining
.saturating_mul(weighted)
.checked_div(weights)
.unwrap_or(0);
let share = upto - given;
given = upto;
share.max(claim.floor)
}
_ => claim.demand,
});
}
let Some(cap) = cap else {
return assigned;
};
let mut excess = assigned.iter().sum::<usize>().saturating_sub(cap);
for group in [Kind::fill(1), Kind::Auto, Kind::Cells] {
if excess == 0 {
break;
}
excess = shrink(&mut assigned, claims, group, excess);
}
assigned
}
impl Claim {
const fn weight(&self) -> usize {
match self.kind {
Kind::Fill(weight) => weight.get() as usize,
_ => 0,
}
}
}
fn shrink(assigned: &mut [usize], claims: &[Claim], group: Kind, mut excess: usize) -> usize {
let holds = |kind: Kind| match group {
Kind::Fill(_) => matches!(kind, Kind::Fill(_)),
other => kind == other,
};
while excess > 0 {
let active: Vec<usize> = (0..claims.len())
.filter(|&index| holds(claims[index].kind) && assigned[index] > claims[index].floor)
.collect();
let total: usize = active.iter().map(|&index| assigned[index]).sum();
if total == 0 {
break;
}
let mut removed = 0;
for &index in &active {
if removed == excess {
break;
}
let cut = (excess * assigned[index])
.div_ceil(total)
.min(excess - removed)
.min(assigned[index] - claims[index].floor);
assigned[index] -= cut;
removed += cut;
}
if removed == 0 {
break;
}
excess -= removed;
}
excess
}
pub(super) const fn kind_of(length: Option<Length>) -> Kind {
match length {
Some(Length::Fill(weight)) => Kind::Fill(weight),
Some(Length::Cells(_)) => Kind::Cells,
None => Kind::Auto,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Degraded {
pub margin: bool,
pub padding: bool,
}
pub(super) fn degrade(
area: Option<usize>,
margin: usize,
border: usize,
padding: usize,
min_content: usize,
) -> Degraded {
let Some(area) = area else {
return Degraded {
margin: false,
padding: false,
};
};
if margin + border + padding + min_content <= area {
return Degraded {
margin: false,
padding: false,
};
}
Degraded {
margin: true,
padding: border + padding + min_content > area,
}
}
pub(super) fn border_extent(style: &BlockStyle) -> Size {
match style.get_border() {
Some(_) => Size::new(
usize::from(style.get_border_left()) + usize::from(style.get_border_right()),
usize::from(style.get_border_top()) + usize::from(style.get_border_bottom()),
),
None => Size::ZERO,
}
}
pub(super) const fn horizontal(sides: Sides) -> usize {
sides.left as usize + sides.right as usize
}
pub(super) const fn vertical(sides: Sides) -> usize {
sides.top as usize + sides.bottom as usize
}
pub(super) fn width_axis(style: &BlockStyle, frame: usize) -> Axis {
Axis {
frame,
length: style.get_width(),
min: style.get_min_width(),
max: style.get_max_width(),
}
}
pub(super) fn height_axis(style: &BlockStyle, frame: usize) -> Axis {
Axis {
frame,
length: style.get_height(),
min: style.get_min_height(),
max: style.get_max_height(),
}
}
pub(super) fn text_lines(text: &str) -> Vec<&PrintableText> {
PrintableLines::new(text).lines()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Border;
#[test]
fn the_floor_wins_over_the_cap() {
assert_eq!(clamp_size(10, Some(4), 0), 4, "the cap binds");
assert_eq!(clamp_size(2, Some(4), 0), 2, "neither binds");
assert_eq!(clamp_size(2, None, 6), 6, "the floor binds");
assert_eq!(clamp_size(10, Some(4), 6), 6, "the floor beats the cap");
}
#[test]
fn the_tighter_bound_wins_and_an_absent_one_never_binds() {
assert_eq!(tighter(Some(4), Some(9)), Some(4));
assert_eq!(tighter(Some(9), Some(4)), Some(4));
assert_eq!(tighter(Some(4), None), Some(4));
assert_eq!(tighter(None, Some(4)), Some(4));
assert_eq!(tighter(None, None), None);
}
#[test]
fn an_axis_sizes_from_the_content_when_no_length_is_stated() {
let axis = Axis {
frame: 2,
length: None,
min: None,
max: None,
};
assert_eq!(
axis.used(Constraint::unbounded(), 5, 1),
7,
"the frame is inside the size"
);
assert_eq!(
axis.used(Constraint::available(Some(4)), 5, 1),
4,
"the area caps it"
);
assert_eq!(
axis.used(Constraint::available(Some(9)), 5, 1),
7,
"a wider area does not pad it"
);
}
#[test]
fn a_stated_length_is_the_base_the_bounds_clamp() {
let axis = |length, min, max| Axis {
frame: 0,
length,
min,
max,
};
assert_eq!(
axis(Some(Length::Cells(6)), None, None).used(Constraint::unbounded(), 2, 0),
6,
"a stated size ignores the content"
);
assert_eq!(
axis(Some(Length::Cells(6)), None, Some(4)).used(Constraint::unbounded(), 2, 0),
4,
"the maximum caps the stated size"
);
assert_eq!(
axis(Some(Length::Cells(6)), Some(8), None).used(Constraint::unbounded(), 2, 0),
8,
"the minimum floors it"
);
assert_eq!(
axis(None, None, Some(4)).used(Constraint::available(Some(9)), 2, 0),
2,
"a maximum alone is shrink-to-fit with a cap"
);
}
#[test]
fn a_fill_length_takes_the_area_and_falls_back_to_the_content() {
let axis = Axis {
frame: 2,
length: Some(Length::fill(1)),
min: None,
max: None,
};
assert_eq!(
axis.used(Constraint::available(Some(10)), 3, 1),
10,
"it spans the area"
);
assert_eq!(
axis.used(Constraint::unbounded(), 3, 1),
5,
"with no area it contributes the intrinsic size"
);
}
#[test]
fn the_content_floor_is_the_axis_asymmetry() {
let axis = Axis {
frame: 2,
length: Some(Length::Cells(1)),
min: None,
max: None,
};
assert_eq!(axis.used(Constraint::available(Some(1)), 4, 2), 4);
assert_eq!(axis.used(Constraint::available(Some(1)), 4, 0), 2);
}
#[test]
fn the_content_bound_is_the_tightest_of_the_size_the_maximum_and_the_area() {
let axis = |length, max| Axis {
frame: 2,
length,
min: None,
max,
};
assert_eq!(
axis(None, None).content_constraint(Constraint::unbounded()),
Constraint::unbounded(),
"nothing bounds"
);
assert_eq!(
axis(None, None).content_constraint(Constraint::available(Some(9))),
Constraint::available(Some(7))
);
assert_eq!(
axis(Some(Length::Cells(5)), None).content_constraint(Constraint::unbounded()),
Constraint::available(Some(3))
);
assert_eq!(
axis(Some(Length::Cells(5)), Some(4))
.content_constraint(Constraint::available(Some(9))),
Constraint::available(Some(2)),
"the maximum is tighter than the stated size"
);
assert_eq!(
axis(Some(Length::fill(1)), None).content_constraint(Constraint::available(Some(6))),
Constraint::available(Some(4)),
"a Fill length is bounded by the area it fills"
);
assert_eq!(
axis(Some(Length::Cells(1)), None).content_constraint(Constraint::unbounded()),
Constraint::available(Some(0)),
"a size below the frame leaves no content, not a negative one"
);
}
#[test]
fn degradation_collapses_margin_before_padding_and_only_under_pressure() {
let at = |area| degrade(area, 2, 2, 2, 1);
assert_eq!(
at(None),
Degraded {
margin: false,
padding: false
},
"an unbounded axis never degrades"
);
assert_eq!(
at(Some(7)),
Degraded {
margin: false,
padding: false
},
"exactly enough is enough"
);
assert_eq!(
at(Some(6)),
Degraded {
margin: true,
padding: false
},
"the margin goes first"
);
assert_eq!(
at(Some(5)),
Degraded {
margin: true,
padding: false
},
"the box itself still fits"
);
assert_eq!(
at(Some(4)),
Degraded {
margin: true,
padding: true
},
"then the padding"
);
assert_eq!(
at(Some(1)),
Degraded {
margin: true,
padding: true
},
"below that the content and the safety net take over"
);
}
fn claim(kind: Kind, demand: usize, floor: usize) -> Claim {
Claim {
kind,
demand,
floor,
}
}
#[test]
fn fill_children_divide_what_the_others_leave() {
let stated = claim(Kind::Cells, 6, 0);
let auto = claim(Kind::Auto, 4, 0);
let fill = |weight| claim(Kind::fill(weight), 0, 0);
assert_eq!(distribute(20, &[stated, fill(1)]), vec![6, 14]);
assert_eq!(distribute(20, &[stated, auto, fill(1)]), vec![6, 4, 10]);
assert_eq!(distribute(10, &[fill(1), fill(1)]), vec![5, 5]);
assert_eq!(distribute(9, &[fill(1), fill(2)]), vec![3, 6]);
}
#[test]
fn a_share_never_loses_a_cell_to_rounding() {
let fill = claim(Kind::fill(1), 0, 0);
assert_eq!(distribute(10, &[fill, fill, fill]), vec![3, 3, 4]);
for area in 0..40 {
let shares = distribute(area, &[fill, fill, fill]);
assert_eq!(shares.iter().sum::<usize>(), area, "at {area}");
}
}
#[test]
fn nothing_is_redistributed_when_a_child_leaves_slack() {
assert_eq!(
distribute(20, &[claim(Kind::fill(1), 0, 0), claim(Kind::Cells, 4, 0)]),
vec![16, 4]
);
}
#[test]
fn a_deficit_shrinks_fill_then_auto_then_stated() {
let claims = [
claim(Kind::Cells, 6, 3),
claim(Kind::Auto, 6, 3),
claim(Kind::fill(1), 0, 3),
];
assert_eq!(distribute(16, &claims), vec![6, 6, 4], "no deficit at all");
assert_eq!(distribute(14, &claims), vec![6, 5, 3]);
assert_eq!(distribute(12, &claims), vec![6, 3, 3]);
assert_eq!(distribute(10, &claims), vec![4, 3, 3]);
assert_eq!(distribute(4, &claims), vec![3, 3, 3]);
}
#[test]
fn a_deficit_within_one_group_is_proportional_and_freezes_at_a_floor() {
let claims = [claim(Kind::Auto, 12, 0), claim(Kind::Auto, 4, 3)];
assert_eq!(distribute(12, &claims), vec![9, 3]);
assert_eq!(distribute(8, &claims), vec![5, 3]);
}
#[test]
fn border_extent_counts_only_enabled_edges_of_a_present_border() {
assert_eq!(border_extent(&BlockStyle::new()), Size::ZERO);
let full = BlockStyle::new().border(Border::NORMAL);
assert_eq!(border_extent(&full), Size::new(2, 2));
let sides = full.clone().border_top(false).border_left(false);
assert_eq!(border_extent(&sides), Size::new(1, 1));
let none = BlockStyle::new()
.border(Border::NORMAL)
.border_top(false)
.border_right(false)
.border_bottom(false)
.border_left(false);
assert_eq!(border_extent(&none), Size::ZERO);
}
}