tabled/features/
format.rs

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
//! This module contains a list of primitives to help to modify a [`Table`].
//!
//! [`Table`]: crate::Table

use papergrid::{
    records::{Records, RecordsMut},
    width::CfgWidthFunction,
    Entity,
};

use crate::{CellOption, Table};

/// A formatting function of particular cells on a [`Table`].
///
/// [`Table`]: crate::Table
#[derive(Debug)]
pub struct Format<F> {
    f: F,
}

impl Format<()> {
    /// This function creates a new [`Format`] instance, so
    /// it can be used as a grid setting.
    ///
    /// # Example
    ///
    /// ```
    /// use tabled::{Table, format::Format, object::Rows, Modify};
    ///
    /// let data = vec![
    ///     (0, "Grodno", true),
    ///     (1, "Minsk", true),
    ///     (2, "Hamburg", false),
    ///     (3, "Brest", true),
    /// ];
    ///
    /// let table = Table::new(&data)
    ///                .with(Modify::new(Rows::new(1..)).with(Format::new(|s| format!(": {} :", s))))
    ///                .to_string();
    ///
    /// assert_eq!(table, "+-------+-------------+-----------+\n\
    ///                    | i32   | &str        | bool      |\n\
    ///                    +-------+-------------+-----------+\n\
    ///                    | : 0 : | : Grodno :  | : true :  |\n\
    ///                    +-------+-------------+-----------+\n\
    ///                    | : 1 : | : Minsk :   | : true :  |\n\
    ///                    +-------+-------------+-----------+\n\
    ///                    | : 2 : | : Hamburg : | : false : |\n\
    ///                    +-------+-------------+-----------+\n\
    ///                    | : 3 : | : Brest :   | : true :  |\n\
    ///                    +-------+-------------+-----------+");
    /// ```
    ///
    pub fn new<F>(f: F) -> Format<F>
    where
        F: FnMut(&str) -> String,
    {
        Format { f }
    }

    /// This function creates a new [`FormatWithIndex`], so
    /// it can be used as a grid setting.
    ///
    /// It's different from [`Format::new`] as it also provides a row and column index.
    ///
    /// # Example
    ///
    /// ```
    /// use tabled::{Table, format::Format, object::Rows, Modify};
    ///
    /// let data = vec![
    ///     (0, "Grodno", true),
    ///     (1, "Minsk", true),
    ///     (2, "Hamburg", false),
    ///     (3, "Brest", true),
    /// ];
    ///
    /// let table = Table::new(&data)
    ///                .with(Modify::new(Rows::single(0)).with(Format::with_index(|_, (_, column)| column.to_string())))
    ///                .to_string();
    ///
    /// assert_eq!(table, "+---+---------+-------+\n\
    ///                    | 0 | 1       | 2     |\n\
    ///                    +---+---------+-------+\n\
    ///                    | 0 | Grodno  | true  |\n\
    ///                    +---+---------+-------+\n\
    ///                    | 1 | Minsk   | true  |\n\
    ///                    +---+---------+-------+\n\
    ///                    | 2 | Hamburg | false |\n\
    ///                    +---+---------+-------+\n\
    ///                    | 3 | Brest   | true  |\n\
    ///                    +---+---------+-------+");
    /// ```
    pub fn with_index<F>(f: F) -> FormatWithIndex<F>
    where
        F: FnMut(&str, (usize, usize)) -> String,
    {
        FormatWithIndex::new(f)
    }

    /// Multiline a helper function for changing multiline content of cell.
    /// Using this formatting applied for all rows not to a string as a whole.
    ///
    /// ```rust,no_run
    /// use tabled::{Table, format::Format, object::Segment, Modify};
    ///
    /// let data: Vec<&'static str> = Vec::new();
    /// let table = Table::new(&data)
    ///     .with(Modify::new(Segment::all()).with(Format::multiline(|s| format!("{}", s))))
    ///     .to_string();
    /// ```
    pub fn multiline<F>(f: F) -> Format<impl Fn(&str) -> String>
    where
        F: Fn(&str) -> String,
    {
        let closure = move |s: &str| {
            let mut v = Vec::new();
            for line in s.lines() {
                v.push(f(line));
            }

            v.join("\n")
        };

        Format::new(closure)
    }
}

impl<F, R> CellOption<R> for Format<F>
where
    F: FnMut(&str) -> String,
    R: Records + RecordsMut<String>,
{
    fn change_cell(&mut self, table: &mut Table<R>, entity: Entity) {
        let width_fn = CfgWidthFunction::from_cfg(table.get_config());
        let (count_rows, count_cols) = table.shape();
        for pos in entity.iter(count_rows, count_cols) {
            let records = table.get_records();
            let content = records.get_text(pos);
            let content = (self.f)(content);
            table.get_records_mut().set(pos, content, &width_fn);
        }

        table.destroy_width_cache();
        table.destroy_height_cache();
    }
}

/// [`FormatWithIndex`] is like a [`Format`] an abstraction over a function you can use against a cell.
///
/// It differerent from [`Format`] that it provides a row and column index.
#[derive(Debug)]
pub struct FormatWithIndex<F> {
    f: F,
}

impl<F> FormatWithIndex<F>
where
    F: FnMut(&str, (usize, usize)) -> String,
{
    fn new(f: F) -> Self {
        Self { f }
    }
}

impl<F, R> CellOption<R> for FormatWithIndex<F>
where
    F: FnMut(&str, (usize, usize)) -> String,
    R: Records + RecordsMut<String>,
{
    fn change_cell(&mut self, table: &mut Table<R>, entity: Entity) {
        let width_fn = CfgWidthFunction::from_cfg(table.get_config());
        let (count_rows, count_cols) = table.shape();
        for pos in entity.iter(count_rows, count_cols) {
            let records = table.get_records();
            let content = records.get_text(pos);
            let content = (self.f)(content, pos);
            table.get_records_mut().set(pos, content, &width_fn);
        }

        table.destroy_width_cache();
        table.destroy_height_cache();
    }
}

impl<F, R> CellOption<R> for F
where
    F: FnMut(&str) -> String,
    R: Records + RecordsMut<String>,
{
    fn change_cell(&mut self, table: &mut Table<R>, entity: Entity) {
        Format::new(self).change_cell(table, entity);
    }
}

impl<R> CellOption<R> for String
where
    R: Records + RecordsMut<String>,
{
    fn change_cell(&mut self, table: &mut Table<R>, entity: Entity) {
        let width_fn = CfgWidthFunction::from_cfg(table.get_config());
        let (count_rows, count_cols) = table.shape();
        for pos in entity.iter(count_rows, count_cols) {
            let text = self.clone();
            table.get_records_mut().set(pos, text, &width_fn);
        }

        table.destroy_width_cache();
        table.destroy_height_cache();
    }
}