From 6f03ef8001904020c2de379b73cedadf577ee9d4 Mon Sep 17 00:00:00 2001 From: dishmaker <141624503+dishmaker@users.noreply.github.com> Date: Thu, 10 Jul 2025 13:38:27 +0200 Subject: [PATCH] der: add `DecodeValueExt` trait with fn `from_der_value` --- der/src/decode.rs | 22 ++++++++++++++++++++-- der/src/lib.rs | 2 +- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/der/src/decode.rs b/der/src/decode.rs index 0ba035a44..4c717fd52 100644 --- a/der/src/decode.rs +++ b/der/src/decode.rs @@ -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; @@ -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>::Error> + where + Self: Choice<'a>, + { + AnyRef::new(tag, value)?.decode_as::() + } +} + +impl<'a, T> DecodeValueExt<'a> for T where T: DecodeValue<'a> {} diff --git a/der/src/lib.rs b/der/src/lib.rs index d867ef928..67ad5853d 100644 --- a/der/src/lib.rs +++ b/der/src/lib.rs @@ -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,