Skip to content

der: simplify Tag::peek_matches in context-specific decoder #1811

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

Merged
Merged
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
26 changes: 2 additions & 24 deletions der/src/asn1/context_specific.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl<T> ContextSpecific<T> {
where
T: Decode<'a>,
{
if !peek_tag_matches(reader, Class::ContextSpecific, tag_number)? {
if !Tag::peek_matches(reader, Class::ContextSpecific, tag_number)? {
return Ok(None);
}
Ok(Some(Self::decode(reader)?))
Expand All @@ -67,7 +67,7 @@ impl<T> ContextSpecific<T> {
T: DecodeValue<'a> + IsConstructed,
{
// Peek tag number
if !peek_tag_matches::<_, T::Error>(reader, Class::ContextSpecific, tag_number)? {
if !Tag::peek_matches(reader, Class::ContextSpecific, tag_number)? {
return Ok(None);
}
// Decode IMPLICIT header
Expand All @@ -92,28 +92,6 @@ impl<T> ContextSpecific<T> {
}
}

/// Returns true if given context-specific (or any given class) field
/// should be decoded, based on peeked tag.
fn peek_tag_matches<'a, R: Reader<'a>, E>(
reader: &mut R,
expected_class: Class,
expected_tag_number: TagNumber,
) -> Result<bool, E>
where
E: From<Error>,
{
// Peek tag or ignore end of stream
let Some(tag) = Tag::peek_optional(reader)? else {
return Ok(false);
};
// Ignore tags with different numbers
if tag.class() != expected_class || tag.number() != expected_tag_number {
return Ok(false);
}
// Tag matches
Ok(true)
}

impl<'a, T> Choice<'a> for ContextSpecific<T>
where
T: Decode<'a> + Tagged,
Expand Down
18 changes: 18 additions & 0 deletions der/src/tag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,24 @@ impl Tag {
Err(ErrorKind::TagNumberInvalid.into())
}

/// Returns true if given context-specific (or any given class) tag number matches the peeked tag.
pub(crate) fn peek_matches<'a, R: Reader<'a>>(
reader: &mut R,
expected_class: Class,
expected_tag_number: TagNumber,
) -> Result<bool> {
// Peek tag or ignore end of stream
let Some(tag) = Tag::peek_optional(reader)? else {
return Ok(false);
};
// Ignore tags with different numbers
if tag.class() != expected_class || tag.number() != expected_tag_number {
return Ok(false);
}
// Tag matches
Ok(true)
}

/// Assert that this [`Tag`] matches the provided expected tag.
///
/// On mismatch, returns an [`Error`] with [`ErrorKind::TagUnexpected`].
Expand Down