purescript-parsing-dataview/README.md
James Brock 092262955e README
2020-07-27 22:51:03 +09:00

2.8 KiB

purescript-parsing-dataview

CI Pursuit

The module Text.Parsing.Parser.DataView provides primitive parsers for parsing DataViews on Javascript ArrayBuffers with the package purescript-parsing.

This module brings the input stream support of purescript-parsing to be able to roughly match the built-in stream support of Megaparsec:

Stream type purescript-parsing Megaparsec
UTF-16 strings String Text
Listy strings Token String
Binary blobs Text.Parsing.Parser.DataView ByteString

Usage examples

Parse values out of a dataview :: Data.ArrayBuffer.Types.DataView. All DataView parsing must be done in an Effect context. The result will be Either a parse error or the parsed value.

Parse two numbers

Parse two big-endian IEEE 754 double-precision floats.

do
  result <- Text.Parsing.Parser.runParserT dataview $ do
    float1 <- anyFloat64be
    float2 <- anyFloat64be
    pure $ Tuple float1 float2

Parse an array

Parse an array of n 32-bit signed integers.

do
  result <- Text.Parsing.Parser.runParserT dataview $ replicateA n anyInt32be

Parse UTF8

Parse a String as UTF8 with a length prefix in a way that's compatible with the Binary.Put.putStringUtf8 function from the Haskell binary library.

We give this as an example, rather than supporting it in the library, because it depends on Data.TextDecoding.decodeUtf8.

do
  result <- Text.Parsing.Parser.runParserT dataview $ do
    -- Parse 32 bits of the big-endian 64-bit length prefix.
    _      <- anyUint32be
    length <- anyUint32be
    stringview <- takeN $ UInt.toInt length
    stringarray <- liftEffect $ mkTypedArray stringview
    case Data.TextDecoding.decodeUtf8 stringarray of
      Left err -> Data.Parsing.Parser.fail $ show err
      Right s  -> pure s

where
  mkTypedArray :: Data.ArrayBuffer.Types.DataView -> Effect Data.ArrayBuffer.Types.Uint8Array
  mkTypedArray dv = do
    let buffer     = Data.ArrayBuffer.DataView.buffer dv
        byteOffset = Data.ArrayBuffer.DataView.byteOffset dv
        byteLength = Data.ArrayBuffer.DataView.byteLength dv
    pure $ Data.ArrayBuffer.Typed.part buffer byteOffset byteLength