rustic_rs/
helpers.rs

1use bytesize::ByteSize;
2use comfy_table::{
3    presets::ASCII_MARKDOWN, Attribute, Cell, CellAlignment, ContentArrangement, Table,
4};
5
6/// Helpers for table output
7/// Create a new bold cell
8pub fn bold_cell<T: ToString>(s: T) -> Cell {
9    Cell::new(s).add_attribute(Attribute::Bold)
10}
11
12/// Create a new table with default settings
13#[must_use]
14pub fn table() -> Table {
15    let mut table = Table::new();
16    _ = table
17        .load_preset(ASCII_MARKDOWN)
18        .set_content_arrangement(ContentArrangement::Dynamic);
19    table
20}
21
22/// Create a new table with titles
23///
24/// The first row will be bold
25pub fn table_with_titles<I: IntoIterator<Item = T>, T: ToString>(titles: I) -> Table {
26    let mut table = table();
27    _ = table.set_header(titles.into_iter().map(bold_cell));
28    table
29}
30
31/// Create a new table with titles and right aligned columns
32pub fn table_right_from<I: IntoIterator<Item = T>, T: ToString>(start: usize, titles: I) -> Table {
33    let mut table = table_with_titles(titles);
34    // set alignment of all rows except first start row
35    table
36        .column_iter_mut()
37        .skip(start)
38        .for_each(|c| c.set_cell_alignment(CellAlignment::Right));
39
40    table
41}
42
43/// Convert a [`ByteSize`] to a human readable string
44#[must_use]
45pub fn bytes_size_to_string(b: u64) -> String {
46    ByteSize(b).to_string_as(true)
47}