From e2ed6f586865c1619c186e4493b2b0092be952e0 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Wed, 7 Jun 2017 17:48:26 -0700 Subject: [PATCH] refactor(chunk): make use of Bytes::extend instead of custom code --- Cargo.toml | 2 +- src/http/chunk.rs | 48 +++++++++-------------------------------------- 2 files changed, 10 insertions(+), 40 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 74f206c2..c9f142f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ include = [ [dependencies] base64 = "0.5" -bytes = "0.4" +bytes = "0.4.4" futures = "0.1.11" futures-cpupool = "0.1" httparse = "1.0" diff --git a/src/http/chunk.rs b/src/http/chunk.rs index bd404b07..24caf796 100644 --- a/src/http/chunk.rs +++ b/src/http/chunk.rs @@ -1,41 +1,13 @@ use std::fmt; -use std::mem; +//use std::mem; -use bytes::{Bytes, BytesMut, BufMut}; +use bytes::Bytes; /// A piece of a message body. pub struct Chunk(Inner); enum Inner { - Mut(BytesMut), Shared(Bytes), - Swapping, -} - -impl Inner { - fn as_bytes_mut(&mut self, reserve: usize) -> &mut BytesMut { - match *self { - Inner::Mut(ref mut bytes) => return bytes, - _ => () - } - - let bytes = match mem::replace(self, Inner::Swapping) { - Inner::Shared(bytes) => bytes, - _ => unreachable!(), - }; - - let bytes_mut = bytes.try_mut().unwrap_or_else(|bytes| { - let mut bytes_mut = BytesMut::with_capacity(reserve + bytes.len()); - bytes_mut.put_slice(bytes.as_ref()); - bytes_mut - }); - - *self = Inner::Mut(bytes_mut); - match *self { - Inner::Mut(ref mut bytes) => bytes, - _ => unreachable!(), - } - } } impl From> for Chunk { @@ -67,17 +39,17 @@ impl From<&'static str> for Chunk { } impl From for Chunk { + #[inline] fn from(mem: Bytes) -> Chunk { Chunk(Inner::Shared(mem)) } } impl From for Bytes { + #[inline] fn from(chunk: Chunk) -> Bytes { match chunk.0 { - Inner::Mut(bytes_mut) => bytes_mut.freeze(), Inner::Shared(bytes) => bytes, - Inner::Swapping => unreachable!(), } } } @@ -95,9 +67,7 @@ impl AsRef<[u8]> for Chunk { #[inline] fn as_ref(&self) -> &[u8] { match self.0 { - Inner::Mut(ref slice) => slice, Inner::Shared(ref slice) => slice, - Inner::Swapping => unreachable!(), } } } @@ -120,19 +90,19 @@ impl IntoIterator for Chunk { type Item = u8; type IntoIter = ::IntoIter; + #[inline] fn into_iter(self) -> Self::IntoIter { match self.0 { - Inner::Mut(bytes) => bytes.freeze().into_iter(), Inner::Shared(bytes) => bytes.into_iter(), - Inner::Swapping => unreachable!(), } } } impl Extend for Chunk { + #[inline] fn extend(&mut self, iter: T) where T: IntoIterator { - let iter = iter.into_iter(); - - self.0.as_bytes_mut(iter.size_hint().0).extend(iter); + match self.0 { + Inner::Shared(ref mut bytes) => bytes.extend(iter) + } } }