Skip to content

rowtype-yoga/purescript-parsing-dataview

Repository files navigation

purescript-parsing-dataview

CI Pursuit Maintainer: jamesdbrock

Primitive parsers for DataViews on JavaScript ArrayBuffers with the package parsing.

With this package, the input stream support of parsing is similar to the built-in stream support of Megaparsec:

Stream type parsing Megaparsec
UTF-16 strings String Text < v2.0
UTF-8 strings DataView Text ≥ v2.0
Listy strings Token String
Binary blobs 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 Numbers.

import Parsing (runParserT)
import Parsing.DataView (anyFloat64be)

do
  result <- runParserT dataview do
    float1 <- anyFloat64be
    float2 <- anyFloat64be
    pure $ Tuple float1 float2

Parse an array

Parse an array of n 32-bit big-endian signed Ints.

import Parsing (runParserT)
import Parsing.DataView (anyUint32be)
import Data.Unfoldable (replicateA)

do
  result <- runParserT dataview $ replicateA n anyInt32be

Parse UTF-8

Parse a UTF-8 String with a length prefix.

We give this as an example, rather than supporting it in the library, because it depends on web-encoding for UTF-8.

import Control.Monad.Except (ExceptT)
import Data.ArrayBuffer.Cast (toUint8Array)
import Effect.Exception (catchException, message)
import Parsing (runParserT, liftExceptT)
import Parsing.DataView (anyInt32be, takeN)
import Web.Encoding.TextDecoder as TextDecoder
import Web.Encoding.UtfLabel as UtfLabel

do
  textDecoder <- TextDecoder.new UtfLabel.utf8

  result <- runParserT dataview do
    -- First parse a 32-bit big-endian length prefix for the length
    -- of the UTF-8 string in bytes.
    length      <- anyInt32be
    stringview  <- takeN length
    stringarray <- lift $ liftEffect $ toUint8Array stringview
    liftExceptT $ ExceptT $ catchException (pure <<< Left <<< message) do
      Right <$> TextDecoder.decode stringarray textDecoder

Serialization

This package is for reading (DataViews on) ArrayBuffers, not writing them. See the package arraybuffer-builder for a way to serialize and build ArrayBuffers.

References

Development

Run the tests with the development spago file:

spago -x spago-dev.dhall test