@@ -196,30 +196,34 @@ impl<T: AsRef<str>> Grid<T> {
196
196
} ;
197
197
}
198
198
199
- // Calculate number of columns with widest column size.
200
- let max_num_columns = self . options . width / widest_column;
201
-
202
- // Caculate approximate number of lines and columns.
203
- let appr_num_lines = div_ceil ( self . cells . len ( ) , max_num_columns) ;
204
- let appr_num_columns = div_ceil ( self . cells . len ( ) , appr_num_lines) ;
199
+ // Calculate minimum number of columns with the widest column size.
200
+ let min_columns = self
201
+ . cells
202
+ . len ( )
203
+ . min ( ( self . options . width + self . options . filling . width ( ) ) / widest_column) ;
204
+ // Caculate approximate number of rows and columns.
205
+ let min_lines = div_ceil ( self . cells . len ( ) , min_columns) ;
206
+ // let appr_num_columns = div_ceil(self.cells.len(), appr_num_lines);
205
207
206
208
// This is a potential dimension, which can definitely fit all of the cells.
207
- let mut potential_dimension = self . compute_dimensions ( appr_num_lines , appr_num_columns ) ;
209
+ let mut potential_dimension = self . compute_dimensions ( min_lines , min_columns ) ;
208
210
// If all of the cells can be fit on one line, return.
209
- if appr_num_lines == 1 {
211
+ if min_lines == 1 {
210
212
return potential_dimension;
211
213
}
212
214
213
215
// Try to increase number of columns, to see if new dimension can still fit.
214
- for num_columns in appr_num_columns + 1 .. {
215
- let new_width = self . options . width - ( num_columns - 1 ) * self . options . filling . width ( ) ;
216
- let num_lines = div_ceil ( self . cells . len ( ) , num_columns) ;
217
- let new_dimension = self . compute_dimensions ( num_lines, num_columns) ;
218
- if new_dimension. widths . iter ( ) . sum :: < usize > ( ) <= new_width {
219
- potential_dimension = new_dimension;
220
- } else {
216
+ for num_columns in min_columns + 1 .. {
217
+ let new_width = ( num_columns - 1 ) * self . options . filling . width ( ) ;
218
+ if new_width > self . options . width {
221
219
break ;
222
220
}
221
+
222
+ let num_rows = div_ceil ( self . cells . len ( ) , num_columns) ;
223
+ let new_dimension = self . compute_dimensions ( num_rows, num_columns) ;
224
+ if new_dimension. widths . iter ( ) . sum :: < usize > ( ) <= self . options . width - new_width {
225
+ potential_dimension = new_dimension;
226
+ }
223
227
}
224
228
225
229
potential_dimension
0 commit comments