streamly-flatparse (empty) → 0.1.0.0
raw patch · 7 files changed
+640/−0 lines, 7 filesdep +basedep +bytestringdep +flatparse
Dependencies added: base, bytestring, flatparse, streamly-bytestring, streamly-core, streamly-flatparse, tasty, tasty-bench, tasty-hunit, tasty-quickcheck
Files
- CHANGELOG.md +7/−0
- LICENSE +29/−0
- README.md +74/−0
- bench/Main.hs +108/−0
- src/Streamly/External/FlatParse.hs +197/−0
- streamly-flatparse.cabal +91/−0
- test/Main.hs +134/−0
+ CHANGELOG.md view
@@ -0,0 +1,7 @@+# Revision history for streamly-flatparse++## 0.1.0.0 -- 2026-11-28++* First release on Hackage.+* `parseBreak`, `parse`, `parseBreakOn`, `parseMany` and `parseArray`:+ flatparse parsers on streams of byte arrays, within a size.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Xavier Dectot+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,74 @@+# streamly-flatparse++Run [flatparse](https://hackage.haskell.org/package/flatparse) parsers on+[Streamly](https://streamly.composewell.com/) streams of byte arrays.++flatparse parsers are fast, but they read one piece of bytes and cannot+stop to wait for more. Bytes that come from a socket or a file come in+arrays cut anywhere. This library stands between the two, in place of the+parsers of Streamly: it gathers the arrays of a stream until a parser has+what it needs, within a size, and gives the stream that follows what was+parsed.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Data.Word (Word8)+import FlatParse.Basic (Parser, anyAsciiDecimalInt, byteString)+import Streamly.Data.Array (Array)+import Streamly.Data.Stream (Stream)+import Streamly.External.FlatParse (ParseError, parseMany)++-- A decimal number on a line of its own.+line :: Parser () Int+line = anyAsciiDecimalInt <* byteString "\n"++numbers :: Monad m => Stream m (Array Word8) -> Stream m (Either (ParseError ()) Int)+numbers = parseMany 100 line+```++## What it gives++- `parseBreak`: a parser on the start of a stream, tried again as arrays+ come, with the stream that follows what it read. `parse` gives the result+ alone.+- `parseBreakOn`: the same after waiting for a delimiter, the parser run+ once on the bytes up to it.+- `parseMany`: a parser again and again, as a stream of what it finds.+- `parseArray`: a parser on one array that holds the whole input.++Each takes the largest number of bytes the parser may be given.++## What the parsers must be like++- For `parseBreak` and `parseMany`, a failure is taken to mean that the+ input is not all there yet. The parser must therefore fail on every+ proper prefix of what it accepts: it must end on something that tells its+ end, such as a delimiter. A parser that succeeds early, like "some+ digits", would stop at the end of an array with more digits to come. An+ error (`cut`, `err`) stops at once: use one where no further byte can+ help.+- For `parseBreakOn`, the delimiter must not occur inside what is parsed.++## Speed++On the head of an HTTP response of 241 bytes (`cabal bench`):++| | |+|---|---|+| flatparse alone, on the bytes | 0.58 μs |+| `parseBreak`, the head in one array | 0.60 μs |+| `parseBreak`, the head cut in three arrays | 1.17 μs |+| `parseBreakOn` the empty line, in one array | 0.93 μs |++On five thousand short lines, 28 kB, each parsed by `parseMany`:++| | |+|---|---|+| flatparse alone, one parser for all the lines | 81 μs |+| `parseMany`, the lines in one array | 237 μs |+| `parseMany`, in arrays of 4096 bytes | 226 μs |++With `parseBreak` the input is parsed again from its start at each array:+cheap for what fits in a few arrays, wasteful for long inputs, which+`parseBreakOn` parses once.
+ bench/Main.hs view
@@ -0,0 +1,108 @@+-- | What it costs to run a flatparse parser on a stream of arrays, over+-- running it on one piece of bytes: the head of an HTTP response, whole+-- in one array as it mostly comes, and cut in three; and many short lines+-- parsed one after the other, as from a file.+module Main (main) where++import Data.ByteString (ByteString, dropWhileEnd)+import Data.ByteString qualified as BS (drop, dropWhile, null, splitAt, take)+import Data.ByteString.Char8 (pack)+import Data.ByteString.Char8 qualified as BS8 (map)+import Data.Char (chr, isDigit)+import Data.Functor.Identity (Identity (..))+import Data.Word (Word8)+import FlatParse.Basic (Parser, Result (OK), anyAsciiDecimalInt, anyWord8,+ byteString, byteStringOf, eof, failed, many, runParser,+ skipMany, skipSatisfyAscii, skipSome, word8, (<|>))+import Streamly.Data.Array (Array)+import Streamly.Data.Fold qualified as F (foldl')+import Streamly.Data.Stream (fold, fromList)+import Streamly.Data.StreamK (StreamK, fromFoldable)+import Streamly.External.ByteString (toArray)+import Streamly.External.FlatParse (ParseError, parseArray, parseBreak,+ parseBreakOn, parseMany)+import Test.Tasty.Bench (bench, bgroup, defaultMain, nf)++main :: IO ()+main =+ defaultMain+ [ bgroup+ "HTTP response head, 241 bytes"+ [ bench "flatparse alone, on the bytes" (nf alone httpHead)+ , bench "parseArray, on one array" (nf (either (const Nothing) Just . parseArray httpFlat) whole)+ , bench "parseBreak, the head in one array" (nf (through (parseBreak 65536 httpFlat)) [whole])+ , bench "parseBreak, the head cut in three arrays" (nf (through (parseBreak 65536 httpFlat)) thirds)+ , bench "parseBreakOn the empty line, in one array" (nf (through (parseBreakOn "\r\n\r\n" 65536 httpFlat)) [whole])+ , bench "parseBreakOn the empty line, cut in three arrays" (nf (through (parseBreakOn "\r\n\r\n" 65536 httpFlat)) thirds)+ ]+ , bgroup+ "5000 short lines, 28 kB"+ [ bench "flatparse alone, one parser for all the lines" (nf allLines linesBytes)+ , bench "parseMany, within 64 bytes, one array" (nf (total 64) [toArray linesBytes])+ , bench "parseMany, within 64 bytes, arrays of 4096 bytes" (nf (total 64) (map toArray (pieces 4096 linesBytes)))+ , bench "parseMany, within 64 bytes, arrays of 16 bytes" (nf (total 64) (map toArray (pieces 16 linesBytes)))+ , bench "parseMany, without a limit, one array" (nf (total maxBound) [toArray linesBytes])+ ]+ ]+ where+ allLines bytes = case runParser (sumLines 0) bytes of+ OK found _ -> found+ _ -> -1+ sumLines !sofar = (line >>= \found -> sumLines (sofar + found)) <|> (sofar <$ eof)+ total :: Int -> [Array Word8] -> Int+ total limit arrays = runIdentity (fold (F.foldl' (\sofar -> either (const (-1)) (sofar +)) 0) (parseMany limit line (fromList arrays)))+ alone bytes = case runParser httpFlat bytes of+ OK found _ -> Just found+ _ -> Nothing+ whole = toArray (httpHead <> "the start of a body")+ thirds = map toArray [BS.take 80 httpHead, BS.take 80 (BS.drop 80 httpHead), BS.drop 160 httpHead <> "the start of a body"]+ through :: (StreamK Identity (Array Word8) -> Identity (Either (ParseError ()) a, StreamK Identity (Array Word8))) -> [Array Word8] -> Maybe a+ through driver arrays = either (const Nothing) Just (fst (runIdentity (driver (fromFoldable arrays))))++-- | The head of an image response, as a Roon Server sent it.+httpHead :: ByteString+httpHead =+ "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nEtag: 96f45bde867a0aaf6df5ff2f47526aa6916ed3ff:6a8027a650750256c151c53e7ee9017f\r\n\+ \Accept-Ranges: bytes\r\nCache-Control: max-age=21600, public\r\nContent-Type: image/jpeg\r\nContent-Length: 43183\r\n\r\n"++httpFlat :: Parser () (Int, ByteString, [(ByteString, ByteString)])+httpFlat = do+ byteString "HTTP/1."+ skipSatisfyAscii isDigit+ word8 32+ status <- anyAsciiDecimalInt+ reason <- restOfLine+ found <- many headerLine+ lineEnd+ pure (status, reason, found)+ where+ headerLine = do+ name <- byteStringOf (skipSome (skipSatisfyAscii tokenChar))+ word8 58+ value <- restOfLine+ pure (BS8.map lower name, value)+ restOfLine = do+ rest <- byteStringOf (skipMany (anyWord8 >>= \byte -> if byte == 10 then failed else pure ()))+ word8 10+ pure (BS.dropWhile blank (dropWhileEnd blank rest))+ lineEnd = skipMany (word8 13) *> word8 10+ blank byte = byte == 32 || byte == 9 || byte == 13+ tokenChar c = c > ' ' && c < '\DEL' && c /= ':'+ lower c = if c >= 'A' && c <= 'Z' then chr (fromEnum c + 32) else c++-- | Five thousand signed numbers, each on its line.+linesBytes :: ByteString+linesBytes = pack (concat [(if even n then 'R' else 'L') : show (n * 37 `mod` 1000) <> "\n" | n <- [1 .. 5000 :: Int]])++-- | A letter for the sign, a decimal number and a line feed.+line :: Parser () Int+line = do+ sign <- (1 <$ word8 82) <|> ((-1) <$ word8 76)+ found <- anyAsciiDecimalInt+ word8 10+ pure (sign * found)++pieces :: Int -> ByteString -> [ByteString]+pieces size bytes+ | BS.null bytes = []+ | otherwise = let (front, back) = BS.splitAt size bytes in front : pieces size back
+ src/Streamly/External/FlatParse.hs view
@@ -0,0 +1,197 @@+-- |+-- Module : Streamly.External.FlatParse+-- Description : flatparse parsers on streams of byte arrays+-- License : BSD-3-Clause+--+-- A flatparse parser is fast, but it reads one piece of bytes and cannot+-- stop to wait for more. Bytes that come from a socket or a file come in+-- arrays cut anywhere. The functions here stand between the two: they+-- gather the arrays of a stream until a parser has what it needs, within a+-- size, and give the stream that follows what was parsed.+--+-- > {-# LANGUAGE OverloadedStrings #-}+-- > import FlatParse.Basic qualified as FP+-- > import Streamly.Data.Stream qualified as Stream+-- > import Streamly.External.FlatParse+-- >+-- > -- A decimal number on a line of its own.+-- > line :: FP.Parser () Int+-- > line = FP.anyAsciiDecimalInt <* FP.byteString "\n"+-- >+-- > numbers :: Monad m => Stream.Stream m (Array Word8) -> Stream.Stream m (Either (ParseError ()) Int)+-- > numbers = parseMany 100 line+--+-- = What the parsers must be like+--+-- Two ways to gather the input, two requirements:+--+-- * 'parseBreak' tries the parser again each time more bytes have come. A+-- failure ('FP.Fail') is taken to mean that the input is not all there+-- yet, so the parser __must fail on every proper prefix of what it+-- accepts__: it must end on something that tells its end, such as a+-- delimiter. A parser that succeeds early, like \"some digits\", would+-- stop at the end of an array with more digits to come. An error+-- ('FP.Err', as 'FP.cut' and 'FP.err' make) stops at once: use one where+-- no further byte can help. The input is parsed again from its start at+-- each attempt, which is cheap for what fits in a few arrays, and+-- wasteful for long inputs.+--+-- * 'parseBreakOn' waits for a delimiter and runs the parser once, on the+-- bytes up to it. The parser need not fail on prefixes, and nothing is+-- parsed twice, but the delimiter must not occur inside what is parsed.+--+-- A flatparse parser cannot be turned into a Streamly @Parser@, to be put+-- together with others: the results here come with the rest of the+-- stream instead, to go on from.+module Streamly.External.FlatParse+ ( -- * Errors+ ParseError (..)++ -- * One piece of input+ , parseArray++ -- * A stream of arrays+ , parseBreak+ , parse+ , parseBreakOn+ , parseMany+ ) where++import Data.ByteString (ByteString, breakSubstring, empty)+import Data.ByteString qualified as BS (drop, length, null, splitAt, take)+import Data.Word (Word8)+import FlatParse.Basic (Parser, Result (Err, Fail, OK), runParser)+import Streamly.Data.Array (Array)+import Streamly.Data.Stream (Stream, unfoldrM)+import Streamly.Data.StreamK (StreamK, cons, fromStream, nil, uncons)+import Streamly.External.ByteString (fromArray, toArray)++-- | Why a parser gave nothing.+data ParseError e+ = -- | The parser failed, and no more input could change that: the+ -- stream had ended.+ Mismatch+ | -- | The parser stopped on an error of its own.+ ParserError e+ | -- | The parser would need more than the bytes allowed: the limit.+ TooLong Int+ deriving stock (Eq, Show)++-- | Run a parser on one array, which holds the whole input. What the+-- parser did not read is left out.+parseArray :: Parser e a -> Array Word8 -> Either (ParseError e) a+parseArray parser array = case runParser parser (fromArray array) of+ OK found _ -> Right found+ Fail -> Left Mismatch+ Err problem -> Left (ParserError problem)++-- | Run a parser on the start of a stream of arrays, and give the stream+-- that follows what it read. The parser is given at most a number of+-- bytes; it is tried again as arrays come, so it must fail on every+-- proper prefix of what it accepts (see the top of this module).+--+-- After a failure the stream given back is the input from its start,+-- nothing lost.+parseBreak :: Monad m => Int -> Parser e a -> StreamK m (Array Word8) -> m (Either (ParseError e) a, StreamK m (Array Word8))+parseBreak limit parser input = do+ (outcome, left, rest) <- advance limit parser empty input+ pure (outcome, prepend left rest)+{-# INLINE parseBreak #-}++-- | Run a parser on bytes already taken from a stream of arrays, followed+-- by that stream: the result, the bytes taken that the parser did not+-- read, and the stream after them. Nothing is copied unless the parser+-- needs bytes of a further array: those left over are a slice of those+-- given. After a failure the bytes given back are all those taken.+advance :: Monad m => Int -> Parser e a -> ByteString -> StreamK m (Array Word8) -> m (Either (ParseError e) a, ByteString, StreamK m (Array Word8))+advance limit parser taken input+ | BS.null taken = gather taken input+ | otherwise = attempt False taken input+ where+ -- Try the parser on what has come so far, no further than the limit.+ attempt atEnd gathered rest =+ let allowed = BS.take limit gathered+ in case runParser parser allowed of+ OK found leftover -> pure (Right found, BS.drop (BS.length allowed - BS.length leftover) gathered, rest)+ Err problem -> pure (Left (ParserError problem), gathered, rest)+ Fail+ -- With exactly as many bytes as allowed, whether the input+ -- is too long shows with the next array, or with the end.+ | BS.length gathered > limit -> pure (Left (TooLong limit), gathered, rest)+ | atEnd -> pure (Left Mismatch, gathered, rest)+ | otherwise -> gather gathered rest+ -- More input may help: add the next array that holds something.+ gather gathered rest =+ uncons rest >>= \case+ Nothing -> attempt True gathered nil+ Just (array, further)+ | BS.null bytes -> gather gathered further+ | otherwise -> attempt False (gathered <> bytes) further+ where+ bytes = fromArray array+{-# INLINE advance #-}++-- | Like 'parseBreak', without the stream that follows.+parse :: Monad m => Int -> Parser e a -> StreamK m (Array Word8) -> m (Either (ParseError e) a)+parse limit parser input = fst <$> parseBreak limit parser input++-- | Wait for a delimiter in a stream of arrays, run a parser once on the+-- bytes up to its end, delimiter included, and give the stream that+-- follows. The delimiter is looked for in the first bytes of the stream,+-- no further than a number of them.+--+-- After a failure the stream given back is the input from its start.+parseBreakOn :: Monad m => ByteString -> Int -> Parser e a -> StreamK m (Array Word8) -> m (Either (ParseError e) a, StreamK m (Array Word8))+parseBreakOn delimiter limit parser = gather empty+ where+ gather buffered input = case breakSubstring delimiter (BS.take limit buffered) of+ (before, found)+ | not (BS.null delimiter) && not (BS.null found) ->+ let size = BS.length before + BS.length delimiter+ (block, after) = BS.splitAt size buffered+ in pure $ case runParser parser block of+ OK value _ -> (Right value, prepend after input)+ Fail -> (Left Mismatch, prepend buffered input)+ Err problem -> (Left (ParserError problem), prepend buffered input)+ | BS.length buffered >= limit -> pure (Left (TooLong limit), prepend buffered input)+ | otherwise ->+ uncons input >>= \case+ Nothing -> pure (Left Mismatch, prepend buffered nil)+ Just (array, rest) -> gather (buffered <> fromArray array) rest++-- | Run a parser again and again on a stream of arrays, as 'parseBreak'+-- does, and give what it finds. The stream ends with the input, or after+-- the first error, which is its last element.+parseMany :: Monad m => Int -> Parser e a -> Stream m (Array Word8) -> Stream m (Either (ParseError e) a)+parseMany limit parser = unfoldrM next . Just . (,) empty . fromStream+ where+ -- The bytes taken from the stream and not parsed yet, and the stream+ -- after them: they are kept as they are from one result to the next,+ -- not put back into the stream.+ next Nothing = pure Nothing+ next (Just (taken, input))+ | BS.null taken =+ nonEmpty input >>= \case+ Nothing -> pure Nothing+ Just (bytes, rest) -> result bytes rest+ | otherwise = result taken input+ result taken input =+ advance limit parser taken input >>= \case+ (Right found, left, rest) -> pure (Just (Right found, Just (left, rest)))+ (Left problem, _, _) -> pure (Just (Left problem, Nothing))+ -- The first array of the stream that holds something, if any.+ nonEmpty input =+ uncons input >>= \case+ Nothing -> pure Nothing+ Just (array, rest)+ | BS.null bytes -> nonEmpty rest+ | otherwise -> pure (Just (bytes, rest))+ where+ bytes = fromArray array+{-# INLINE parseMany #-}++-- | A stream with bytes put back before it.+prepend :: ByteString -> StreamK m (Array Word8) -> StreamK m (Array Word8)+prepend bytes stream+ | BS.null bytes = stream+ | otherwise = cons (toArray bytes) stream
+ streamly-flatparse.cabal view
@@ -0,0 +1,91 @@+cabal-version: 3.12+name: streamly-flatparse+version: 0.1.0.0+synopsis: Run flatparse parsers on Streamly streams of byte arrays+description:+ flatparse parsers are fast, but need their whole input in one piece.+ This library runs them on a stream of byte arrays, as they come from a+ socket or a file: it gathers the arrays until the parser succeeds, or+ until a delimiter, within a size, and gives back the stream that follows+ what was parsed.++homepage: https://github.com/GuillaumedeVolpiano/streamly-flatparse+license: BSD-3-Clause+license-file: LICENSE+author: Xavier Dectot+maintainer: Xavier Dectot <xavier@wheredoibegin.fr>+category: Parsing, Streamly+build-type: Simple+tested-with: GHC ==9.8.4 || ==9.10.3 || ==9.12.4+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/GuillaumedeVolpiano/streamly-flatparse.git++common shared+ default-language: GHC2021+ default-extensions:+ DataKinds+ DerivingStrategies+ DisambiguateRecordFields+ DuplicateRecordFields+ ExplicitNamespaces+ GADTs+ LambdaCase+ MonoLocalBinds+ NoFieldSelectors+ OverloadedRecordDot+ OverloadedStrings+ RoleAnnotations++ ghc-options:+ -Wall -Wcompat -Wredundant-constraints -Wmissing-deriving-strategies+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules: Streamly.External.FlatParse+ build-depends:+ , base >=4.19 && <4.22+ , bytestring ^>=0.12+ , flatparse ^>=0.5+ , streamly-bytestring ^>=0.2.3+ , streamly-core ^>=0.3.3++test-suite streamly-flatparse-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , base+ , bytestring+ , flatparse+ , streamly-bytestring+ , streamly-core+ , streamly-flatparse+ , tasty ^>=1.5+ , tasty-hunit ^>=0.10+ , tasty-quickcheck ^>=0.11++-- What gathering the arrays costs, over flatparse alone. Run it by hand,+-- with cabal bench.+benchmark streamly-flatparse-bench+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: bench+ main-is: Main.hs+ ghc-options: -threaded+ build-depends:+ , base+ , bytestring+ , flatparse+ , streamly-bytestring+ , streamly-core+ , streamly-flatparse+ , tasty-bench >=0.4 && <0.6
+ test/Main.hs view
@@ -0,0 +1,134 @@+-- | flatparse parsers on streams of arrays cut anywhere.+module Main (main) where++import Data.ByteString (ByteString)+import Data.ByteString qualified as BS (concat, null, splitAt)+import Data.ByteString.Char8 (pack)+import Data.Functor.Identity (Identity (..))+import Data.Word (Word8)+import FlatParse.Basic (Parser, anyAsciiDecimalInt, anyWord8, byteStringOf, err,+ optional_, skipMany, skipSatisfyAscii, skipSome, word8)+import Streamly.Data.Array (Array)+import Streamly.Data.Stream (fromList, toList)+import Streamly.Data.StreamK (StreamK, fromStream, toStream)+import Streamly.External.ByteString (fromArray, toArray)+import Streamly.External.FlatParse (ParseError (..), parse, parseArray,+ parseBreak, parseBreakOn, parseMany)+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))+import Test.Tasty.QuickCheck (Positive (..), testProperty, (===))++main :: IO ()+main = defaultMain tests++pieces :: Int -> ByteString -> [ByteString]+pieces size bytes+ | BS.null bytes = []+ | otherwise = let (front, back) = BS.splitAt size bytes in front : pieces size back++-- | Bytes as a stream of arrays of a size.+cut :: Int -> ByteString -> StreamK Identity (Array Word8)+cut size = fromStream . fromList . map toArray . pieces size++-- | The result of a parse, with the bytes of the stream given back.+broken :: (Either (ParseError e) a, StreamK Identity (Array Word8)) -> (Either (ParseError e) a, ByteString)+broken (outcome, rest) = (outcome, BS.concat (map fromArray (runIdentity (toList (toStream rest)))))++-- | A name, a colon, a decimal number and a line feed. A second colon is+-- an error that no further byte can mend.+entry :: Parser String (ByteString, Int)+entry = do+ name <- byteStringOf (skipSome (skipSatisfyAscii (\c -> c >= 'a' && c <= 'z')))+ word8 58+ optional_ (word8 58 *> err "two colons")+ value <- anyAsciiDecimalInt+ word8 10+ pure (name, value)++-- | Some digits: a parser that succeeds on a prefix of what it accepts.+digits :: Parser () Int+digits = anyAsciiDecimalInt++tests :: TestTree+tests =+ testGroup+ "streamly-flatparse"+ [ testGroup+ "parseArray"+ [ testCase "the whole input in one array" $ do+ parseArray entry (toArray "volume:42\nrest") @?= Right ("volume", 42)+ parseArray entry (toArray "volume:42") @?= Left Mismatch+ parseArray entry (toArray "volume::42\n") @?= Left (ParserError "two colons")+ ]+ , testGroup+ "parseBreak"+ [ testProperty "the result and what follows do not depend on how the bytes are cut" $ \(Positive size) ->+ broken (runIdentity (parseBreak 100 entry (cut size "volume:42\nbalance:7\ntail")))+ === (Right ("volume", 42), "balance:7\ntail")+ , testProperty "a failure gives the whole input back, however it is cut" $ \(Positive size) ->+ broken (runIdentity (parseBreak 100 entry (cut size "Volume:42\n")))+ === (Left Mismatch, "Volume:42\n")+ , testProperty "an error of the parser stops at once, the input given back" $ \(Positive size) ->+ broken (runIdentity (parseBreak 100 entry (cut size "volume::42\nbalance:7\n")))+ === (Left (ParserError "two colons"), "volume::42\nbalance:7\n")+ , testCase "an error stops before the rest of the stream is read" $ do+ let endless = fromStream (fromList (map toArray ("a::" : repeat "x")))+ fst (runIdentity (parseBreak 1000 entry endless)) @?= Left (ParserError "two colons")+ , testProperty "the parser is given no more than the limit, exactly" $ \(Positive size) ->+ let input = "volume:42\nmore"+ in ( fst (runIdentity (parseBreak 10 entry (cut size input)))+ , broken (runIdentity (parseBreak 9 entry (cut size input)))+ )+ === (Right ("volume", 42), (Left (TooLong 9), input))+ , testCase "input that ends before the parser is done" $ do+ broken (runIdentity (parseBreak 100 entry (cut 3 "volume:4"))) @?= (Left Mismatch, "volume:4")+ broken (runIdentity (parseBreak 100 entry (cut 3 ""))) @?= (Left Mismatch, "")+ -- Exactly as many bytes as allowed, and no more to come.+ broken (runIdentity (parseBreak 8 entry (cut 3 "volume:4"))) @?= (Left Mismatch, "volume:4")+ , testCase "endless input that never fits" $ do+ let endless = fromStream (fromList (map toArray (repeat "abc")))+ fst (runIdentity (parseBreak 50 entry endless)) @?= Left (TooLong 50)+ , testCase "empty arrays are passed over" $+ broken (runIdentity (parseBreak 100 entry (fromStream (fromList (map toArray ["", "vol", "", "ume:4", "", "2\nx"])))))+ @?= (Right ("volume", 42), "x")+ , testCase "a parser that succeeds on a prefix stops too early: what the documentation warns of" $ do+ fst (runIdentity (parseBreak 100 digits (cut 2 "12345 "))) @?= Right 12+ fst (runIdentity (parseBreak 100 digits (cut 100 "12345 "))) @?= Right 12345+ , testCase "parse gives the result alone" $+ runIdentity (parse 100 entry (cut 4 "volume:42\n")) @?= Right ("volume", 42)+ ]+ , testGroup+ "parseBreakOn"+ [ testProperty "the parser runs on the bytes up to the delimiter, however they are cut" $ \(Positive size) ->+ broken (runIdentity (parseBreakOn "\r\n\r\n" 100 (byteStringOf (skipMany anyWord8) :: Parser () ByteString) (cut size "a: b\r\nc: d\r\n\r\nbody")))+ === (Right "a: b\r\nc: d\r\n\r\n", "body")+ , testCase "a parser that succeeds on a prefix is safe here" $+ broken (runIdentity (parseBreakOn " " 100 digits (cut 2 "12345 678"))) @?= (Right 12345, "678")+ , testProperty "no delimiter within the limit, or before the end" $ \(Positive size) ->+ ( broken (runIdentity (parseBreakOn "\n\n" 5 digits (cut size "123456\n\n")))+ , broken (runIdentity (parseBreakOn "\n\n" 100 digits (cut size "123456\n")))+ )+ === ((Left (TooLong 5), "123456\n\n"), (Left Mismatch, "123456\n"))+ , testCase "a delimiter that ends exactly at the limit is found" $+ broken (runIdentity (parseBreakOn "\n\n" 5 digits (cut 2 "123\n\nx"))) @?= (Right 123, "x")+ , testCase "a parser that fails, or errs, on the block gives the input back" $ do+ broken (runIdentity (parseBreakOn "\n" 100 entry (cut 3 "Volume:1\nx"))) @?= (Left Mismatch, "Volume:1\nx")+ broken (runIdentity (parseBreakOn "\n" 100 entry (cut 3 "volume::1\nx"))) @?= (Left (ParserError "two colons"), "volume::1\nx")+ ]+ , testGroup+ "parseMany"+ [ testProperty "every entry of a stream, however it is cut" $ \(Positive size) ->+ let input = BS.concat [pack ("name:" <> show n <> "\n") | n <- [1 .. 50 :: Int]]+ in runIdentity (toList (parseMany 100 entry (toStream (cut size input))))+ === [Right ("name", n) | n <- [1 .. 50]]+ , testCase "the first error is the last element" $+ runIdentity (toList (parseMany 100 entry (toStream (cut 4 "a:1\nb::2\nc:3\n"))))+ @?= [Right ("a", 1), Left (ParserError "two colons")]+ , testCase "input cut short ends on a mismatch, and empty input gives nothing" $ do+ runIdentity (toList (parseMany 100 entry (toStream (cut 4 "a:1\nb:")))) @?= [Right ("a", 1), Left Mismatch]+ runIdentity (toList (parseMany 100 entry (toStream (cut 4 "")))) @?= []+ , testProperty "an entry longer than the limit is the last element, however the stream is cut" $ \(Positive size) ->+ runIdentity (toList (parseMany 8 entry (toStream (cut size "a:1\nb:2\nvolume:30\nc:3\n"))))+ === [Right ("a", 1), Right ("b", 2), Left (TooLong 8)]+ ]+ ]