Skip to main content

rasn/
der.rs

1//! # Distinguished Encoding Rules
2
3pub use crate::ber::*;
4
5/// Attempts to decode `T` from `input` using DER.
6pub fn decode<T: crate::Decode>(input: &[u8]) -> Result<T, crate::error::DecodeError> {
7    T::decode(&mut crate::ber::de::Decoder::new(
8        input,
9        crate::ber::de::DecoderOptions::der(),
10    ))
11}
12/// Attempts to decode `T` from `input` using DER. Returns both `T` and reference to the remainder of the input.
13///
14/// # Errors
15/// Returns `DecodeError` if `input` is not valid DER encoding specific to the expected type.
16pub fn decode_with_remainder<T: crate::Decode>(
17    input: &[u8],
18) -> Result<(T, &[u8]), crate::error::DecodeError> {
19    let decoder = &mut de::Decoder::new(input, de::DecoderOptions::der());
20    let decoded_instance = T::decode(decoder)?;
21    Ok((decoded_instance, decoder.remaining()))
22}
23
24/// Attempts to encode `value` to DER.
25pub fn encode<T: crate::Encode>(
26    value: &T,
27) -> Result<alloc::vec::Vec<u8>, crate::error::EncodeError> {
28    let mut enc = crate::ber::enc::Encoder::new(crate::ber::enc::EncoderOptions::der());
29
30    value.encode(&mut enc)?;
31
32    Ok(enc.output())
33}
34
35/// Creates a new DER encoder that can be used to encode any value.
36pub fn encode_scope(
37    encode_fn: impl FnOnce(&mut crate::ber::enc::Encoder) -> Result<(), crate::error::EncodeError>,
38) -> Result<alloc::vec::Vec<u8>, crate::error::EncodeError> {
39    let mut enc = crate::ber::enc::Encoder::new(crate::ber::enc::EncoderOptions::der());
40
41    (encode_fn)(&mut enc)?;
42
43    Ok(enc.output())
44}