Struct Table

Source
pub struct Table { /* private fields */ }
Expand description

The structure provides an interface for building a table for types that implements Tabled.

To build a string representation of a table you must use a std::fmt::Display. Or simply call .to_string() method.

The default table Style is Style::ascii, with a single left and right Padding.

§Example

§Basic usage

use tabled::Table;

let table = Table::new(&["Year", "2021"]);

§With settings

use tabled::{Table, settings::{Style, Alignment}};

let data = vec!["Hello", "2021"];
let mut table = Table::new(&data);
table
    .with(Style::psql())
    .with(Alignment::left());

§With a Tabled trait.

use tabled::{Table, Tabled};

#[derive(Tabled)]
struct Character {
    good: f32,
    bad: f32,
    encouraging: f32,
    destructive: f32,
}

#[derive(Tabled)]
struct Person<'a>(
    #[tabled(rename = "name")] &'a str,
    #[tabled(inline)] Character,
);

let data = vec![
    Person("007", Character { good: 0.8, bad: 0.2, encouraging: 0.8, destructive: 0.1}),
    Person("001", Character { good: 0.2, bad: 0.5, encouraging: 0.2, destructive: 0.1}),
    Person("006", Character { good: 0.4, bad: 0.1, encouraging: 0.5, destructive: 0.8}),
];

let table = Table::new(&data);

Implementations§

Source§

impl Table

Source

pub fn new<I, T>(iter: I) -> Self
where I: IntoIterator<Item = T>, T: Tabled,

Creates a Table instance, from a list of Tabled values.

If you use a reference iterator you’d better use FromIterator instead. As it has a different lifetime constraints and make less copies therefore.

§Examples
use tabled::{Table, Tabled, assert::assert_table};

#[derive(Tabled)]
struct Relationship {
    love: bool
}

let list = vec![
    Relationship { love: true },
    Relationship { love: false },
];

let table = Table::new(list);

assert_table!(
    table,
    "+-------+"
    "| love  |"
    "+-------+"
    "| true  |"
    "+-------+"
    "| false |"
    "+-------+"
);
§Don’t hesitate to use iterators.
use tabled::{Table, Tabled, assert::assert_table};

#[derive(Tabled)]
struct Relationship {
    person: String,
    love: bool
}

let list = vec![
    Relationship { person: String::from("Clara"), love: true },
    Relationship { person: String::from("Greg"), love: false },
];

// Maybe don't love but don't hate :)
let iter = list.into_iter()
    .map(|mut rel| {
        if !rel.love {
            rel.love = true;
        }

        rel
    });

let table = Table::new(iter);

assert_table!(
    table,
    "+--------+------+"
    "| person | love |"
    "+--------+------+"
    "| Clara  | true |"
    "+--------+------+"
    "| Greg   | true |"
    "+--------+------+"
);
§Notice that you can pass tuples.
use tabled::{Table, Tabled, assert::assert_table};

#[derive(Tabled)]
struct Relationship {
    love: bool
}

let list = vec![
    ("Kate", Relationship { love: true }),
    ("", Relationship { love: false }),
];

let table = Table::new(list);

assert_table!(
    table,
    "+------+-------+"
    "| &str | love  |"
    "+------+-------+"
    "| Kate | true  |"
    "+------+-------+"
    "|      | false |"
    "+------+-------+"
);
§As a different way to create a Table, you can use Table::from_iter.
use std::iter::FromIterator;
use tabled::{Table, assert::assert_table};

let list = vec![
    vec!["Kate", "+", "+", "+", "-"],
    vec!["", "-", "-", "-", "-"],
];

let table = Table::from_iter(list);

assert_table!(
    table,
    "+------+---+---+---+---+"
    "| Kate | + | + | + | - |"
    "+------+---+---+---+---+"
    "|      | - | - | - | - |"
    "+------+---+---+---+---+"
);
Source

pub fn with_capacity<I, T>(iter: I, count_rows: usize) -> Self
where I: IntoIterator<Item = T>, T: Tabled,

Creates a Table instance, from a list of Tabled values.

It’s an optimized version of Table::new.

use tabled::{Table, Tabled, assert::assert_table};

#[derive(Tabled)]
struct Relationship {
    person: String,
    love: bool
}

let list = vec![
    Relationship { person: String::from("Clara"), love: true },
    Relationship { person: String::from("Greg"), love: false },
];

let table = Table::with_capacity(&list, list.len());

assert_table!(
    table,
    "+--------+-------+"
    "| person | love  |"
    "+--------+-------+"
    "| Clara  | true  |"
    "+--------+-------+"
    "| Greg   | false |"
    "+--------+-------+"
);
Source

pub fn nohead<I, T>(iter: I) -> Self
where I: IntoIterator<Item = T>, T: Tabled,

Creates a Table instance, from a list of Tabled values.

