Attoparsec is a parser-combinator library for constructing high-performance parsers, particularly for raw byte data. Small parsers compose into larger ones through familiar Haskell abstractions, making a binary format parser read like a sequence of format rules rather than manual input handling. section 12.0 section 12.2
The central byte-oriented type is `Parser a`, imported from `Data.Attoparsec.ByteString`; it parses `ByteString` input. `Data.Attoparsec.Text` provides equivalent parsing types and functions for `Text`. A `ByteString` contains `Word8` values, so its input is suited to binary files as well as byte-encoded textual fields. section 12.2 section 12.2.1
Build parsers from byte-level primitives and combinators:
- Use `string` to recognize a fixed `ByteString`, `word8` for a particular byte, and `anyWord8` for any byte. section 12.2.1
- Use `satisfy` for predicates such as accepted whitespace, `choice` for alternatives, and `skipMany1` for one-or-more repetitions. section 12.2.2
- Use `C8.decimal` from `Data.Attoparsec.ByteString.Char8` to parse decimal fields, and Applicative or Monad operations to turn parsed fields into Haskell values. section 12.2.2
- Use `parse` when incremental input matters: it returns `Done`, `Fail`, or `Partial`. Use `parseOnly` for complete inputs when only success or failure is needed. section 12.2.1
Parsing a PNM header
A PNM header parser first skips whitespace and comments, selects one of the `P1` through `P6` magic-number parsers, reads width and height with `decimal`, then reads an optional maximum value for formats other than `P1` and `P4`. Fixed markers can be translated directly into constructors, as in `P1 <$ string "P1"`. section 12.2.2
ghci> Partial c = AP.parse (AP.string "Hello") "He" ghci> Partial c2 = c "l" ghci> c2 "lo" Done "" "Hello"
A `Partial` result holds a continuation: supply successive byte chunks until the fixed string parser can produce `Done`. section 12.2.1
Incremental input allows parsing to begin before a large file is fully loaded. However, arbitrary backtracking means that once all input has been supplied, the complete input remains in memory. section 12.2
