Add IntoBuf trait

This commit is contained in:
Carl Lerche
2016-09-25 22:40:39 -07:00
parent b10992a5e8
commit 4ca7e0fabf
4 changed files with 67 additions and 2 deletions
+17
View File
@@ -0,0 +1,17 @@
extern crate bytes;
use bytes::{Buf, IntoBuf, Bytes};
pub fn dump<T>(data: &T) where
for<'a> &'a T: IntoBuf,
{
let mut dst: Vec<u8> = vec![];
data.into_buf().copy_to(&mut dst);
println!("GOT: {:?}", dst);
}
pub fn main() {
let b = Bytes::from_slice(b"hello world");
dump(&b);
dump(&b);
}
+34
View File
@@ -363,6 +363,40 @@ pub trait MutBuf {
}
}
/*
*
* ===== IntoBuf =====
*
*/
/// Conversion into a `Buf`
///
/// Usually, `IntoBuf` is implemented on references of types and not directly
/// on the types themselves. For example, `IntoBuf` is implemented for `&'a
/// Vec<u8>` and not `Vec<u8>` directly.
pub trait IntoBuf {
type Buf: Buf;
fn into_buf(self) -> Self::Buf;
}
impl<'a> IntoBuf for &'a [u8] {
type Buf = io::Cursor<&'a [u8]>;
/// Creates a buffer from a value
fn into_buf(self) -> Self::Buf {
io::Cursor::new(self)
}
}
impl<'a> IntoBuf for &'a Vec<u8> {
type Buf = io::Cursor<&'a [u8]>;
fn into_buf(self) -> Self::Buf {
io::Cursor::new(&self[..])
}
}
/*
*
* ===== Sink / Source =====
+15 -1
View File
@@ -2,7 +2,7 @@ pub mod rope;
pub mod seq;
pub mod small;
use Buf;
use {Buf, IntoBuf};
use self::seq::Seq;
use self::small::Small;
use self::rope::{Rope, RopeBuf};
@@ -188,6 +188,20 @@ impl cmp::PartialEq<Bytes> for Bytes {
}
}
impl<'a> IntoBuf for &'a Bytes {
type Buf = BytesBuf<'a>;
fn into_buf(self) -> Self::Buf {
self.buf()
}
}
/*
*
* ===== BytesBuf =====
*
*/
impl<'a> Buf for BytesBuf<'a> {
fn remaining(&self) -> usize {
match self.kind {
+1 -1
View File
@@ -10,7 +10,7 @@ mod imp;
// TODO: delete
mod alloc;
pub use imp::buf::{Buf, MutBuf};
pub use imp::buf::{Buf, MutBuf, IntoBuf};
pub use imp::bytes::Bytes;
pub mod buf {