Skip to content

Commit

Permalink
der: add Any::encode_from (#976)
Browse files Browse the repository at this point in the history
Support for encoding an `Any` value from any type which impls `Tagged` +
`EncodeValue`.
  • Loading branch information
tarcieri authored Apr 4, 2023
1 parent 5e9b577 commit 94cc741
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions der/src/asn1/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ use crate::{
};
use core::cmp::Ordering;

#[cfg(feature = "alloc")]
use crate::SliceWriter;

/// ASN.1 `ANY`: represents any explicitly tagged ASN.1 value.
///
/// This is a zero-copy reference type which borrows from the input data.
Expand Down Expand Up @@ -193,6 +196,19 @@ mod allocating {
AnyRef::from(self).decode_as()
}

/// Encode the provided type as an [`Any`] value.
pub fn encode_from<T>(msg: &T) -> Result<Self>
where
T: Tagged + EncodeValue,
{
let encoded_len = usize::try_from(msg.value_len()?)?;
let mut buf = vec![0u8; encoded_len];
let mut writer = SliceWriter::new(&mut buf);
msg.encode_value(&mut writer)?;
writer.finish()?;
Any::new(msg.tag(), buf)
}

/// Attempt to decode this value an ASN.1 `SEQUENCE`, creating a new
/// nested reader and calling the provided argument with it.
pub fn sequence<'a, F, T>(&'a self, f: F) -> Result<T>
Expand Down

0 comments on commit 94cc741

Please sign in to comment.