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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use crate::{Expression, RuntimeErrorKind};
use std::fmt;
/// Table
#[derive(Clone, PartialEq)]
pub struct TableData {
headers: Vec<String>,
rows: Vec<Vec<Expression>>,
groups: Vec<usize>,
}
impl TableData {
/// 创建新的表格
pub fn new(headers: Vec<String>, rows: Vec<Vec<Expression>>) -> Self {
Self {
headers,
rows,
groups: vec![],
}
}
pub fn with_header(headers: Vec<String>) -> Self {
Self {
headers,
rows: Vec::new(),
groups: vec![],
}
}
/// 添加group标记
pub fn set_groups(&mut self, groups: &[String]) {
self.groups = self.column_indexes(groups);
self.groups.sort_by(|a, b| b.cmp(a)); // 逆序很重要
self.groups.dedup(); // 去重很重要
}
pub fn groups(&self) -> &[usize] {
&self.groups
}
pub fn is_grouped(&self) -> bool {
!self.groups.is_empty()
}
/// 添加新行
pub fn push_row(&mut self, row: Vec<Expression>) {
// 确保行的列数与表头一致,不足则填充 None
let mut padded_row = row;
if padded_row.len() < self.headers.len() {
padded_row.resize(self.headers.len(), Expression::None);
} else if padded_row.len() > self.headers.len() {
// 如果行太长,截断到表头长度
padded_row.truncate(self.headers.len());
}
self.rows.push(padded_row);
}
/// 清空并设置数据
pub fn set_rows(&mut self, rows: Vec<Vec<Expression>>) -> Result<(), RuntimeErrorKind> {
// 确保行的列数与表头一致
for row in rows.iter() {
if row.len() != self.column_count() {
return Err(RuntimeErrorKind::CustomError(
"row size mismatch: {row}".into(),
));
}
}
self.rows = rows;
Ok(())
}
pub fn set_rows_vec(&mut self, rows: Vec<Expression>) -> Result<(), RuntimeErrorKind> {
// 确保行的列数与表头一致
let rs = rows
.into_iter()
.map(|row| match row {
Expression::List(r) => r.as_ref().clone(),
Expression::Map(m) => self
.headers
.iter()
.map(|header| m.get(header.as_str()).cloned().unwrap_or(Expression::None))
.collect::<Vec<_>>(),
_ => vec![],
})
.collect::<Vec<Vec<_>>>();
for row in rs.iter() {
if row.len() != self.column_count() {
return Err(RuntimeErrorKind::CustomError(
"row size mismatch: {row}".into(),
));
}
}
self.rows = rs;
Ok(())
}
/// 获取列数据
pub fn get_column(&self, index: usize) -> Option<Vec<Expression>> {
if index >= self.headers.len() {
return None;
}
Some(
self.rows
.iter()
.map(|row| row.get(index).cloned().unwrap_or(Expression::None))
.collect(),
)
}
pub fn column_indexes(&self, col_names: &[String]) -> Vec<usize> {
col_names
.iter()
.filter_map(|x| self.headers.iter().position(|h| h == x))
.collect()
}
pub fn columns(&self, indexes: &[usize]) -> Option<Vec<Vec<Expression>>> {
if indexes.is_empty() {
return None;
}
Some(
self.rows
.iter()
.map(|row| {
indexes
.iter()
.map(|i| row.get(*i).map_or(Expression::None, |x| x.clone()))
.collect()
})
.collect::<Vec<_>>(),
)
}
/// 获取行数据
pub fn get_row(&self, index: usize) -> Option<&[Expression]> {
self.rows.get(index).map(|row| row.as_slice())
}
/// 过滤行
pub fn filter_rows<F>(&self, mut predicate: F) -> TableData
where
F: FnMut(usize, &[Expression]) -> bool,
{
let filtered_rows = self
.rows
.iter()
.enumerate()
.filter_map(|(i, row)| {
if predicate(i, row.as_slice()) {
Some(row.clone())
} else {
None
}
})
.collect();
TableData {
headers: self.headers.clone(),
rows: filtered_rows,
groups: self.groups.clone(),
}
}
/// 按列排序
// pub fn sort_by_column(&mut self, column: usize) {
// let mut rows = self.rows.clone();
// rows.sort_by(|a, b| match (a.get(column), b.get(column)) {
// (Some(a_val), Some(b_val)) => a_val.cmp(b_val),
// _ => std::cmp::Ordering::Equal,
// });
// let _ = self.set_rows(rows);
// }
/// 获取表头
pub fn headers(&self) -> &[String] {
&self.headers
}
pub fn rows(&self) -> &Vec<Vec<Expression>> {
&self.rows
}
/// 获取行数
pub fn row_count(&self) -> usize {
self.rows.len()
}
/// 获取列数
pub fn column_count(&self) -> usize {
self.headers.len()
}
/// 转换为 List<Map> 格式(向后兼容)
pub fn to_map(&self) -> Expression {
Expression::from(self.to_map_vec())
}
pub fn to_map_vec(&self) -> Vec<Expression> {
use std::collections::BTreeMap;
self.rows
.iter()
.map(|row| {
let map: BTreeMap<String, Expression> = self
.headers
.iter()
.enumerate()
.map(|(i, header)| {
let value = row.get(i).cloned().unwrap_or(Expression::None);
(header.clone(), value)
})
.collect();
Expression::from(map)
})
.collect::<Vec<_>>()
}
}
// impl fmt::Debug for TableData {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// }
impl fmt::Display for TableData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
// 美化格式输出
let headers = if self.groups.is_empty() {
self.headers.clone()
} else {
let mut h = self.headers.clone();
let _ = self
.groups
.clone()
.into_iter()
.map(|g| h.swap_remove(g))
.collect::<Vec<_>>();
h
};
if headers.is_empty() {
return write!(f, "[]");
}
// 计算每列的最大宽度
let mut col_widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
if self.groups.is_empty() {
for row in &self.rows {
for (i, cell) in row.iter().enumerate() {
if i < col_widths.len() {
let cell_str = cell.to_string();
col_widths[i] = col_widths[i].max(cell_str.len());
}
}
}
} else {
for row in &self.rows {
let mut row = row.clone();
let _ = self
.groups
.clone()
.into_iter()
.map(|g| row.swap_remove(g))
.collect::<Vec<_>>();
for (i, cell) in row.iter().enumerate() {
if i < col_widths.len() {
let cell_str = cell.to_string();
col_widths[i] = col_widths[i].max(cell_str.len());
}
}
}
}
// 输出表头
writeln!(
f,
"{}",
"─".repeat(col_widths.iter().sum::<usize>() + col_widths.len() * 3 - 1)
)?;
for (i, header) in headers.iter().enumerate() {
if i > 0 {
write!(f, " │ ")?;
}
write!(f, "{:width$}", header, width = col_widths[i])?;
}
writeln!(f)?;
writeln!(
f,
"{}",
"─".repeat(col_widths.iter().sum::<usize>() + col_widths.len() * 3 - 1)
)?;
// 输出数据行
if self.groups.is_empty() {
for row in &self.rows {
for (i, cell) in row.iter().enumerate() {
if i > 0 {
write!(f, " │ ")?;
}
write!(f, "{:width$}", cell.to_string(), width = col_widths[i])?;
}
writeln!(f)?;
}
} else {
let mut current_group: Vec<Expression> = vec![];
for row in &self.rows {
let mut row = row.clone();
let labels = self
.groups
.clone()
.into_iter()
.map(|g| row.swap_remove(g))
.collect::<Vec<_>>();
if labels != current_group {
writeln!(
f,
"───── {} ─────",
labels
.iter()
.map(|g| g.to_string())
.collect::<Vec<_>>()
.join(" ")
)?;
current_group = labels;
}
for (i, cell) in row.iter().enumerate() {
if i > 0 {
write!(f, " │ ")?;
}
write!(f, "{:width$}", cell.to_string(), width = col_widths[i])?;
}
writeln!(f)?;
}
}
if !self.rows.is_empty() {
writeln!(
f,
"{}",
"─".repeat(col_widths.iter().sum::<usize>() + col_widths.len() * 3 - 1)
)?;
}
return Ok(());
}
// 紧凑格式输出
writeln!(f, "{{")?;
writeln!(f, " headers: [")?;
writeln!(f, " {}", self.headers.join(", "))?;
writeln!(f, " ]\n")?;
writeln!(f, " groups: [")?;
writeln!(f, " {:?}", self.groups)?;
writeln!(f, " ]\n")?;
writeln!(f, " rows: [")?;
for row in &self.rows {
writeln!(
f,
" [{}]",
row.iter()
.map(|cell| cell.to_string())
.collect::<Vec<_>>()
.join(",")
)?;
}
writeln!(f, " ]")?;
writeln!(f, "}}")
}
}