Skip to content

Commit

Permalink
ssh-encoding: add Encode::{encode_vec, encode_bytes} (#267)
Browse files Browse the repository at this point in the history
Adds convenience methods for producing a `Vec<u8>` or `BytesMut` from
any type which impls `Encode`.
  • Loading branch information
tarcieri authored Aug 13, 2024
1 parent 98d6448 commit e0d423b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
18 changes: 17 additions & 1 deletion ssh-encoding/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use core::str;
use alloc::{string::String, vec::Vec};

#[cfg(feature = "bytes")]
use bytes::Bytes;
use bytes::{Bytes, BytesMut};

/// Encoding trait.
///
Expand All @@ -34,6 +34,22 @@ pub trait Encode {
self.encoded_len()?.encode(writer)?;
self.encode(writer)
}

/// Encode this value, returning a `Vec<u8>` containing the encoded message.
#[cfg(feature = "alloc")]
fn encode_vec(&self) -> Result<Vec<u8>, Error> {
let mut ret = Vec::with_capacity(self.encoded_len()?);
self.encode(&mut ret)?;
Ok(ret)
}

/// Encode this value, returning a [`BytesMut`] containing the encoded message.
#[cfg(feature = "bytes")]
fn encode_bytes(&self) -> Result<BytesMut, Error> {
let mut ret = BytesMut::with_capacity(self.encoded_len()?);
self.encode(&mut ret)?;
Ok(ret)
}
}

/// Encode a single `byte` to the writer.
Expand Down
3 changes: 3 additions & 0 deletions ssh-encoding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,8 @@ pub use crate::{
#[cfg(feature = "base64")]
pub use crate::{base64::Base64Reader, base64::Base64Writer};

#[cfg(feature = "bytes")]
pub use bytes;

#[cfg(feature = "pem")]
pub use crate::pem::{DecodePem, EncodePem};
11 changes: 11 additions & 0 deletions ssh-encoding/src/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ use crate::Result;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "bytes")]
use bytes::{BufMut, BytesMut};

#[cfg(feature = "sha2")]
use sha2::{Digest, Sha256, Sha512};

Expand All @@ -23,6 +26,14 @@ impl Writer for Vec<u8> {
}
}

#[cfg(feature = "bytes")]
impl Writer for BytesMut {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
self.put(bytes);
Ok(())
}
}

#[cfg(feature = "sha2")]
impl Writer for Sha256 {
fn write(&mut self, bytes: &[u8]) -> Result<()> {
Expand Down

0 comments on commit e0d423b

Please sign in to comment.