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
use std::{fmt, iter::FromIterator};
use papergrid::Grid;
use crate::{builder::Builder, Object, Tabled};
pub trait TableOption {
fn change(&mut self, grid: &mut Grid);
}
impl<T> TableOption for &mut T
where
T: TableOption + ?Sized,
{
fn change(&mut self, grid: &mut Grid) {
T::change(self, grid)
}
}
pub trait CellOption {
fn change_cell(&mut self, grid: &mut Grid, row: usize, column: usize);
}
pub struct Table {
pub(crate) grid: Grid,
}
impl Table {
pub fn new<T: Tabled>(iter: impl IntoIterator<Item = T>) -> Self {
Self::from_iter(iter)
}
pub fn shape(&self) -> (usize, usize) {
(self.grid.count_rows(), self.grid.count_columns())
}
pub fn with<O>(mut self, mut option: O) -> Self
where
O: TableOption,
{
option.change(&mut self.grid);
self
}
}
impl fmt::Display for Table {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.grid)
}
}
impl<D> FromIterator<D> for Table
where
D: Tabled,
{
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = D>,
{
let rows = iter.into_iter().map(|t| t.fields());
Builder::from_iter(rows).set_header(D::headers()).build()
}
}
pub struct Modify<O> {
obj: O,
modifiers: Vec<Box<dyn CellOption>>,
}
impl<O> Modify<O>
where
O: Object,
{
pub fn new(obj: O) -> Self {
Self {
obj,
modifiers: Vec::new(),
}
}
pub fn with<F>(mut self, f: F) -> Self
where
F: CellOption + 'static,
{
let func = Box::new(f);
self.modifiers.push(func);
self
}
}
impl<O> TableOption for Modify<O>
where
O: Object,
{
fn change(&mut self, grid: &mut Grid) {
let cells = self.obj.cells(grid.count_rows(), grid.count_columns());
for func in &mut self.modifiers {
for &(row, column) in &cells {
func.change_cell(grid, row, column)
}
}
}
}
pub trait TableIteratorExt {
fn table(self) -> Table;
}
impl<T, U> TableIteratorExt for U
where
T: Tabled,
U: IntoIterator<Item = T>,
{
fn table(self) -> Table {
Table::new(self)
}
}