tabela
tabela (Portuguese for "table") is a Rust crate that provides a simple and easy-to-use way to display tabular data in the terminal, with the ability to add colors, styles and alignment to each cell.
I decided to write it because I found myself repeating the same table code over and over again in my projects, which consists of iterating through the data and figuring out the widths of each column based on the longest string in each column, including the header if provided, then writing the headers with correct width to a string, then iterating through the data again and writing each cell with the correct width like format!("{:<width1$} {:<width2$}", row.field1, row.field2).
Concepts
- Table: A table is a collection of rows, it also stores the header (if provided) and the separator of the cells. Note that for performance reasons the table stores the rows as
&[&R]instead ofVec<R>. - Row: A row is a trait that represents a row of data in a table, it must implement the
as_rowmethod that returns a vector of cells. For example if you have a data of typeVec<Person>you'd have to implement theRowtrait for&Person, refer to the example below. - Cell: A cell is a struct that represents a cell in a table, it stores the string value of a type
Vthat implements theDisplaytrait, as well as the color (optional), style (optional) and alignment (left by default). - Color: Re-export of
colored::Color. - CellStyle: A enum that represents the style of a cell, it can be
Bold,ItalicorDimmed. - Alignment: A enum that represents the alignment of a cell, it can be
Left,CenterorRight. - TableError: A enum that represents the errors that can occur when formatting a table.
Installation
Add this to your Cargo.toml:
[]
= "^0.2"
Or install it with cargo add tabela.
Usage
use ;
// row type
// row implementation
let data = ;
let data_refs: = data.iter.collect; // rows have to be references, in the future maybe
// support for owned rows will be added
let table = new
.with_header // adds header with bold style
.with_separator; // uses two spaces as separator (personal preference)
let formatted = table.format.unwrap; // errors can only happen in `Table::format` if the
// header length is different than the row length or
// if the other rows' length is different than the first row length
// so I wouldn't worry about using `unwrap` here
println!;
// output (without color/style characters):
//
// Name Some Age
// Johnny 30
// Jane 25
// (extra '\n' at the end)
Tests
Run the tests with cargo test.
Benchmarks
TBA
License
This crate is distributed under the terms of the MIT license.