der/
decodable.rs

1//! Trait definition for [`Decodable`].
2
3use crate::{DecodeValue, Decoder, FixedTag, Header, Result};
4
5/// Decoding trait.
6///
7/// This trait provides the core abstraction upon which all decoding operations
8/// are based.
9///
10/// # Blanket impl for `TryFrom<Any>`
11///
12/// In almost all cases you do not need to impl this trait yourself, but rather
13/// can instead impl `TryFrom<Any<'a>, Error = Error>` and receive a blanket
14/// impl of this trait.
15pub trait Decodable<'a>: Sized {
16    /// Attempt to decode this message using the provided decoder.
17    fn decode(decoder: &mut Decoder<'a>) -> Result<Self>;
18
19    /// Parse `Self` from the provided DER-encoded byte slice.
20    fn from_der(bytes: &'a [u8]) -> Result<Self> {
21        let mut decoder = Decoder::new(bytes)?;
22        let result = Self::decode(&mut decoder)?;
23        decoder.finish(result)
24    }
25}
26
27impl<'a, T> Decodable<'a> for T
28where
29    T: DecodeValue<'a> + FixedTag,
30{
31    fn decode(decoder: &mut Decoder<'a>) -> Result<T> {
32        let header = Header::decode(decoder)?;
33        header.tag.assert_eq(T::TAG)?;
34        T::decode_value(decoder, header.length)
35    }
36}