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:path, $($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[..]), Ok((&b"123"[..], &b"XYZ"[..])));
 assert_eq!(sw(&b[..]), Err(Err::Error(error_node_position!(&b"abcdef"[..], ErrorKind::Switch,
   error_position!(&b"ef"[..], ErrorKind::Tag)))));
 assert_eq!(sw(&c[..]), Ok((&b""[..], &b"123"[..])));
 assert_eq!(sw(&d[..]), Err(Err::Error(error_position!(&b"blah"[..], ErrorKind::Switch))));

You can specify a default case like with a normal match, using _

 named!(sw,
   switch!(take!(4),
     b"abcd" => tag!("XYZ") |
     _       => value!(&b"default"[..])
   )
 );

 let a = b"abcdXYZ123";
 let b = b"blah";

 assert_eq!(sw(&a[..]), Ok((&b"123"[..], &b"XYZ"[..])));
 assert_eq!(sw(&b[..]), Ok((&b""[..], &b"default"[..])));

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

 named!(xyz, tag!("XYZ"));
 named!(num, tag!("123"));
 named!(sw,
   switch!(take!(4),
     b"abcd" => xyz |
     b"efgh" => 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)
   )
 );