Skip to content

Commit d1e461e

Browse files
committed
Improve packet pretty-printing.
Use more functional constructors (into_iter, map, etc.) instead of mutable values and a for loop. This yields a packet-printing routine that doesn't put excess newlines after subpackets.
1 parent 0b6e28e commit d1e461e

File tree

2 files changed

+14
-16
lines changed

2 files changed

+14
-16
lines changed

src/lib.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -121,23 +121,21 @@ pub enum Val {
121121
}
122122

123123
impl Val {
124-
pub fn pretty_print(self, indent:usize) -> String {
124+
pub fn pretty_print(self, indent_level:usize) -> String {
125125
match self {
126126
Val::Subpacket(values) => {
127-
let mut s = "\n".to_string();
128-
let prefix =
129-
::std::iter::repeat(" ").take(2 * indent).collect::<String>();
130-
131-
for (k, v) in values {
132-
s = s + &format!["{}{}: ", prefix, k];
133-
s = s + &*(match v {
134-
Ok(value) => value.pretty_print(indent + 1),
135-
Err(e) => format!["<< Error: {} >>", e],
136-
});
137-
s = s + "\n";
138-
};
139-
140-
s
127+
let indent:String = std::iter::repeat(" ").take(2 * indent_level).collect();
128+
129+
"\n".to_string() + &values.into_iter()
130+
.map(|(k,v)| {
131+
format!["{}{}: ", indent, k]
132+
+ &match v {
133+
Ok(val) => val.pretty_print(indent_level + 1),
134+
Err(e) => format!["<< Error: {} >>", e],
135+
}
136+
})
137+
.collect::<Vec<String>>()
138+
.join("\n")
141139
}
142140

143141
Val::Signed(i) => format!["{}", i],

src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ fn main() {
6464
let mut count = 0;
6565

6666
while let Ok(packet) = c.next() {
67-
println!("{}-B packet:", packet.data.len());
67+
println!("\n\n{}-B packet:", packet.data.len());
6868

6969
match protocol.dissect(packet.data) {
7070
Ok(dissected) => print!["{}", dissected.pretty_print(1)],

0 commit comments

Comments
 (0)