From 23ad12f842cd2532b685e903922bd74a8745598d Mon Sep 17 00:00:00 2001 From: Paul Cavallaro <paulcavallaro@gmail.com> Date: Fri, 17 Jul 2015 22:22:58 -0400 Subject: [PATCH] Add bytes() method to MutByteBuf to allow reading of data already written without necessitating flipping to ByteBuf. --- src/buf/byte.rs | 4 ++++ test/test_byte_buf.rs | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/buf/byte.rs b/src/buf/byte.rs index aae272c..1e187dd 100644 --- a/src/buf/byte.rs +++ b/src/buf/byte.rs @@ -303,6 +303,10 @@ impl MutByteBuf { len as usize } } + + pub fn bytes<'a>(&'a self) -> &'a [u8] { + &self.buf.mem.bytes()[..self.buf.pos()] + } } impl MutBuf for MutByteBuf { diff --git a/test/test_byte_buf.rs b/test/test_byte_buf.rs index 576bb0b..a0e6937 100644 --- a/test/test_byte_buf.rs +++ b/test/test_byte_buf.rs @@ -17,6 +17,18 @@ pub fn test_initial_buf_empty() { assert!(buf.remaining() == 128); } +#[test] +pub fn test_byte_buf_bytes() { + let mut buf = ByteBuf::mut_with_capacity(32); + buf.write(&b"hello "[..]).unwrap(); + assert_eq!(&b"hello "[..], buf.bytes()); + + buf.write(&b"world"[..]).unwrap(); + assert_eq!(&b"hello world"[..], buf.bytes()); + let buf = buf.flip(); + assert_eq!(&b"hello world"[..], buf.bytes()); +} + #[test] pub fn test_byte_buf_read_write() { let mut buf = ByteBuf::mut_with_capacity(32); -- GitLab