Implement Debug for Bytes

This commit is contained in:
Carl Lerche
2015-02-17 12:40:15 -08:00
parent e39ba25a95
commit 7444721d98
4 changed files with 90 additions and 1 deletions
+7 -1
View File
@@ -1,5 +1,5 @@
use {Buf, ByteStr, ByteBuf, SmallByteStr};
use std::{mem, ops, ptr};
use std::{fmt, mem, ops, ptr};
use std::any::{Any, TypeId};
use std::raw::TraitObject;
use core::nonzero::NonZero;
@@ -165,6 +165,12 @@ impl ops::Index<usize> for Bytes {
}
}
impl fmt::Debug for Bytes {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
super::debug(self, "Bytes", fmt)
}
}
impl Clone for Bytes {
fn clone(&self) -> Bytes {
self.obj().clone()
+40
View File
@@ -455,3 +455,43 @@ pub enum BufError {
Underflow,
Overflow,
}
/*
*
* ===== Internal utilities =====
*
*/
fn debug<B: ByteStr>(bytes: &B, name: &str, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut buf = bytes.buf();
try!(write!(fmt, "{}[len={}; ", name, bytes.len()));
let mut rem = 128;
while let Some(byte) = buf.read_byte() {
if rem > 0 {
if is_ascii(byte) {
try!(write!(fmt, "{}", byte as char));
} else {
try!(write!(fmt, "\\x{:02X}", byte));
}
rem -= 1;
} else {
try!(write!(fmt, " ... "));
break;
}
}
try!(write!(fmt, "]"));
Ok(())
}
fn is_ascii(byte: u8) -> bool {
match byte {
10 | 13 | 32...126 => true,
_ => false,
}
}