bencode: implement debug on the inner structs

This commit is contained in:
2016-12-12 00:55:26 -05:00
parent 72d4dfc0b8
commit 2e9503d2d7

View File

@@ -59,30 +59,14 @@ impl fmt::Debug for Object {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Object::Int(num) => write!(f, "{}", num), Object::Int(num) => write!(f, "{}", num),
Object::Bytes(ref bytes) => { Object::Bytes(ref bytes) => bytes.fmt(f),
match str::from_utf8(bytes) { Object::List(ref list) => list.fmt(f),
Ok(s) => write!(f, "{}", s), Object::Dict(ref dict) => dict.fmt(f),
Err(_) => {
for &b in bytes.iter() {
write!(f, "{:X}", b)?;
}
Ok(())
}
}
}
Object::List(ref list) => {
f.debug_list().entries(list.iter()).finish()
}
Object::Dict(ref dict) => {
f.debug_map()
.entries(dict.iter().map(|(k, v)| (k.clone(), v)))
.finish()
}
} }
} }
} }
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] #[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Bytes(Vec<u8>); pub struct Bytes(Vec<u8>);
impl Bytes { impl Bytes {
@@ -113,7 +97,23 @@ impl DerefMut for Bytes {
} }
} }
#[derive(Clone, Debug, Eq, PartialEq)] impl fmt::Debug for Bytes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match str::from_utf8(&self.0) {
Ok(s) => write!(f, "\"{}\"", s),
Err(_) => {
write!(f, "\"")?;
for &b in self.0.iter() {
write!(f, "{:x}", b)?;
}
write!(f, "\"")?;
Ok(())
}
}
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct List(Vec<Object>); pub struct List(Vec<Object>);
impl List { impl List {
@@ -140,7 +140,13 @@ impl DerefMut for List {
} }
} }
#[derive(Clone, Debug, Eq, PartialEq)] impl fmt::Debug for List {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Dict(BTreeMap<Bytes, Object>); pub struct Dict(BTreeMap<Bytes, Object>);
impl Dict { impl Dict {
@@ -195,6 +201,14 @@ impl DerefMut for Dict {
} }
} }
impl fmt::Debug for Dict {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_map()
.entries(self.iter())
.finish()
}
}
// convertion utilities // convertion utilities
// int // int