Skip to content

Commit 6d07d8f

Browse files
committed
asn1_rs-derive: avoid use of finish(), which can panic (Closes #40)
1 parent 8750624 commit 6d07d8f

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

derive/src/container.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,10 @@ fn get_field_parser(f: &FieldInfo, asn1_type: Asn1Type, custom_errors: bool) ->
423423
.map(|x| quote! {let #name: Option<_> = #name; let #name = #name.unwrap_or(#x);});
424424
let map_err = if let Some(tt) = f.map_err.as_ref() {
425425
if asn1_type == Asn1Type::Ber {
426-
Some(quote! { .finish().map_err(#tt) })
426+
Some(quote! {
427+
.map_err(|err| err.map(#tt))
428+
.map_err(asn1_rs::from_nom_error::<_, Self::Error>)
429+
})
427430
} else {
428431
// Some(quote! { .map_err(|err| nom::Err::convert(#tt)) })
429432
Some(quote! { .map_err(|err| err.map(#tt)) })
@@ -432,7 +435,7 @@ fn get_field_parser(f: &FieldInfo, asn1_type: Asn1Type, custom_errors: bool) ->
432435
// add mapping functions only if custom errors are used
433436
if custom_errors {
434437
if asn1_type == Asn1Type::Ber {
435-
Some(quote! { .finish() })
438+
Some(quote! { .map_err(asn1_rs::from_nom_error::<_, Self::Error>) })
436439
} else {
437440
Some(quote! { .map_err(nom::Err::convert) })
438441
}

src/error.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,17 @@ impl<I, E> FromExternalError<I, E> for Error {
177177
}
178178
}
179179

180+
/// Flatten all `nom::Err` variants error into a single error type
181+
pub fn from_nom_error<E, F>(e: nom::Err<E>) -> F
182+
where
183+
F: From<E> + From<Error>,
184+
{
185+
match e {
186+
nom::Err::Error(e) | nom::Err::Failure(e) => F::from(e),
187+
nom::Err::Incomplete(n) => F::from(Error::Incomplete(n)),
188+
}
189+
}
190+
180191
/// Holds the result of BER/DER serialization functions
181192
pub type ParseResult<'a, T, E = Error> = IResult<&'a [u8], T, E>;
182193

0 commit comments

Comments
 (0)