rocket::mtls::x509::der

Function parse_der_container

Source
pub fn parse_der_container<'a, O, F, E>(f: F) -> impl FnMut(&'a [u8])
where F: FnMut(&'a [u8], Header<'a>) -> Result<(&'a [u8], O), Err<E>>, E: ParseError<&'a [u8]> + From<Error>,
Available on crate feature mtls only.
Expand description

Parse a DER object and apply provided function to content

Given a parser for content, read DER object header and apply parser to return the remaining bytes and the parser result.

The remaining bytes point after the content: any bytes that are part of the content but not parsed are ignored. The nom combinator all_consuming can be used to ensure all the content is parsed.

This function is mostly intended for constructed objects, but can be used for any valid DER object.

ยงExamples

Parsing a defined sequence with different types:

pub struct MyObject<'a> {
    a: u32,
    b: &'a [u8],
}

/// Read a DER-encoded object:
/// SEQUENCE {
///     a INTEGER (0..4294967295),
///     b OCTETSTRING
/// }
fn parse_myobject(i: &[u8]) -> BerResult<MyObject> {
    parse_der_container(
        |i: &[u8], hdr: Header| {
            if hdr.tag() != Tag::Sequence {
                return Err(nom::Err::Error(BerError::BerTypeError.into()));
            }
            let (i, a) = parse_der_u32(i)?;
            let (i, obj) = parse_der_octetstring(i)?;
            let b = obj.as_slice().unwrap();
            Ok((i, MyObject{ a, b }))
        }
    )(i)
}

let (rem, v) = parse_myobject(&bytes).expect("parsing failed");