Macro nom::try_parse[][src]

macro_rules! try_parse {
    ($i:expr, $submac:ident!( $($args:tt)* )) => { ... };
    ($i:expr, $f:expr) => { ... };
}

A bit like std::try!, this macro will return the remaining input and parsed value if the child parser returned Ok, and will do an early return for the Err side.

this can provide more flexibility than do_parse! if needed


 fn take_add(input:&[u8], size: u8) -> IResult<&[u8], &[u8]> {
   let (i1, length)     = try_parse!(input, map_opt!(nom::number::streaming::be_u8, |sz| size.checked_add(sz)));
   let (i2, data)   = try_parse!(i1, take!(length));
   return Ok((i2, data));
 }
let arr1 = [1, 2, 3, 4, 5];
let r1 = take_add(&arr1[..], 1);
assert_eq!(r1, Ok((&[4,5][..], &[2,3][..])));

let arr2 = [0xFE, 2, 3, 4, 5];
// size is overflowing
let r1 = take_add(&arr2[..], 42);
assert_eq!(r1, Err(Err::Error(error_position!(&[254, 2,3,4,5][..], ErrorKind::MapOpt))));