Skip to content

Commit

Permalink
Add encode to Vec<u8> (#378)
Browse files Browse the repository at this point in the history
* Message::{encode_to_vec,encode_length_delimited_to_vec}

* test for Message::encode_to_vec

Co-authored-by: Lucio Franco <luciofranco14@gmail.com>
  • Loading branch information
rubdos and LucioFranco committed Jul 6, 2021
1 parent 59f2a73 commit d8cb390
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/message.rs
Expand Up @@ -59,6 +59,18 @@ pub trait Message: Debug + Send + Sync {
Ok(())
}

#[cfg(feature = "std")]
/// Encodes the message to a newly allocated buffer.
fn encode_to_vec(&self) -> Vec<u8>
where
Self: Sized,
{
let mut buf = Vec::with_capacity(self.encoded_len());

self.encode_raw(&mut buf);
buf
}

/// Encodes the message with a length-delimiter to a buffer.
///
/// An error will be returned if the buffer does not have sufficient capacity.
Expand All @@ -78,6 +90,20 @@ pub trait Message: Debug + Send + Sync {
Ok(())
}

#[cfg(feature = "std")]
/// Encodes the message with a length-delimiter to a newly allocated buffer.
fn encode_length_delimited_to_vec(&self) -> Vec<u8>
where
Self: Sized,
{
let len = self.encoded_len();
let mut buf = Vec::with_capacity(len + encoded_len_varint(len as u64));

encode_varint(len as u64, &mut buf);
self.encode_raw(&mut buf);
buf
}

/// Decodes an instance of the message from a buffer.
///
/// The entire buffer will be consumed.
Expand Down
7 changes: 7 additions & 0 deletions tests/src/lib.rs
Expand Up @@ -180,6 +180,7 @@ where
if let Err(error) = roundtrip.encode(&mut buf2) {
return RoundtripResult::Error(error.into());
}
let buf3 = roundtrip.encode_to_vec();

/*
// Useful for debugging:
Expand All @@ -192,6 +193,12 @@ where
return RoundtripResult::Error(anyhow!("roundtripped encoded buffers do not match"));
}

if buf1 != buf3 {
return RoundtripResult::Error(anyhow!(
"roundtripped encoded buffers do not match with `encode_to_vec`"
));
}

RoundtripResult::Ok(buf1)
}

Expand Down

0 comments on commit d8cb390

Please sign in to comment.