From 87fd190378a3eb2089c42c461650cb68d1577a28 Mon Sep 17 00:00:00 2001 From: Milo Turner Date: Mon, 9 Mar 2020 14:28:34 -0400 Subject: [PATCH] don't create intermediate Vec's while serializing messages --- hptp/src/msg.rs | 24 +++++++++++++++--------- hptp/src/peer.rs | 7 ++++--- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/hptp/src/msg.rs b/hptp/src/msg.rs index f6f2951..b18f326 100644 --- a/hptp/src/msg.rs +++ b/hptp/src/msg.rs @@ -17,7 +17,9 @@ pub struct DesError; pub trait SerDes: Sized { fn des(data: &[u8]) -> Result; - fn ser_into(self) -> Vec; + + // `buf.len()` must be >= `MAX_SERIALIZED_SIZE` + fn ser_to(&self, buf: &mut [u8]) -> usize; } impl SerDes for UpMsg { @@ -25,23 +27,27 @@ impl SerDes for UpMsg { Ok(UpMsg::Data(data.into())) } - fn ser_into(self) -> Vec { + fn ser_to(&self, buf: &mut [u8]) -> usize { match self { - UpMsg::Data(data) => data, + UpMsg::Data(data) => { + let len = data.len(); + buf[..len].copy_from_slice(&data[..]); + len + } } } } impl SerDes for DownMsg { fn des(data: &[u8]) -> Result { - if data == [0] { - Ok(DownMsg::Ack) - } else { - Err(DesError) + match data.first() { + Some(0) => Ok(DownMsg::Ack), + _ => Err(DesError), } } - fn ser_into(self) -> Vec { - vec![0] + fn ser_to(&self, buf: &mut [u8]) -> usize { + buf[0] = 0; + 1 } } diff --git a/hptp/src/peer.rs b/hptp/src/peer.rs index 47a5353..58d0af4 100644 --- a/hptp/src/peer.rs +++ b/hptp/src/peer.rs @@ -55,9 +55,10 @@ impl Peer { where F: SerDes, { - let targ = self.targ.ok_or(SendError::NoTarget)?; - let data = msg.ser_into(); - let _n_sent = self.sock.send_to(&data, targ).await?; + let mut buf = [0u8; msg::MAX_SERIALIZED_SIZE]; + let len = msg.ser_to(&mut buf); + let who = self.targ.ok_or(SendError::NoTarget)?; + let _n_sent = self.sock.send_to(&buf[..len], who).await?; Ok(()) }