From 4d6aa6d53297ef21901a6ba62387b5e15f148852 Mon Sep 17 00:00:00 2001 From: Pierre Chifflier Date: Tue, 18 Jan 2022 21:56:37 +0100 Subject: [PATCH] rust: add 'bits' combinator to simplify nom bits parsers Add a specialized version of the 'bits' nom combinator so adding bits-level parsers does not require type annotations. --- rust/src/common.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/rust/src/common.rs b/rust/src/common.rs index 71eaad728f..bbb4a73bfc 100644 --- a/rust/src/common.rs +++ b/rust/src/common.rs @@ -3,7 +3,8 @@ use std::os::raw::c_char; pub mod nom7 { use nom7::bytes::streaming::{tag, take_until}; - use nom7::error::ParseError; + use nom7::error::{Error, ParseError}; + use nom7::ErrorConvert; use nom7::IResult; /// Reimplementation of `take_until_and_consume` for nom 7 @@ -20,6 +21,24 @@ pub mod nom7 { Ok((i, res)) } } + + /// Specialized version of the nom 7 `bits` combinator + /// + /// The `bits combinator has trouble inferring the transient error type + /// used by the tuple parser, because the function is generic and any + /// error type would be valid. + /// Use an explicit error type (as described in + /// https://docs.rs/nom/7.1.0/nom/bits/fn.bits.html) to solve this problem, and + /// specialize this function for `&[u8]`. + pub fn bits<'a, O, E, P>(parser: P) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], O, E> + where + E: ParseError<&'a [u8]>, + Error<(&'a [u8], usize)>: ErrorConvert, + P: FnMut((&'a [u8], usize)) -> IResult<(&'a [u8], usize), O, Error<(&'a [u8], usize)>>, + { + // use full path to disambiguate nom `bits` from this current function name + nom7::bits::bits(parser) + } } #[macro_export]