File: custom_error.rs

package info (click to toggle)
rust-der-parser 10.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 492 kB
  • sloc: makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,494 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! This test file ensures the functions to parse containers like sequences and sets
//! work correctly with custom errors.

use der_parser::ber::{parse_ber_sequence_of_v, parse_ber_u32};
use der_parser::error::BerError;
use nom::error::{ErrorKind, ParseError};
use nom::{Err, IResult};

#[derive(Debug)]
pub enum MyError<'a> {
    Variant1,
    Variant2,
    BerError(BerError),
    NomError(&'a [u8], ErrorKind),
}

impl<'a> ParseError<&'a [u8]> for MyError<'a> {
    fn from_error_kind(input: &'a [u8], kind: ErrorKind) -> Self {
        MyError::NomError(input, kind)
    }

    fn append(_input: &'a [u8], _kind: ErrorKind, other: Self) -> Self {
        other
    }
}

impl From<BerError> for MyError<'_> {
    fn from(e: BerError) -> Self {
        MyError::BerError(e)
    }
}

#[test]
fn parse_sequence_of_v_custom_errors() {
    fn parse_element(i: &[u8]) -> IResult<&[u8], u32, MyError> {
        // incomplete must *NOT* be mapped, or parse_ber_sequence_of_v cannot detect end of
        // sequence
        match parse_ber_u32(i) {
            Ok(x) => Ok(x),
            Err(Err::Incomplete(e)) => Err(Err::Incomplete(e)),
            _ => Err(Err::Error(MyError::Variant1)),
        }
    }

    let bytes = [
        0x30, 0x0a, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x03, 0x01, 0x00, 0x00,
    ];

    let (rem, v) =
        parse_ber_sequence_of_v(parse_element)(&bytes).expect("Could not parse SEQUENCE OF");
    assert!(rem.is_empty());
    assert_eq!(&v, &[65537, 65536]);
}