1 //! This test file ensures the functions to parse containers like sequences and sets
2 //! work correctly with custom errors.
3
4 use der_parser::ber::{parse_ber_sequence_of_v, parse_ber_u32};
5 use der_parser::error::BerError;
6 use nom::error::{ErrorKind, ParseError};
7 use nom::{Err, IResult};
8
9 #[derive(Debug)]
10 pub enum MyError<'a> {
11 Variant1,
12 Variant2,
13 BerError(BerError),
14 NomError(&'a [u8], ErrorKind),
15 }
16
17 impl<'a> ParseError<&'a [u8]> for MyError<'a> {
from_error_kind(input: &'a [u8], kind: ErrorKind) -> Self18 fn from_error_kind(input: &'a [u8], kind: ErrorKind) -> Self {
19 MyError::NomError(input, kind)
20 }
21
append(_input: &'a [u8], _kind: ErrorKind, other: Self) -> Self22 fn append(_input: &'a [u8], _kind: ErrorKind, other: Self) -> Self {
23 other
24 }
25 }
26
27 impl<'a> From<BerError> for MyError<'a> {
from(e: BerError) -> Self28 fn from(e: BerError) -> Self {
29 MyError::BerError(e)
30 }
31 }
32
33 #[test]
parse_sequence_of_v_custom_errors()34 fn parse_sequence_of_v_custom_errors() {
35 fn parse_element(i: &[u8]) -> IResult<&[u8], u32, MyError> {
36 // incomplete must *NOT* be mapped, or parse_ber_sequence_of_v cannot detect end of
37 // sequence
38 match parse_ber_u32(i) {
39 Ok(x) => Ok(x),
40 Err(Err::Incomplete(e)) => Err(Err::Incomplete(e)),
41 _ => Err(Err::Error(MyError::Variant1)),
42 }
43 }
44
45 let bytes = [
46 0x30, 0x0a, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x03, 0x01, 0x00, 0x00,
47 ];
48
49 let (rem, v) =
50 parse_ber_sequence_of_v(parse_element)(&bytes).expect("Could not parse SEQUENCE OF");
51 assert!(rem.is_empty());
52 assert_eq!(&v, &[65537, 65536]);
53 }
54