Skip to content
Snippets Groups Projects
Commit 4ca7e0fa authored by Carl Lerche's avatar Carl Lerche
Browse files

Add IntoBuf trait

parent b10992a5
No related branches found
No related tags found
No related merge requests found
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);
}
......@@ -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 =====
......
......@@ -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 {
......
......@@ -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 {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment