Skip to content

Commit 94cc741

Browse files
authored
der: add Any::encode_from (#976)
Support for encoding an `Any` value from any type which impls `Tagged` + `EncodeValue`.
1 parent 5e9b577 commit 94cc741

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

der/src/asn1/any.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ use crate::{
88
};
99
use core::cmp::Ordering;
1010

11+
#[cfg(feature = "alloc")]
12+
use crate::SliceWriter;
13+
1114
/// ASN.1 `ANY`: represents any explicitly tagged ASN.1 value.
1215
///
1316
/// This is a zero-copy reference type which borrows from the input data.
@@ -193,6 +196,19 @@ mod allocating {
193196
AnyRef::from(self).decode_as()
194197
}
195198

199+
/// Encode the provided type as an [`Any`] value.
200+
pub fn encode_from<T>(msg: &T) -> Result<Self>
201+
where
202+
T: Tagged + EncodeValue,
203+
{
204+
let encoded_len = usize::try_from(msg.value_len()?)?;
205+
let mut buf = vec![0u8; encoded_len];
206+
let mut writer = SliceWriter::new(&mut buf);
207+
msg.encode_value(&mut writer)?;
208+
writer.finish()?;
209+
Any::new(msg.tag(), buf)
210+
}
211+
196212
/// Attempt to decode this value an ASN.1 `SEQUENCE`, creating a new
197213
/// nested reader and calling the provided argument with it.
198214
pub fn sequence<'a, F, T>(&'a self, f: F) -> Result<T>

0 commit comments

Comments
 (0)