Skip to content

Commit

Permalink
der: add Decode::from_ber (#1389)
Browse files Browse the repository at this point in the history
Support for decoding an input byte slice while specifying what encoding
rules should be used with the given reader.
  • Loading branch information
tarcieri authored Apr 24, 2024
1 parent a375cbf commit e8ef21c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
12 changes: 11 additions & 1 deletion der/src/decode.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Trait definition for [`Decode`].
use crate::{Error, FixedTag, Header, Reader, SliceReader};
use crate::{EncodingRules, Error, FixedTag, Header, Reader, SliceReader};
use core::marker::PhantomData;

#[cfg(feature = "pem")]
Expand All @@ -23,6 +23,16 @@ pub trait Decode<'a>: Sized + 'a {
/// Attempt to decode this message using the provided decoder.
fn decode<R: Reader<'a>>(decoder: &mut R) -> Result<Self, Self::Error>;

/// Parse `Self` from the provided BER-encoded byte slice.
///
/// Note that most usages should probably use [`Decode::from_der`]. This method allows some
/// BER productions which are not allowed under DER.
fn from_ber(bytes: &'a [u8]) -> Result<Self, Self::Error> {
let mut reader = SliceReader::new_with_encoding_rules(bytes, EncodingRules::Ber)?;
let result = Self::decode(&mut reader)?;
Ok(reader.finish(result)?)
}

/// Parse `Self` from the provided DER-encoded byte slice.
fn from_der(bytes: &'a [u8]) -> Result<Self, Self::Error> {
let mut reader = SliceReader::new(bytes)?;
Expand Down
12 changes: 10 additions & 2 deletions der/src/reader/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,17 @@ pub struct SliceReader<'a> {
impl<'a> SliceReader<'a> {
/// Create a new slice reader for the given byte slice.
pub fn new(bytes: &'a [u8]) -> Result<Self, Error> {
Self::new_with_encoding_rules(bytes, EncodingRules::default())
}

/// Create a new slice reader with the given encoding rules.
pub fn new_with_encoding_rules(
bytes: &'a [u8],
encoding_rules: EncodingRules,
) -> Result<Self, Error> {
Ok(Self {
bytes: BytesRef::new(bytes)?,
encoding_rules: EncodingRules::default(),
encoding_rules,
failed: false,
position: Length::ZERO,
})
Expand Down Expand Up @@ -196,7 +204,7 @@ mod tests {
assert_eq!(
ErrorKind::TrailingData {
decoded: 3u8.into(),
remaining: 1u8.into()
remaining: 1u8.into(),
},
err.kind()
);
Expand Down

0 comments on commit e8ef21c

Please sign in to comment.