Sorting
cols can sort lines by any column. For tree tables, sorting is recursive —
children are reordered within each parent node, preserving the tree structure.
By default, sorting is alphabetical by the cell’s string data. You can supply
a custom comparator for numeric or application-specific ordering.
Alphabetic sorting (default)
use cols::{Table, Column, print_table};
fn main() {
let mut t = Table::new();
t.headings_set(false);
t.add_column(Column::new("NAME").tree(true));
let root = t.new_line(None);
t.line_mut(root).data_set(0, "items");
for val in ["cherry", "apple", "banana"] {
let row = t.new_line(Some(root));
t.line_mut(row).data_set(0, val);
}
t.sort(0);
print_table(&t, &mut std::io::stdout().lock()).unwrap();
}
items
├─apple
├─banana
└─cherry
Custom comparators
Set a comparator on the column for non-alphabetical ordering:
use cols::{Table, Column, print_table};
fn main() {
let mut t = Table::new();
t.headings_set(false);
t.add_column(Column::new("VALUE").tree(true).order_function(|a, b| {
let av: i64 = a.data().unwrap_or("0").parse().unwrap_or(0);
let bv: i64 = b.data().unwrap_or("0").parse().unwrap_or(0);
av.cmp(&bv)
}));
let root = t.new_line(None);
t.line_mut(root).data_set(0, "items");
for val in ["10", "2", "100", "20", "3"] {
let row = t.new_line(Some(root));
t.line_mut(row).data_set(0, val);
}
t.sort(0);
print_table(&t, &mut std::io::stdout().lock()).unwrap();
}
items
├─2
├─3
├─10
├─20
└─100
You can also set a comparator after the column is in the table:
table.column_mut(0).unwrap().order_function_set(|a, b| {
// ...
a.data().cmp(&b.data())
});
Re-sorting
After adding new lines, call resort() to re-apply the last sort:
table.sort(0);
// ... add more lines ...
table.resort(); // re-sorts using column 0
How it works
For flat tables, sorting reorders root lines. For trees, sorting reorders children within each parent node — the tree structure is preserved. The sort is stable and uses the column’s comparator (defaulting to string comparison).