Skip to content

Commit 9680af5

Browse files
authored
spki: return Result from AlgorithmIdentifier::params_* (#274)
Returning a result makes for simpler error handling with `?` in functions which also return a `Result`, and also makes it possible to propagate incompatible DER tags encountered when using these methods.
1 parent 6aa1058 commit 9680af5

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

spki/src/algorithm.rs

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,34 @@ pub struct AlgorithmIdentifier<'a> {
2727
impl<'a> AlgorithmIdentifier<'a> {
2828
/// Get the `parameters` field as an [`Any`].
2929
///
30-
/// This will be `None` if the parameters are an [`ObjectIdentifier`] or
31-
/// [`Null`], so this method should be used for handling any other
32-
/// ASN.1 type besides those two.
33-
pub fn parameters_any(&self) -> Option<Any<'a>> {
34-
self.parameters.and_then(AlgorithmParameters::any)
30+
/// Returns an error if `parameters` are `None`, or if they are `Some`
31+
/// but are an [`ObjectIdentifier`] or [`Null`], i.e. this method is
32+
/// explicitly for handling cases other than those two.
33+
pub fn parameters_any(&self) -> Result<Any<'a>> {
34+
let params = self.parameters.ok_or(der::ErrorKind::Truncated)?;
35+
36+
params.any().ok_or_else(|| {
37+
der::ErrorKind::UnexpectedTag {
38+
expected: Some(der::Tag::Sequence),
39+
actual: params.tag(),
40+
}
41+
.into()
42+
})
3543
}
3644

3745
/// Get the `parameters` field as an [`ObjectIdentifier`].
3846
///
39-
/// Returns `None` if it is absent or not an OID.
40-
pub fn parameters_oid(&self) -> Option<ObjectIdentifier> {
41-
self.parameters.and_then(AlgorithmParameters::oid)
47+
/// Returns an error if it is absent or not an OID.
48+
pub fn parameters_oid(&self) -> Result<ObjectIdentifier> {
49+
let params = self.parameters.ok_or(der::ErrorKind::Truncated)?;
50+
51+
params.oid().ok_or_else(|| {
52+
der::ErrorKind::UnexpectedTag {
53+
expected: Some(der::Tag::Sequence),
54+
actual: params.tag(),
55+
}
56+
.into()
57+
})
4258
}
4359
}
4460

@@ -126,6 +142,15 @@ impl<'a> AlgorithmParameters<'a> {
126142
pub fn is_oid(self) -> bool {
127143
self.oid().is_some()
128144
}
145+
146+
/// Get the ASN.1 DER [`Tag`] for these parameters
147+
pub fn tag(self) -> Tag {
148+
match self {
149+
Self::Any(any) => any.tag(),
150+
Self::Null => Tag::Null,
151+
Self::Oid(_) => Tag::ObjectIdentifier,
152+
}
153+
}
129154
}
130155

131156
impl<'a> From<Null> for AlgorithmParameters<'a> {

0 commit comments

Comments
 (0)