Implement FromBuf and Buf::collect

Enables collecting the contents of a `Buf` value into a relevant
concrete buffer implementation.
This commit is contained in:
Carl Lerche
2017-03-01 09:30:13 -08:00
parent fd8f716e68
commit 4f8c565111
4 changed files with 178 additions and 1 deletions
+25 -1
View File
@@ -1,4 +1,4 @@
use super::{Take, Reader};
use super::{Take, Reader, FromBuf};
use byteorder::ByteOrder;
use std::{cmp, ptr};
@@ -441,6 +441,30 @@ pub trait Buf {
T::read_f64(&buf)
}
/// Transforms a `Buf` into a concrete buffer.
///
/// `collect()` can operate on any value that implements `Buf`, and turn it
/// into the relevent concrete buffer type.
///
/// # Examples
///
/// Collecting a buffer and loading the contents into a `Vec<u8>`.
///
/// ```
/// use bytes::{Buf, Bytes, IntoBuf};
///
/// let buf = Bytes::from(&b"hello world"[..]).into_buf();
/// let vec: Vec<u8> = buf.collect();
///
/// assert_eq!(vec, &b"hello world"[..]);
/// ```
fn collect<B>(self) -> B
where Self: Sized,
B: FromBuf,
{
B::from_buf(self)
}
/// Creates an adaptor which will read at most `limit` bytes from `self`.
///
/// This function returns a new instance of `Buf` which will read at most