Parsing an integer with nom always results in Incomplete

前端 未结 2 667
遇见更好的自我
遇见更好的自我 2021-01-13 21:03

Everything I try gives me Incomplete(Size(1)). My best guess right now is:

named!(my_u64(&str) -> u64,
    map_res!(recognize!(nom::digit         


        
2条回答
  •  梦谈多话
    2021-01-13 22:01

    As of nom 5.1.1 approach towards combining parsers changed from macro-based to function based, what is discussed broader in nom's author blog.

    Along with this change another followed - streaming and complete parsers are now residing in different modules and you need to explicitly choose which type of parsing you need. Most usually there is a clear distinction with module name.

    Old macros are preserved, but they work strictly in streaming mode. Types like CompleteStr or CompleteByteSlice are gone.

    To write code you asked for the new way you could do it for example like this (notice explicit character::complete in imports)

    Since it took me some time to grasp it - parsers e.g map_res return a impl Fn(I) -> IResult which is why there is additional pair of parenthesis - to call that closure.

    use std::str;
    use nom::{
        IResult,
        character::complete::{
            digit1
        },
        combinator::{
            recognize,
            map_res
        }
    };
    
    fn my_u64(input : &str) -> IResult<&str, u64> {
        map_res(recognize(digit1), str::parse)(input)
    }
    
    #[cfg(test)]
    mod test {
        use super::*;
        #[test]
        fn test_my_u64() {
            let input = "42";
            let num = my_u64(input);
            assert_eq!(Ok(("", 42u64)), num);
        }
    }
    

提交回复
热议问题