Compared to Table::new it does not use a “header” (first line).

If you use a reference iterator you’d better use FromIterator instead. As it has a different lifetime constraints and make less copies therefore.

§Examples
use tabled::{Table, Tabled, assert::assert_table};

#[derive(Tabled)]
struct Relationship {
    love: bool
}

let list = vec![
    ("Kate", Relationship { love: true }),
    ("", Relationship { love: false }),
];

let table = Table::nohead(list);

assert_table!(
    table,
    "+------+-------+"
    "| Kate | true  |"
    "+------+-------+"
    "|      | false |"
    "+------+-------+"
);
Source

pub fn kv<I, T>(iter: I) -> Self
where I: IntoIterator<Item = T>, T: Tabled,

Creates a Key-Value Table instance, from a list of Tabled values.

§Examples
use tabled::{Table, Tabled, assert::assert_table};

#[derive(Tabled)]
#[tabled(rename_all = "PascalCase")]
struct Swim {
    event: String,
    time: String,
    #[tabled(rename = "Pool Length")]
    pool: u8,
}

const POOL_25: u8 = 25;
const POOL_50: u8 = 50;

let list = vec![
    Swim { event: String::from("Men 100 Freestyle"), time: String::from("47.77"), pool: POOL_25 },
    Swim { event: String::from("Men 400 Freestyle"), time: String::from("03:59.16"), pool: POOL_25 },
    Swim { event: String::from("Men 800 Freestyle"), time: String::from("08:06.70"), pool: POOL_25 },
    Swim { event: String::from("Men 4x100 Medley Relay"), time: String::from("03:27.28"), pool: POOL_50 },
];

let table = Table::kv(list);

assert_table!(
    table,
    "+-------------+------------------------+"
    "| Event       | Men 100 Freestyle      |"
    "+-------------+------------------------+"
    "| Time        | 47.77                  |"
    "+-------------+------------------------+"
    "| Pool Length | 25                     |"
    "+-------------+------------------------+"
    "| Event       | Men 400 Freestyle      |"
    "+-------------+------------------------+"
    "| Time        | 03:59.16               |"
    "+-------------+------------------------+"
    "| Pool Length | 25                     |"
    "+-------------+------------------------+"
    "| Event       | Men 800 Freestyle      |"
    "+-------------+------------------------+"
    "| Time        | 08:06.70               |"
    "+-------------+------------------------+"
    "| Pool Length | 25                     |"
    "+-------------+------------------------+"
    "| Event       | Men 4x100 Medley Relay |"
    "+-------------+------------------------+"
    "| Time        | 03:27.28               |"
    "+-------------+------------------------+"
    "| Pool Length | 50                     |"
    "+-------------+------------------------+"
);

Next you’ll find a more complex example with a subtle style.

use tabled::{Table, Tabled, settings::Style};
use tabled::settings::{style::HorizontalLine, Theme};
use tabled::assert::assert_table;

#[derive(Tabled)]
#[tabled(rename_all = "PascalCase")]
struct Swim {
    event: String,
    time: String,
    #[tabled(rename = "Pool Length")]
    pool: u8,
}

const POOL_25: u8 = 25;
const POOL_50: u8 = 50;

let list = vec![
    Swim { event: String::from("Men 100 Freestyle"), time: String::from("47.77"), pool: POOL_25 },
    Swim { event: String::from("Men 400 Freestyle"), time: String::from("03:59.16"), pool: POOL_25 },
    Swim { event: String::from("Men 800 Freestyle"), time: String::from("08:06.70"), pool: POOL_25 },
    Swim { event: String::from("Men 4x100 Medley Relay"), time: String::from("03:27.28"), pool: POOL_50 },
];

let mut table = Table::kv(list);

let mut style = Theme::from_style(Style::rounded().remove_horizontals());
for entry in 1 .. table.count_rows() / Swim::LENGTH {
    style.insert_horizontal_line(entry * Swim::LENGTH, HorizontalLine::inherit(Style::modern()));
}

table.with(style);

assert_table!(
    table,
    "╭─────────────┬────────────────────────╮"
    "│ Event       │ Men 100 Freestyle      │"
    "│ Time        │ 47.77                  │"
    "│ Pool Length │ 25                     │"
    "├─────────────┼────────────────────────┤"
    "│ Event       │ Men 400 Freestyle      │"
    "│ Time        │ 03:59.16               │"
    "│ Pool Length │ 25                     │"
    "├─────────────┼────────────────────────┤"
    "│ Event       │ Men 800 Freestyle      │"
    "│ Time        │ 08:06.70               │"
    "│ Pool Length │ 25                     │"
    "├─────────────┼────────────────────────┤"
    "│ Event       │ Men 4x100 Medley Relay │"
    "│ Time        │ 03:27.28               │"
    "│ Pool Length │ 50                     │"
    "╰─────────────┴────────────────────────╯"
);
Source

