tabled/features/width/justify.rs
1//! This module contains [`Justify`] structure, used to set an exact width to each column.
2
3use papergrid::records::{Records, RecordsMut};
4
5use crate::{
6 measurment::{Max, Measurment, Min},
7 CellOption, Table, TableOption, Width,
8};
9
10/// Justify sets all columns widths to the set value.
11///
12/// Be aware that it doesn't consider padding.
13/// So if you want to set a exact width you might need to use [`Padding`] to set it to 0.
14///
15/// ## Examples
16///
17/// ```
18/// use tabled::{width::Justify, Style, Modify, object::Segment, Padding, Table};
19///
20/// let data = ["Hello", "World", "!"];
21///
22/// let table = Table::new(&data)
23/// .with(Style::markdown())
24/// .with(Modify::new(Segment::all()).with(Padding::zero()))
25/// .with(Justify::new(3));
26/// ```
27///
28/// [`Max`] usage to justify by a max column width.
29///
30/// ```
31/// use tabled::{width::Justify, Style, Table};
32///
33/// let data = ["Hello", "World", "!"];
34///
35/// let table = Table::new(&data)
36/// .with(Style::markdown())
37/// .with(Justify::max());
38/// ```
39///
40/// [`Padding`]: crate::Padding
41#[derive(Debug)]
42pub struct Justify<W> {
43 width: W,
44}
45
46impl<W> Justify<W>
47where
48 W: Measurment<Width>,
49{
50 /// Creates a new [`Justify`] instance.
51 ///
52 /// Be aware that [`Padding`] is not considered when comparing the width.
53 ///
54 /// [`Padding`]: crate::Padding
55 pub fn new(width: W) -> Self {
56 Self { width }
57 }
58}
59
60impl Justify<Max> {
61 /// Creates a new Justify instance with a Max width used as a value.
62 pub fn max() -> Self {
63 Self { width: Max }
64 }
65}
66
67impl Justify<Min> {
68 /// Creates a new Justify instance with a Min width used as a value.
69 pub fn min() -> Self {
70 Self { width: Min }
71 }
72}
73
74impl<W, R> TableOption<R> for Justify<W>
75where
76 W: Measurment<Width>,
77 R: Records + RecordsMut<String>,
78{
79 fn change(&mut self, table: &mut Table<R>) {
80 let width = self.width.measure(table.get_records(), table.get_config());
81
82 let (count_rows, count_cols) = table.shape();
83 for row in 0..count_rows {
84 for col in 0..count_cols {
85 let pos = (row, col).into();
86 Width::increase(width).change_cell(table, pos);
87 Width::truncate(width).change_cell(table, pos);
88 }
89 }
90
91 // we can't cache the widths because it doesn't consider padding
92 // table.cache_width(vec![width; table.shape().1]);
93 table.destroy_width_cache();
94 table.destroy_height_cache();
95 }
96}