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
use minimad::Alignment;
use crate::compound_style::CompoundStyle;
#[derive(Debug, Clone, Copy)]
pub struct Spacing {
pub width: usize,
pub align: Alignment,
}
fn truncate(s: &str, max_chars: usize) -> &str {
match s.char_indices().nth(max_chars) {
None => s,
Some((idx, _)) => &s[..idx],
}
}
impl Spacing {
#[inline(always)]
pub fn completions(align: Alignment, inner_width: usize, outer_width: usize) -> (usize, usize) {
if inner_width >= outer_width {
return (0, 0);
}
match align {
Alignment::Left | Alignment::Unspecified => (0, outer_width - inner_width),
Alignment::Center => {
let lp = (outer_width - inner_width) / 2;
(lp, outer_width - inner_width - lp)
},
Alignment::Right => (outer_width - inner_width, 0),
}
}
#[inline(always)]
pub fn optional_completions(align: Alignment, inner_width: usize, outer_width: Option<usize>) -> (usize, usize) {
match outer_width {
Some(outer_width) => Spacing::completions(align, inner_width, outer_width),
None => (0, 0),
}
}
#[inline(always)]
pub fn completions_for(&self, inner_width: usize) -> (usize, usize) {
Spacing::completions(self.align, inner_width, self.width)
}
pub fn print_counted_str(&self, s: &str, str_width: usize, style: &CompoundStyle) {
if str_width >= self.width {
let s = truncate(s, self.width);
print!("{}", style.apply_to(s));
} else {
let (lp, rp) = self.completions_for(str_width);
let mut con = String::new();
for _ in 0..lp {
con.push(' ');
}
con.push_str(s);
for _ in 0..rp {
con.push(' ');
}
print!("{}", style.apply_to(&con));
}
}
pub fn print_str(&self, s: &str, style: &CompoundStyle) {
self.print_counted_str(s, s.chars().count(), style);
}
}