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
extern crate smallvec;
extern crate textwrap;
extern crate unicode_width;
use smallvec::*;
use std::io::{Result, Write};
use std::iter::repeat;
use std::str;
use textwrap::fill;
use unicode_width::UnicodeWidthStr;
const ENDSL: &[u8] = b"| ";
const ENDSR: &[u8] = b" |\n";
#[cfg(not(feature = "clippy"))]
const FERRIS: &[u8] = br#"
\
\
_~^~^~_
\) / o o \ (/
'_ - _'
/ '-----' \
"#;
#[cfg(feature = "clippy")]
const CLIPPY: &[u8] = br#"
\
\
__
/ \
| |
@ @
| |
|| |/
|| ||
|\_/|
\___/
"#;
const NEWLINE: u8 = b'\n';
const DASH: u8 = b'-';
const UNDERSCORE: u8 = b'_';
const BUFSIZE: usize = 2048;
pub fn say<W>(input: &[u8], max_width: usize, writer: &mut W) -> Result<()>
where
W: Write,
{
let mut write_buffer = SmallVec::<[u8; BUFSIZE]>::new();
let wrapped = fill(unsafe { str::from_utf8_unchecked(input) }, max_width);
let lines: Vec<&str> = wrapped.lines().collect();
let line_count = lines.len();
let actual_width = longest_line(&lines);
let mut top_bar_buffer: Vec<u8> = repeat(UNDERSCORE).take(actual_width + 2).collect();
top_bar_buffer.insert(0, b' ');
let mut bottom_bar_buffer: Vec<u8> = repeat(DASH).take(actual_width + 2).collect();
bottom_bar_buffer.insert(0, b' ');
write_buffer.extend_from_slice(&top_bar_buffer);
write_buffer.push(NEWLINE);
for (current_line, line) in lines.into_iter().enumerate() {
if line_count == 1 {
write_buffer.extend_from_slice(b"< ");
} else if current_line == 0 {
write_buffer.extend_from_slice(b"/ ");
} else if current_line == line_count - 1 {
write_buffer.extend_from_slice(b"\\ ");
} else {
write_buffer.extend_from_slice(ENDSL);
}
let line_len = UnicodeWidthStr::width(line);
write_buffer.extend_from_slice(line.as_bytes());
for _i in line_len..actual_width {
write_buffer.extend_from_slice(b" ");
}
if line_count == 1 {
write_buffer.extend_from_slice(b" >\n");
} else if current_line == 0 {
write_buffer.extend_from_slice(b" \\\n");
} else if current_line == line_count - 1 {
write_buffer.extend_from_slice(b" /\n");
} else {
write_buffer.extend_from_slice(ENDSR);
}
}
write_buffer.extend_from_slice(&bottom_bar_buffer);
#[cfg(feature = "clippy")]
write_buffer.extend_from_slice(CLIPPY);
#[cfg(not(feature = "clippy"))]
write_buffer.extend_from_slice(FERRIS);
writer.write_all(&write_buffer)?;
Ok(())
}
fn longest_line(lines: &[&str]) -> usize {
let mut max_width = 0;
for line in lines {
let line_width = UnicodeWidthStr::width(line.to_owned());
if line_width > max_width {
max_width = line_width;
}
}
max_width
}