Error handling with nom and eyre

I'm trying to parse some binary data using nom and eyre. For parser functions that will need to chain with other parsers, I name them parse and have them return an IResult, and everything is dandy. But if a function is going to consume the entire buffer and just return a struct, say, I just have it return an eyre::Result.

impl Header {
    fn parse(input: &[u8]) -> IResult<&[u8], Self> {...}

impl MyStruct {
    fn new(buf: &[u8]) -> eyre::Result<Self> {
        let (input, header) = Header::parse(buf).finish()?;

However, this doesn't work because: [u8] cannot be formatted with the default formatter
because std::fmt::Display is required for std::error::Error and is not implemented for [u8]. It seems I cannot convert from an IResult to any std::error::Error type if the I or O of IResult doesn't implement Display.

Is there an easy workaround?

One kind of workaround is that instead of having fn new return an eyre::Result, it can return a std Result<Self, MyErr> with a MyErr type that you declare yourself. Then you can implement the required from trait for it to convert an IResult to your result yourself, and you can implement Display and std Error so it can be converted to an eyre::Result by the caller if that returns an eyre::Result.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.