0

I'm using rust nom 4.0.0 where it supports switch! macro:

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

However, nom 7.1.1 doesn't support switch! macro and I was wondering if there are other ways to achieve the same result with nom 7.1.1.

MoneyBall
  • 2,343
  • 5
  • 26
  • 59
  • 1
    Presumably you'd do this with [`alt`](https://docs.rs/nom/latest/nom/branch/fn.alt.html). – cdhowie May 17 '22 at 00:12
  • @cdhowie I think you are right! I'll check it out! Thank you! – MoneyBall May 17 '22 at 00:14
  • 1
    Good luck. I didn't post an answer because I haven't used nom and don't quite understand what your example does, just enough to recognize that it's trying out alternative patterns, which is what `alt` does. – cdhowie May 17 '22 at 00:17
  • @cdhowie gotcha! It seems to be that `alt` is a more general form of `switch` where `switch` requires a fixed number of bytes as an argument while `alt` doesn't need a fixed number of bytes. Thank you! – MoneyBall May 17 '22 at 00:36
  • `alt()` is not a complete replacement for `switch!`: you can't choose based on the previous parsed input. This is common in binary formats. I had this problem some time ago. I ended up using `match`, but this break the sequence of combinators and... not really, uh, nom-y. – Chayim Friedman May 17 '22 at 14:54
  • @ChayimFriedman I jumped from `nom 4.x.x` to `nom 7.x.x` and there's definitely lots of breaking changes. I think you're right in that `alt()` is not a complete replacement for `switch!`. However, I think some combination of `map`, `take` and other methods can replace `switch!`. I'm not sure if it's faster though.. – MoneyBall May 17 '22 at 23:24

0 Answers0