Skip to content

Conversation

sebosp
Copy link

@sebosp sebosp commented Mar 24, 2025

@sebosp sebosp requested a review from Geal as a code owner March 24, 2025 21:30
@asibahi
Copy link

asibahi commented Apr 13, 2025

I have been mucking around with this. I think a better implementation would be to implement it as a proper impl Parser a la nom8. Also made it generic over HexDisplay rather than be wedded to &[u8].

#[cfg(feature = "std")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "std")))]
pub fn dbg_dmp<'a, P, I, O, E>(parser: P, context: &'static str) -> DbgDmp<P>
where
  E: std::fmt::Debug,
  P: Parser<I, Output = O, Error = E>,
{
  DbgDmp { parser, context }
}

/// dbg_dmp implementation
#[cfg(feature = "std")]
pub struct DbgDmp<P> {
  parser: P,
  context: &'static str,
}

#[cfg(feature = "std")]
impl<F, I> Parser<I> for DbgDmp<F>
where
  I: HexDisplay + Clone,
  F: Parser<I>,
  <F as Parser<I>>::Error: std::fmt::Debug,
{
  type Output = <F as Parser<I>>::Output;
  type Error = <F as Parser<I>>::Error;

  fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> {
    match self
      .parser
      .process::<OutputM<OM::Output, Emit, OM::Incomplete>>(input.clone())
    {
      Err(e) => {
        eprintln!("{} Error: {:?} at:\n{}", self.context, e, input.to_hex(8));
        match e {
          Err::Error(e) => Err(Err::Error(OM::Error::bind(|| e))),
          Err::Failure(e) => Err(Err::Failure(e)),
          Err::Incomplete(e) => Err(Err::Incomplete(e)),
        }
      }
      Ok(v) => Ok(v),
    }
  }
}

(Edit: a slightly more concise code).

It does look overly complex and I do not particularly like it. I adjusted the doctest to accommodate it and it passes.

use nom::{Parser, IResult, error::dbg_dmp, bytes::tag};

fn f(i: &[u8]) -> IResult<&[u8], &[u8]> {
  dbg_dmp(tag("abcd"), "tag").parse_complete(i)
}

let a = &b"efghijkl"[..];

// Will print the following message:
// tag Error: Error(Error { input: [101, 102, 103, 104, 105, 106, 107, 108], code: Tag }) at:
// 00000000	65 66 67 68 69 6a 6b 6c 	efghijkl
f(a);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants