File: colorization.rs

package info (click to toggle)
rustc-web 1.78.0%2Bdfsg1-2~deb11u3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,245,360 kB
  • sloc: xml: 147,985; javascript: 18,022; sh: 11,083; python: 10,265; ansic: 6,172; cpp: 5,023; asm: 4,390; makefile: 4,269
file content (69 lines) | stat: -rw-r--r-- 2,160 bytes parent folder | download | duplicates (16)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! This example demonstrates using the [`Color`] [setting](tabled::settings) to
//! stylize text, backgrounds, and borders.
//!
//! * 🚩 This example requires the `color` feature.
//!
//! * Note how [`Format::content()`] is used to break out [`CellOption`]
//! specifications. This is helpful for organizing extensive [`Table`] configurations.

use tabled::{
    builder::Builder,
    settings::{object::Rows, style::Style, themes::Colorization, Color, Concat},
    Table, Tabled,
};

#[derive(Tabled)]
#[tabled(rename_all = "UPPERCASE")]
struct Employee {
    id: usize,
    #[tabled(rename = "FIRST NAME")]
    first_name: String,
    #[tabled(rename = "LAST NAME")]
    last_name: String,
    salary: usize,
    comment: String,
}

impl Employee {
    fn new(id: usize, first_name: &str, last_name: &str, salary: usize, comment: &str) -> Self {
        Self {
            id,
            salary,
            first_name: first_name.to_string(),
            last_name: last_name.to_string(),
            comment: comment.to_string(),
        }
    }
}

fn main() {
    let data = vec![
        Employee::new(1, "Arya", "Stark", 3000, ""),
        Employee::new(20, "Jon", "Snow", 2000, "You know nothing, Jon Snow!"),
        Employee::new(300, "Tyrion", "Lannister", 5000, ""),
    ];

    let total = data.iter().map(|e| e.salary).sum::<usize>();
    let total_row = Builder::from(vec![vec![
        String::from(""),
        String::from(""),
        String::from("TOTAL"),
        total.to_string(),
    ]])
    .build();

    let color_data_primary = Color::BG_WHITE | Color::FG_BLACK;
    let color_data_second = Color::BG_BRIGHT_WHITE | Color::FG_BLACK;
    let color_head = Color::BOLD | Color::BG_CYAN | Color::FG_BLACK;
    let color_footer = Color::BOLD | Color::BG_BLUE | Color::FG_BLACK;

    let mut table = Table::new(data);
    table
        .with(Concat::vertical(total_row))
        .with(Style::empty())
        .with(Colorization::rows([color_data_primary, color_data_second]))
        .with(Colorization::exact([color_head], Rows::first()))
        .with(Colorization::exact([color_footer], Rows::last()));

    println!("{table}");
}