3

我正在编写一个 nom 解析器组合器,它消耗字节并返回一个Option<&[u8]>. 解析器组合器应遵循以下规则:

  1. 读取单个有符号大端 16 位整数 ( s)
  2. 如果s是-1,返回None
  3. 如果s不是 -1,则读取s位并返回Some

这是我的解析器组合器:

fn parse(i: &[u8]) -> nom::IResult<&[u8], Option<&[u8]>> {
    nom::combinator::flat_map(be_i16, |s: i16| {
        match s {
            -1 => nom::combinator::success(None),
            _ => nom::combinator::map(take(s as u16), Some)
        }
    })(i)
}

但是我看到以下错误:

error[E0308]: `match` arms have incompatible types
  --> src/main.rs:15:18
   |
13 | /         match s {
14 | |             -1 => nom::combinator::success(None),
   | |                   ------------------------------ this is found to be of type `impl Fn<(_,)>`
15 | |             _ => nom::combinator::map(take(s as u16), Some)
   | |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found a different opaque type
16 | |         }
   | |_________- `match` arms have incompatible types
   |
  ::: /Users/dfarr/.cargo/registry/src/github.com-1ecc6299db9ec823/nom-6.0.1/src/combinator/mod.rs:74:64
   |
74 |   pub fn map<I, O1, O2, E, F, G>(mut first: F, mut second: G) -> impl FnMut(I) -> IResult<I, O2, E>
   |                                                                  ---------------------------------- the found opaque type
   |
   = note:     expected type `impl Fn<(_,)>`
           found opaque type `impl FnMut<(_,)>`
   = note: distinct uses of `impl Trait` result in different opaque types

我可以看到nom::combinator::success确实有一个返回类型impl Fn(I) -> ...,并且nom::combinator::map返回impl FnMut(I) -> ...。有没有一种更惯用的方式来使用 nom ,这些组合器可以以这种方式一起使用?

4

0 回答 0