Parsing an integer with nom always results in Incomplete

戏子无情 提交于 2019-11-28 14:00:14

Nom 4 made the handling of partial data much stricter than in previous versions, to better support streaming parsers and custom input types.

Effectively, if the parser runs out of input and it can't tell that it's meant to have run out of input, it'll always return Err::Incomplete. This may also contain information on exactly how much more input the parser was expecting (in your case, at least 1 more byte).

It determines whether there's potentially any more input using the AtEof trait. This always returns false for &str and &[u8], as they don't provide any information about whether they're complete or not!

The trick is to change the input type of your parsers to make it explicit that the input will always be complete - Nom provides the CompleteStr and CompleteByteSlice wrappers for this purpose, or you can implement your own input type.

So in order for your parser to work as expected, it'd need to look something like this:

named!(my_u64(CompleteStr) -> u64,
    map_res!(recognize!(nom::digit), u64::from_str)
);

And your test would look something like this:

#[cfg(test)]
mod test {
    #[test]
    fn my_u64() {
        assert_eq!(Ok((CompleteStr(""), 0)), super::my_u64(CompleteStr("0")));
    }
}

See the announcement post for Nom 4 for more details.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!