Skip to content

der: add DecodeValueExt trait with fn from_der_value #1936

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions der/src/decode.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
//! Trait definition for [`Decode`].

use crate::{EncodingRules, Error, FixedTag, Header, Reader, SliceReader, reader::read_value};
use crate::{
AnyRef, Choice, EncodingRules, Error, FixedTag, Header, Reader, SliceReader, Tag,
reader::read_value,
};
use core::marker::PhantomData;

#[cfg(feature = "pem")]
use crate::{PemReader, pem::PemLabel};

#[cfg(doc)]
use crate::{ErrorKind, Length, Tag};
use crate::{ErrorKind, Length};

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
Expand Down Expand Up @@ -143,3 +146,18 @@ where
Ok(Box::new(T::decode_value(reader, header)?))
}
}

/// Extension trait for [`DecodeValue`], simplifying slice decoding.
pub trait DecodeValueExt<'a>: DecodeValue<'a> {
/// Parse `Self` from the provided DER-encoded value bytes, i.e. without the tag-length.
///
/// Returns [`ErrorKind::TrailingData`] if message is incomplete.
fn from_der_value(tag: Tag, value: &'a [u8]) -> Result<Self, <Self as DecodeValue<'a>>::Error>
where
Self: Choice<'a>,
{
AnyRef::new(tag, value)?.decode_as::<Self>()
}
}

impl<'a, T> DecodeValueExt<'a> for T where T: DecodeValue<'a> {}
2 changes: 1 addition & 1 deletion der/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ pub use crate::{
asn1::bit_string::allowed_len_bit_string::AllowedLenBitString,
asn1::{AnyRef, Choice, Sequence},
datetime::DateTime,
decode::{Decode, DecodeOwned, DecodeValue},
decode::{Decode, DecodeOwned, DecodeValue, DecodeValueExt},
encode::{Encode, EncodeValue},
encode_ref::{EncodeRef, EncodeValueRef},
encoding_rules::EncodingRules,
Expand Down