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
#![cfg(feature = "color")]
use std::fmt;
use super::strings::indent_vec;
use super::{Format, OutputStyle};
fn check_disable_color() {
if atty::isnt(atty::Stream::Stderr) {
colored::control::set_override(false)
}
}
#[derive(Debug, Default)]
struct OutputSegment {
buf: String,
style: OutputStyle,
}
#[derive(Debug)]
pub struct Formatter {
prev: Vec<OutputSegment>,
current: OutputSegment,
}
impl Formatter {
fn new() -> Self {
Self {
prev: Vec::new(),
current: Default::default(),
}
}
pub fn write_str(&mut self, s: impl AsRef<str>) {
self.current.buf.push_str(s.as_ref());
}
pub fn write_char(&mut self, c: char) {
self.current.buf.push(c);
}
pub fn write_fmt(&mut self, output: impl Into<FormattedOutput>) {
let formatted = output.into();
let new_current = OutputSegment {
buf: String::new(),
style: self.current.style.clone(),
};
self.prev
.push(std::mem::replace(&mut self.current, new_current));
self.prev.extend(formatted.segments);
}
pub fn style(&self) -> &OutputStyle {
&self.current.style
}
pub fn set_style(&mut self, style: OutputStyle) {
self.prev.push(std::mem::replace(
&mut self.current,
OutputSegment {
buf: String::new(),
style,
},
));
}
pub fn reset_style(&mut self) {
self.set_style(Default::default());
}
}
#[derive(Debug)]
pub struct FormattedOutput {
segments: Vec<OutputSegment>,
}
impl FormattedOutput {
pub fn new<Value, Fmt>(value: Value, format: Fmt) -> crate::Result<Self>
where
Fmt: Format<Value = Value>,
{
let mut formatter = Formatter::new();
format.fmt(&mut formatter, value)?;
let mut segments = formatter.prev;
segments.push(formatter.current);
Ok(Self { segments })
}
fn indented_inner(self, spaces: u32, hanging: bool) -> Self {
if spaces == 0 {
return self;
}
let mut styles = Vec::with_capacity(self.segments.len());
let mut buffers = Vec::with_capacity(self.segments.len());
for segment in self.segments {
styles.push(segment.style);
buffers.push(segment.buf);
}
Self {
segments: indent_vec(buffers, spaces, hanging)
.into_iter()
.zip(styles)
.map(|(buf, style)| OutputSegment { buf, style })
.collect(),
}
}
pub fn indented(self, spaces: u32) -> Self {
self.indented_inner(spaces, false)
}
pub fn fail(&self) -> ! {
check_disable_color();
panic!("\n{}\n", self);
}
}
impl fmt::Display for FormattedOutput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for segment in &self.segments {
f.write_fmt(format_args!("{}", segment.style.apply(&segment.buf)))?;
}
Ok(())
}
}