Skip to content

Instantly share code, notes, and snippets.

/file.rs Secret

Created June 30, 2014 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/748de74227001c4d2700 to your computer and use it in GitHub Desktop.
Save anonymous/748de74227001c4d2700 to your computer and use it in GitHub Desktop.
/// Calculate the `(columns, rows, column width)` of the grid.
///
/// `rows` is the number of rows of all but the last column.
fn calculate_dimensions(entries: &[Entry]) -> (uint, uint, Vec<uint>) {
let (term_width, _) = term::dimensions();
// One letter + two spaces.
let min_column_width = 3;
let max_columns = min(term_width/min_column_width + 1, entries.len());
'outer_loop: for nc in range(2, max_columns + 1).rev() {
let n_rows = match div_rem(entries.len(), nc) {
(rows, 0) => rows,
(rows, _) => {
if (rows + 1) * (nc - 1) >= entries.len() {
// The entries can't be organized in nc columns.
// Example: Organize 11 entries in 10 columns.
continue;
}
rows + 1
}
};
for row in range(0, n_rows) {
let mut width = 0;
for n in range_step(row, entries.len(), n_rows) {
width += entries[n].len + 2;
}
if width - 2 > term_width {
continue 'outer_loop;
}
}
let mut col_width = Vec::with_capacity(nc);
for col in range(0, nc) {
let width = entries.iter()
.skip(col * n_rows)
.take(n_rows)
.map(|e| e.len)
.max()
.unwrap();
if col < nc - 1 {
col_width.push(width + 2);
} else {
col_width.push(width);
}
}
return (nc, n_rows, col_width);
}
let width = entries.iter().map(|e| e.len).max().unwrap();
(1, entries.len(), vec!(width))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment