Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encode to Vec<u8> #378

Merged
merged 3 commits into from Jul 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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