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
use std::fmt::{Debug, Display, Formatter, LowerHex, Result};
const DEFAULT_PRECISION: usize = 10;
const ELLIPSIS: &str = "..";
pub struct HexFmt<T>(pub T);
impl<T: AsRef<[u8]>> Debug for HexFmt<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
LowerHex::fmt(self, f)
}
}
impl<T: AsRef<[u8]>> Display for HexFmt<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
LowerHex::fmt(self, f)
}
}
impl<T: AsRef<[u8]>> LowerHex for HexFmt<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
let precision = f.precision().unwrap_or(DEFAULT_PRECISION);
let bytes = self.0.as_ref();
if 2 * bytes.len() <= precision {
for byte in bytes {
write!(f, "{:02x}", byte)?;
}
return Ok(());
}
if precision <= ELLIPSIS.len() {
return write!(f, "{:.*}", precision, ELLIPSIS);
}
let num_hex_digits = precision.saturating_sub(ELLIPSIS.len());
let right = num_hex_digits / 2;
let left = num_hex_digits - right;
for byte in &bytes[..(left / 2)] {
write!(f, "{:02x}", byte)?;
}
if left & 1 == 1 {
write!(f, "{:1x}", bytes[left / 2] >> 4)?;
}
f.write_str(ELLIPSIS)?;
if right & 1 == 1 {
write!(f, "{:1x}", bytes[(bytes.len() - right / 2 - 1)] & 0x0f)?;
}
for byte in &bytes[(bytes.len() - right / 2)..] {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
pub struct HexList<T>(pub T);
impl<T: Clone + IntoIterator> Debug for HexList<T>
where
T::Item: AsRef<[u8]>,
{
fn fmt(&self, f: &mut Formatter) -> Result {
LowerHex::fmt(self, f)
}
}
impl<T: Clone + IntoIterator> Display for HexList<T>
where
T::Item: AsRef<[u8]>,
{
fn fmt(&self, f: &mut Formatter) -> Result {
LowerHex::fmt(self, f)
}
}
impl<T: Clone + IntoIterator> LowerHex for HexList<T>
where
T::Item: AsRef<[u8]>,
{
fn fmt(&self, f: &mut Formatter) -> Result {
let entries = self.0.clone().into_iter().map(HexFmt);
f.debug_list().entries(entries).finish()
}
}
#[cfg(test)]
mod tests {
use super::HexFmt;
#[test]
fn test_fmt() {
assert_eq!("", &format!("{:.0}", HexFmt(&[0x01])));
assert_eq!(".", &format!("{:.1}", HexFmt(&[0x01])));
assert_eq!("01", &format!("{:.2}", HexFmt(&[0x01])));
assert_eq!("..", &format!("{:.2}", HexFmt(&[0x01, 0x23])));
}
}