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
use core::primitive::str;
use core::{default::Default, fmt};
use nu_ansi_term::{Color, Style};
pub fn simple_hex<T: AsRef<[u8]>>(source: &T) -> String {
let mut writer = String::new();
hex_write(&mut writer, source, HexConfig::simple(), None).unwrap_or(());
writer
}
pub fn simple_hex_write<T, W>(writer: &mut W, source: &T) -> fmt::Result
where
T: AsRef<[u8]>,
W: fmt::Write,
{
hex_write(writer, source, HexConfig::simple(), None)
}
pub fn pretty_hex<T: AsRef<[u8]>>(source: &T) -> String {
let mut writer = String::new();
hex_write(&mut writer, source, HexConfig::default(), Some(true)).unwrap_or(());
writer
}
pub fn pretty_hex_write<T, W>(writer: &mut W, source: &T) -> fmt::Result
where
T: AsRef<[u8]>,
W: fmt::Write,
{
hex_write(writer, source, HexConfig::default(), Some(true))
}
pub fn config_hex<T: AsRef<[u8]>>(source: &T, cfg: HexConfig) -> String {
let mut writer = String::new();
hex_write(&mut writer, source, cfg, Some(true)).unwrap_or(());
writer
}
#[derive(Clone, Copy, Debug)]
pub struct HexConfig {
pub title: bool,
pub ascii: bool,
pub width: usize,
pub group: usize,
pub chunk: usize,
pub address_offset: usize,
pub skip: Option<usize>,
pub length: Option<usize>,
}
impl Default for HexConfig {
fn default() -> HexConfig {
HexConfig {
title: true,
ascii: true,
width: 16,
group: 4,
chunk: 1,
address_offset: 0,
skip: None,
length: None,
}
}
}
impl HexConfig {
pub fn simple() -> Self {
HexConfig::default().to_simple()
}
fn delimiter(&self, i: usize) -> &'static str {
if i > 0 && self.chunk > 0 && i % self.chunk == 0 {
if self.group > 0 && i % (self.group * self.chunk) == 0 {
" "
} else {
" "
}
} else {
""
}
}
fn to_simple(self) -> Self {
HexConfig {
title: false,
ascii: false,
width: 0,
..self
}
}
}
fn categorize_byte(byte: &u8) -> (Style, Option<char>) {
let null_char_style = Style::default().fg(Color::Fixed(242));
let null_char = Some('0');
let ascii_printable_style = Style::default().fg(Color::Cyan).bold();
let ascii_printable = None;
let ascii_space_style = Style::default().fg(Color::Green).bold();
let ascii_space = Some(' ');
let ascii_white_space_style = Style::default().fg(Color::Green).bold();
let ascii_white_space = Some('_');
let ascii_other_style = Style::default().fg(Color::Purple).bold();
let ascii_other = Some('•');
let non_ascii_style = Style::default().fg(Color::Yellow).bold();
let non_ascii = Some('×');
if byte == &0 {
(null_char_style, null_char)
} else if byte.is_ascii_graphic() {
(ascii_printable_style, ascii_printable)
} else if byte.is_ascii_whitespace() {
if byte == &32 {
(ascii_space_style, ascii_space)
} else {
(ascii_white_space_style, ascii_white_space)
}
} else if byte.is_ascii() {
(ascii_other_style, ascii_other)
} else {
(non_ascii_style, non_ascii)
}
}
pub fn hex_write<T, W>(
writer: &mut W,
source: &T,
cfg: HexConfig,
with_color: Option<bool>,
) -> fmt::Result
where
T: AsRef<[u8]>,
W: fmt::Write,
{
let use_color = with_color.unwrap_or(false);
if source.as_ref().is_empty() {
return Ok(());
}
let amount = match cfg.length {
Some(len) => len,
None => source.as_ref().len(),
};
let skip = cfg.skip.unwrap_or(0);
let address_offset = cfg.address_offset;
let source_part_vec: Vec<u8> = source
.as_ref()
.iter()
.skip(skip)
.take(amount)
.map(|&x| x as u8)
.collect();
if cfg.title {
if use_color {
writeln!(
writer,
"Length: {0} (0x{0:x}) bytes | {1}printable {2}whitespace {3}ascii_other {4}non_ascii{5}",
source_part_vec.len(),
Style::default().fg(Color::Cyan).bold().prefix(),
Style::default().fg(Color::Green).bold().prefix(),
Style::default().fg(Color::Purple).bold().prefix(),
Style::default().fg(Color::Yellow).bold().prefix(),
Style::default().fg(Color::Yellow).suffix()
)?;
} else {
writeln!(writer, "Length: {0} (0x{0:x}) bytes", source_part_vec.len(),)?;
}
}
let lines = source_part_vec.chunks(if cfg.width > 0 {
cfg.width
} else {
source_part_vec.len()
});
let lines_len = lines.len();
for (i, row) in lines.enumerate() {
if cfg.width > 0 {
let style = Style::default().fg(Color::Cyan);
if use_color {
write!(
writer,
"{}{:08x}{}: ",
style.prefix(),
i * cfg.width + skip + address_offset,
style.suffix()
)?;
} else {
write!(writer, "{:08x}: ", i * cfg.width + skip + address_offset,)?;
}
}
for (i, x) in row.as_ref().iter().enumerate() {
if use_color {
let (style, _char) = categorize_byte(x);
write!(
writer,
"{}{}{:02x}{}",
cfg.delimiter(i),
style.prefix(),
x,
style.suffix()
)?;
} else {
write!(writer, "{}{:02x}", cfg.delimiter(i), x,)?;
}
}
if cfg.ascii {
for j in row.len()..cfg.width {
write!(writer, "{} ", cfg.delimiter(j))?;
}
write!(writer, " ")?;
for x in row {
let (style, a_char) = categorize_byte(x);
let replacement_char = match a_char {
Some(c) => c,
None => *x as char,
};
if use_color {
write!(
writer,
"{}{}{}",
style.prefix(),
replacement_char,
style.suffix()
)?;
} else {
write!(writer, "{}", replacement_char,)?;
}
}
}
if i + 1 < lines_len {
writeln!(writer)?;
}
}
Ok(())
}
pub struct Hex<'a, T: 'a>(&'a T, HexConfig);
impl<'a, T: 'a + AsRef<[u8]>> fmt::Display for Hex<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hex_write(f, self.0, self.1.to_simple(), None)
}
}
impl<'a, T: 'a + AsRef<[u8]>> fmt::Debug for Hex<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hex_write(f, self.0, self.1, None)
}
}
pub trait PrettyHex: Sized {
fn hex_dump(&self) -> Hex<Self>;
fn hex_conf(&self, cfg: HexConfig) -> Hex<Self>;
}
impl<T> PrettyHex for T
where
T: AsRef<[u8]>,
{
fn hex_dump(&self) -> Hex<Self> {
Hex(self, HexConfig::default())
}
fn hex_conf(&self, cfg: HexConfig) -> Hex<Self> {
Hex(self, cfg)
}
}