pub fn builder<I, T>(iter: I) -> Builder
where T: Tabled, I: IntoIterator<Item = T>,

Creates a builder from a data set given.

§Example
use tabled::{
    Table, Tabled,
    settings::{object::Segment, Modify, Alignment}
};

#[derive(Tabled)]
struct User {
    name: &'static str,
    #[tabled(inline("device::"))]
    device: Device,
}

#[derive(Tabled)]
enum Device {
    PC,
    Mobile
}

let data = vec![
    User { name: "Vlad", device: Device::Mobile },
    User { name: "Dimitry", device: Device::PC },
    User { name: "John", device: Device::PC },
];

let mut table = Table::builder(data)
    .index()
    .column(0)
    .transpose()
    .build()
    .modify(Segment::new(1.., 1..), Alignment::center())
    .to_string();

assert_eq!(
    table,
    "+----------------+------+---------+------+\n\
     | name           | Vlad | Dimitry | John |\n\
     +----------------+------+---------+------+\n\
     | device::PC     |      |    +    |  +   |\n\
     +----------------+------+---------+------+\n\
     | device::Mobile |  +   |         |      |\n\
     +----------------+------+---------+------+"
)
Source

pub fn with<O>(&mut self, option: O) -> &mut Self

It’s a generic function which applies options to the Table.

It applies settings immediately.

use tabled::{Table, settings::Style};
use tabled::assert::assert_table;

let data = vec![
    ("number", "name"),
    ("285-324-7322", "Rosalia"),
    ("564.549.6468", "Mary"),
];

let mut table = Table::new(data);
table.with(Style::markdown());

assert_table!(
    table,
    "| &str         | &str    |"
    "|--------------|---------|"
    "| number       | name    |"
    "| 285-324-7322 | Rosalia |"
    "| 564.549.6468 | Mary    |"
);
Source

pub fn modify<T, O>(&mut self, target: T, option: O) -> &mut Self

It’s a generic function which applies options to particular cells on the Table. Target cells using Objects such as Cell, Rows, Location and more.

It applies settings immediately.

use tabled::{Table, settings::{object::Columns, Alignment}};
use tabled::assert::assert_table;

let data = vec![
    ("number", "name"),
    ("285-324-7322", "Rosalia"),
    ("564.549.6468", "Mary"),
];

let mut table = Table::new(data);
table.modify(Columns::first(), Alignment::right());
table.modify(Columns::one(1), Alignment::center());

assert_table!(
    table,
    "+--------------+---------+"
    "|         &str |  &str   |"
    "+--------------+---------+"
    "|       number |  name   |"
    "+--------------+---------+"
    "| 285-324-7322 | Rosalia |"
    "+--------------+---------+"
    "| 564.549.6468 |  Mary   |"
    "+--------------+---------+"
);
Source

pub fn shape(&self) -> (usize, usize)

Returns a table shape (count rows, count columns).

Source

pub fn count_rows(&self) -> usize

Returns an amount of rows in the table.

Source

pub fn count_columns(&self) -> usize

Returns an amount of columns in the table.

Source

pub fn is_empty(&self) -> bool

Returns a table shape (count rows, count columns).

Source

pub fn total_height(&self) -> usize

Returns total widths of a table, including margin and horizontal lines.

Source

pub fn total_width(&self) -> usize

Returns total widths of a table, including margin and vertical lines.

Source

pub fn get_config(&self) -> &ColoredConfig

Returns a table config.

Source

pub fn get_config_mut(&mut self) -> &mut ColoredConfig

Returns a table config.

Source

pub fn get_records(&self) -> &VecRecords<Text<String>>

Returns a used records.

Source

pub fn get_records_mut(&mut self) -> &mut VecRecords<Text<String>>

Returns a used records.

Source

pub fn get_dimension(&self) -> &CompleteDimension

Returns a dimension.

Source

pub fn get_dimension_mut(&mut self) -> &mut CompleteDimension

Returns a dimension.

Trait Implementations§

Source§

impl Clone for Table

Source§

fn clone(&self) -> Table

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Table

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Table

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Table

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Builder> for Table

Source§

fn from(builder: Builder) -> Self

Converts to this type from the input type.
Source§

impl From<Table> for Builder

Source§

fn from(val: Table) -> Self

Converts to this type from the input type.
Source§

impl<T> FromIterator<T> for Table
where T: IntoIterator, T::Item: Into<String>,

Source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl PartialEq for Table

Source§

fn eq(&self, other: &Table) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Table

Source§

impl StructuralPartialEq for Table

Auto Trait Implementations§

§

impl Freeze for Table

§

impl RefUnwindSafe for Table

§

impl Send for Table

§

impl Sync for Table

§

impl Unpin for Table

§

impl UnwindSafe for Table

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.