diff --git a/multistream-select/src/protocol/listener.rs b/multistream-select/src/protocol/listener.rs index d2bfd59d..89a0c501 100644 --- a/multistream-select/src/protocol/listener.rs +++ b/multistream-select/src/protocol/listener.rs @@ -113,11 +113,13 @@ impl Sink for Listener } ListenerToDialerMessage::ProtocolsListResponse { list } => { + use std::iter; + let mut out_msg = varint::encode(list.len()); for elem in list.iter() { - out_msg.push(b'\r'); + out_msg.extend(iter::once(b'\r')); out_msg.extend_from_slice(elem); - out_msg.push(b'\n'); + out_msg.extend(iter::once(b'\n')); } match self.inner.start_send(BytesMut::from(out_msg)) { diff --git a/varint-rs/src/lib.rs b/varint-rs/src/lib.rs index ed508bb0..2166930a 100644 --- a/varint-rs/src/lib.rs +++ b/varint-rs/src/lib.rs @@ -31,7 +31,7 @@ extern crate futures; #[macro_use] extern crate error_chain; -use bytes::{BufMut, BytesMut, IntoBuf}; +use bytes::{BufMut, Bytes, BytesMut, IntoBuf}; use futures::{Poll, Async}; use num_bigint::BigUint; use num_traits::ToPrimitive; @@ -421,7 +421,7 @@ impl Default for VarintCodec { enum VarintCodecInner { WaitingForLen(VarintDecoder), WaitingForData(usize), - Poisonned, + Poisoned, } impl Decoder for VarintCodec { @@ -430,7 +430,7 @@ impl Decoder for VarintCodec { fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { loop { - match mem::replace(&mut self.inner, VarintCodecInner::Poisonned) { + match mem::replace(&mut self.inner, VarintCodecInner::Poisoned) { VarintCodecInner::WaitingForData(len) => { if src.len() >= len { self.inner = VarintCodecInner::WaitingForLen(VarintDecoder::default()); @@ -451,9 +451,7 @@ impl Decoder for VarintCodec { }, } }, - VarintCodecInner::Poisonned => { - panic!("varint codec was poisoned") - }, + VarintCodecInner::Poisoned => panic!("varint codec was poisoned"), } } } @@ -466,7 +464,7 @@ impl Encoder for VarintCodec type Error = io::Error; fn encode(&mut self, item: D, dst: &mut BytesMut) -> Result<(), io::Error> { - let encoded_len = encode(item.as_ref().len()); // TODO: can be optimized by not allocating? + let encoded_len = encode(item.as_ref().len()); dst.put(encoded_len); dst.put(item); Ok(()) @@ -495,12 +493,14 @@ pub fn decode(mut input: R) -> errors::Resu } /// Syncronously decode a number from a `Read` -pub fn encode(input: T) -> Vec { +pub fn encode(input: T) -> Bytes { + use tokio_io::io::AllowStdIo; + let mut encoder = EncoderState::new(input); - let mut out = io::Cursor::new(Vec::with_capacity(1)); + let mut out = AllowStdIo::new(BytesMut::new().writer()); match T::write(&mut encoder, &mut out).expect("Writing to a vec should never fail, Q.E.D") { - Async::Ready(_) => out.into_inner(), + Async::Ready(_) => out.into_inner().into_inner().freeze(), Async::NotReady => unreachable!(), } }