pub trait FromDer<'a, E = Error>: Sized {
fn from_der(bytes: &'a [u8]) -> ParseResult<'_, Self, E>;
}
Expand description
Base trait for DER object parsers
Library authors should usually not directly implement this trait, but should prefer implementing the
TryFrom<Any>
+ CheckDerConstraints
traits,
which offers greater flexibility and provides an equivalent FromDer
implementation for free
(in fact, it provides both FromBer
and FromDer
).
Note: if you already implemented TryFrom<Any>
and CheckDerConstraints
,
you can get a free FromDer
implementation by implementing the
DerAutoDerive
trait. This is not automatic, so it is also possible to manually
implement FromDer
if preferred.
Examples
use asn1_rs::{Any, CheckDerConstraints, DerAutoDerive, Result, Tag};
use std::convert::TryFrom;
// The type to be decoded
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MyType(pub u32);
impl<'a> TryFrom<Any<'a>> for MyType {
type Error = asn1_rs::Error;
fn try_from(any: Any<'a>) -> Result<MyType> {
any.tag().assert_eq(Tag::Integer)?;
// for this fictive example, the type contains the number of characters
let n = any.data.len() as u32;
Ok(MyType(n))
}
}
impl CheckDerConstraints for MyType {
fn check_constraints(any: &Any) -> Result<()> {
any.header.assert_primitive()?;
Ok(())
}
}
impl DerAutoDerive for MyType {}
// The above code provides a `FromDer` implementation for free.
// Example of parsing code:
use asn1_rs::FromDer;
let input = &[2, 1, 2];
// Objects can be parsed using `from_der`, which returns the remaining bytes
// and the parsed object:
let (rem, my_type) = MyType::from_der(input).expect("parsing failed");
Required Methods
fn from_der(bytes: &'a [u8]) -> ParseResult<'_, Self, E>
fn from_der(bytes: &'a [u8]) -> ParseResult<'_, Self, E>
Attempt to parse input bytes into a DER object (enforcing constraints)
Implementations on Foreign Types
sourceimpl<'a, T> FromDer<'a, Error> for Option<T> where
T: FromDer<'a>,
impl<'a, T> FromDer<'a, Error> for Option<T> where
T: FromDer<'a>,
fn from_der(bytes: &'a [u8]) -> ParseResult<'_, Self>
sourceimpl<'a, T, E> FromDer<'a, E> for Vec<T> where
T: FromDer<'a, E>,
E: From<Error>,
impl<'a, T, E> FromDer<'a, E> for Vec<T> where
T: FromDer<'a, E>,
E: From<Error>,
manual impl of FromDer, so we do not need to require TryFrom
fn from_der(bytes: &'a [u8]) -> ParseResult<'_, Self, E>
sourceimpl<'a, T, E> FromDer<'a, E> for BTreeSet<T> where
T: FromDer<'a, E>,
T: Ord,
E: From<Error>,
impl<'a, T, E> FromDer<'a, E> for BTreeSet<T> where
T: FromDer<'a, E>,
T: Ord,
E: From<Error>,
manual impl of FromDer, so we do not need to require TryFrom
fn from_der(bytes: &'a [u8]) -> ParseResult<'a, Self, E>
sourceimpl<'a, T, E> FromDer<'a, E> for HashSet<T> where
T: FromDer<'a, E>,
T: Hash + Eq,
E: From<Error>,
impl<'a, T, E> FromDer<'a, E> for HashSet<T> where
T: FromDer<'a, E>,
T: Hash + Eq,
E: From<Error>,
manual impl of FromDer, so we do not need to require TryFrom