Macro nom::switch [] [src]

macro_rules! switch {
    (__impl $i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => { ... };
    ($i:expr, $submac:ident!( $($args:tt)*), $($rest:tt)*) => { ... };
    ($i:expr, $e:ident, $($rest:tt)*) => { ... };
}

switch!(I -> IResult<I,P>, P => I -> IResult<I,O> | ... | P => I -> IResult<I,O> ) => I -> IResult<I, O> choose the next parser depending on the result of the first one, if successful, and returns the result of the second parser

 named!(sw,
   switch!(take!(4),
     b"abcd" => tag!("XYZ") |
     b"efgh" => tag!("123")
   )
 );

 let a = b"abcdXYZ123";
 let b = b"abcdef";
 let c = b"efgh123";
 let d = b"blah";

 assert_eq!(sw(&a[..]), Done(&b"123"[..], &b"XYZ"[..]));
 assert_eq!(sw(&b[..]), Error(error_node_position!(ErrorKind::Switch, &b"abcdef"[..],
   error_position!(ErrorKind::Tag, &b"ef"[..]))));
 assert_eq!(sw(&c[..]), Done(&b""[..], &b"123"[..]));
 assert_eq!(sw(&d[..]), Error(error_position!(ErrorKind::Switch, &b"blah"[..])));

Due to limitations in Rust macros, it is not possible to have simple functions on the right hand side of pattern, like this:

 named!(sw,
   switch!(take!(4),
     b"abcd" => tag!("XYZ") |
     b"efgh" => tag!("123")
   )
 );

If you want to pass your own functions instead, you can use the call! combinator as follows:

 named!(xyz, tag!("XYZ"));
 named!(num, tag!("123"));
 named!(sw,
   switch!(take!(4),
     b"abcd" => call!(xyz) |
     b"efgh" => call!(num)
   )
 );