Search code examples
haskellattoparsec

Transform an attoparsec parser into a parser which fails if the number of bytes it consumes is not of a certain length


Say I have an attoparsec parser, x.

I am looking to create a function f :: Int -> Parser a -> Parser a, such that if y = f n x, then:

  • y fails if x fails
  • y fails if x succeeds and x does not consume n bytes
  • y succeeds otherwise

How would I go about doing this?


Solution

  • You can use match to implement it:

    f n x = do
        (bs, res) <- match x
        guard (BS.length bs >= n)
        return res
    

    You should check that this interacts with (<|>) in an acceptable way before putting it to heavy use.