Skip to content

Commit

Permalink
Fix fit to grid failing in a common case
Browse files Browse the repository at this point in the history
  • Loading branch information
ariasuni committed Dec 26, 2021
1 parent 1cbc10f commit 64b8b5d
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,11 @@ impl Grid {
return Some(Dimensions { num_lines: 1, widths: vec![ the_cell.width ] });
}

if self.options.filling.width() > maximum_width {
// Filling is too large to separate even two elements with zero width
return None;
}

let theoretical_max_num_lines = self.theoretical_max_num_lines(maximum_width);
if theoretical_max_num_lines == 1 {
// This if—statement is neccesary for the function to work correctly
Expand All @@ -380,8 +385,7 @@ impl Grid {
// Instead of numbers of columns, try to find the fewest number of *lines*
// that the output will fit in.
let mut smallest_dimensions_yet = None;
for num_lines in (1 .. theoretical_max_num_lines).rev() {

for num_lines in (1 ..= theoretical_max_num_lines).rev() {
// The number of columns is the number of cells divided by the number
// of lines, *rounded up*.
let mut num_columns = self.cell_count / num_lines;
Expand All @@ -407,11 +411,11 @@ impl Grid {
if potential_dimensions.widths.iter().sum::<Width>() < adjusted_width {
smallest_dimensions_yet = Some(potential_dimensions);
} else {
return smallest_dimensions_yet;
continue;
}
}

None
smallest_dimensions_yet
}
}

Expand Down Expand Up @@ -749,4 +753,22 @@ mod test {

assert_eq!(display.width(), 4);
}

#[test]
fn theoretical_is_effective_max_num_line() {
let mut grid = Grid::new(GridOptions {
filling: Filling::Text("||".into()),
direction: Direction::LeftToRight,
});

for s in &["test1", "test2", "test3", "test4", "test5", "test6", "test7",
"test8", "test9", "test10", "test11"]
{
grid.add(Cell::from(*s));
}

let bits = "test1||test2||test3||test4 ||test5 ||test6\ntest7||test8||test9||test10||test11||\n";
assert_eq!(grid.fit_into_width(69).unwrap().to_string(), bits);
assert_eq!(grid.fit_into_width(69).unwrap().row_count(), 2);
}
}

0 comments on commit 64b8b5d

Please sign in to comment.