From b9e182a2ceaf798f8af4004a3030512a187fe4d8 Mon Sep 17 00:00:00 2001 From: Manuel Woelker Date: Sun, 22 Jan 2017 21:10:48 +0100 Subject: [PATCH] impl fmt::Debug for EasyBuf (cf. #120) Debug format looks like this for small resp. long buffers EasyBuf{len=2/6 [5, 6]} EasyBuf{len=255/255 [0, 1, 2, 3, ..., 251, 252, 253, 254]} --- src/io/frame.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/io/frame.rs b/src/io/frame.rs index 11eed10e1..f34e6917a 100644 --- a/src/io/frame.rs +++ b/src/io/frame.rs @@ -1,3 +1,4 @@ +use std::fmt; use std::io; use std::ops::{Deref, DerefMut}; use std::sync::Arc; @@ -195,6 +196,18 @@ impl<'a> Drop for EasyBufMut<'a> { } } +impl fmt::Debug for EasyBuf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let bytes = self.as_ref(); + let len = self.len(); + if len < 10 { + write!(formatter, "EasyBuf{{len={}/{} {:?}}}", self.len(), self.buf.len(), bytes) + } else { // choose a more compact representation + write!(formatter, "EasyBuf{{len={}/{} [{}, {}, {}, {}, ..., {}, {}, {}, {}]}}", self.len(), self.buf.len(), bytes[0], bytes[1], bytes[2], bytes[3], bytes[len-4], bytes[len-3], bytes[len-2], bytes[len-1]) + } + } +} + /// Encoding and decoding of frames via buffers. /// /// This trait is used when constructing an instance of `Framed`. It provides @@ -397,3 +410,36 @@ impl Framed { self.upstream } } + +#[cfg(test)] +mod tests { + use super::EasyBuf; + + #[test] + fn debug_empty_easybuf() { + let buf: EasyBuf = vec![].into(); + assert_eq!("EasyBuf{len=0/0 []}", format!("{:?}", buf)); + } + + #[test] + fn debug_small_easybuf() { + let buf: EasyBuf = vec![1, 2, 3, 4, 5, 6].into(); + assert_eq!("EasyBuf{len=6/6 [1, 2, 3, 4, 5, 6]}", format!("{:?}", buf)); + } + + #[test] + fn debug_small_easybuf_split() { + let mut buf: EasyBuf = vec![1, 2, 3, 4, 5, 6].into(); + let split = buf.split_off(4); + assert_eq!("EasyBuf{len=4/6 [1, 2, 3, 4]}", format!("{:?}", buf)); + assert_eq!("EasyBuf{len=2/6 [5, 6]}", format!("{:?}", split)); + } + + #[test] + fn debug_large_easybuf() { + let vec: Vec = (0u8..255u8).collect(); + let buf: EasyBuf = vec.into(); + assert_eq!("EasyBuf{len=255/255 [0, 1, 2, 3, ..., 251, 252, 253, 254]}", format!("{:?}", buf)); + } + +}