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
use std;
use std::borrow::Cow;
use std::cmp;
use std::fmt::{Display, Formatter, Result};
use wcwidth::{char_width, str_width};
#[derive(Clone, Copy)]
pub enum Alignment {
Left,
Right,
Center,
}
pub struct Cell<'data> {
pub data: Cow<'data, str>,
pub col_span: usize,
pub alignment: Alignment,
pub pad_content: bool,
}
impl<'data> Cell<'data> {
pub fn new<T>(data: T, col_span: usize) -> Cell<'data>
where
T: Into<Cow<'data, str>>,
{
return Cell {
data: data.into(),
col_span: col_span,
alignment: Alignment::Left,
pad_content: true,
};
}
pub fn new_with_alignment<T>(data: T, col_span: usize, alignment: Alignment) -> Cell<'data>
where
T: Into<Cow<'data, str>>,
{
return Cell {
data: data.into(),
col_span: col_span,
alignment: alignment,
pad_content: true,
};
}
pub fn new_with_alignment_and_padding<T>(
data: T,
col_span: usize,
alignment: Alignment,
pad_content: bool,
) -> Cell<'data>
where
T: Into<Cow<'data, str>>,
{
return Cell {
data: data.into(),
col_span: col_span,
alignment: alignment,
pad_content: pad_content,
};
}
pub fn width(&self) -> usize {
let wrapped = self.wrap_to_width(std::usize::MAX);
let mut max = 0;
for s in wrapped {
let str_width = match str_width(s.as_str()) {
Some(w) => w,
None => 0,
};
max = cmp::max(max, str_width);
}
return max + 2;
}
pub fn split_width(&self) -> f32 {
let res = self.width() as f32 / self.col_span as f32;
return res;
}
pub fn wrap_to_width(&self, width: usize) -> Vec<String> {
let pad_char = match self.pad_content {
true => ' ',
false => '\0',
};
let mut res: Vec<String> = Vec::new();
let mut buf = String::new();
buf.push(pad_char);
for c in self.data.chars().enumerate() {
if str_width(buf.as_str()).unwrap_or_default() as usize
>= width - char_width(pad_char).unwrap_or_default() as usize
|| c.1 == '\n'
{
buf.push(pad_char);
res.push(buf);
buf = String::new();
buf.push(pad_char);
if c.1 == '\n' {
continue;
}
}
buf.push(c.1);
}
buf.push(pad_char);
res.push(buf);
return res;
}
}
impl<'data, T> From<&'data T> for Cell<'data>
where
T: Display,
{
fn from(x: &'data T) -> Cell<'data> {
return Cell::new(format!("{}", x), 1);
}
}
impl<'data> Display for Cell<'data> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.data)
}
}