buf: implement FromBufStream for Bytes (#1009)

This commit is contained in:
Carl Lerche
2019-03-27 19:22:06 -07:00
committed by GitHub
parent d8177f81ac
commit 03859a7dcd
3 changed files with 79 additions and 44 deletions
+27 -3
View File
@@ -1,6 +1,6 @@
use SizeHint;
use bytes::{Buf, BufMut};
use bytes::{Buf, BufMut, Bytes};
use std::usize;
@@ -47,12 +47,18 @@ pub struct CollectVecError {
_p: (),
}
/// Error returned from collecting into a `Bytes`
#[derive(Debug)]
pub struct CollectBytesError {
_p: (),
}
impl<T: Buf> FromBufStream<T> for Vec<u8> {
type Builder = Vec<u8>;
type Error = CollectVecError;
fn builder(_hint: &SizeHint) -> Vec<u8> {
Vec::new()
fn builder(hint: &SizeHint) -> Vec<u8> {
Vec::with_capacity(hint.lower() as usize)
}
fn extend(builder: &mut Self, buf: &mut T, hint: &SizeHint) -> Result<(), Self::Error> {
@@ -110,3 +116,21 @@ impl<T: Buf> FromBufStream<T> for Vec<u8> {
Ok(builder)
}
}
impl<T: Buf> FromBufStream<T> for Bytes {
type Builder = Vec<u8>;
type Error = CollectBytesError;
fn builder(hint: &SizeHint) -> Vec<u8> {
<Vec<u8> as FromBufStream<T>>::builder(hint)
}
fn extend(builder: &mut Vec<u8>, buf: &mut T, hint: &SizeHint) -> Result<(), Self::Error> {
<Vec<u8> as FromBufStream<T>>::extend(builder, buf, hint)
.map_err(|_| CollectBytesError { _p: () })
}
fn build(builder: Vec<u8>) -> Result<Self, Self::Error> {
Ok(builder.into())
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ pub mod error {
//! Error types
pub use super::collect::CollectError;
pub use super::from::CollectVecError;
pub use super::from::{CollectBytesError, CollectVecError};
pub use super::limit::LimitError;
}