Skip to content

Commit 6f03ef8

Browse files
committed
der: add DecodeValueExt trait with fn from_der_value
1 parent 9ca99ba commit 6f03ef8

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

der/src/decode.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
//! Trait definition for [`Decode`].
22
3-
use crate::{EncodingRules, Error, FixedTag, Header, Reader, SliceReader, reader::read_value};
3+
use crate::{
4+
AnyRef, Choice, EncodingRules, Error, FixedTag, Header, Reader, SliceReader, Tag,
5+
reader::read_value,
6+
};
47
use core::marker::PhantomData;
58

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

912
#[cfg(doc)]
10-
use crate::{ErrorKind, Length, Tag};
13+
use crate::{ErrorKind, Length};
1114

1215
#[cfg(feature = "alloc")]
1316
use alloc::boxed::Box;
@@ -143,3 +146,18 @@ where
143146
Ok(Box::new(T::decode_value(reader, header)?))
144147
}
145148
}
149+
150+
/// Extension trait for [`DecodeValue`], simplifying slice decoding.
151+
pub trait DecodeValueExt<'a>: DecodeValue<'a> {
152+
/// Parse `Self` from the provided DER-encoded value bytes, i.e. without the tag-length.
153+
///
154+
/// Returns [`ErrorKind::TrailingData`] if message is incomplete.
155+
fn from_der_value(tag: Tag, value: &'a [u8]) -> Result<Self, <Self as DecodeValue<'a>>::Error>
156+
where
157+
Self: Choice<'a>,
158+
{
159+
AnyRef::new(tag, value)?.decode_as::<Self>()
160+
}
161+
}
162+
163+
impl<'a, T> DecodeValueExt<'a> for T where T: DecodeValue<'a> {}

der/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ pub use crate::{
364364
asn1::bit_string::allowed_len_bit_string::AllowedLenBitString,
365365
asn1::{AnyRef, Choice, Sequence},
366366
datetime::DateTime,
367-
decode::{Decode, DecodeOwned, DecodeValue},
367+
decode::{Decode, DecodeOwned, DecodeValue, DecodeValueExt},
368368
encode::{Encode, EncodeValue},
369369
encode_ref::{EncodeRef, EncodeValueRef},
370370
encoding_rules::EncodingRules,

0 commit comments

Comments
 (0)