module Data.Attoparsec.ByteString.Run
  (
    parseStream, parseAndRestore, parseOnlyStrict, parseOnlyLazy,
    module Data.Attoparsec.Run,
  )
  where

import Data.Attoparsec.Run

import Control.Monad (unless)
import Control.Monad.State (evalState)
import Data.Attoparsec.ByteString (parseWith, Parser)
import Data.ByteString (ByteString, null)
import qualified Data.ByteString.Lazy as Lazy
import Prelude (($), (<$>), pure, mempty, Monad, Either)

parseOnlyStrict :: ByteString -> Parser a -> Either ParseError a
parseOnlyStrict :: forall a. ByteString -> Parser a -> Either ParseError a
parseOnlyStrict ByteString
x Parser a
p = forall s a. State s a -> s -> a
evalState (forall (m :: * -> *) a.
Monad m =>
RestorableInput m ByteString -> Parser a -> m (Either ParseError a)
parseAndRestore forall i (m :: * -> *).
(Monoid i, MonadState [i] m) =>
RestorableInput m i
inputState Parser a
p) [ByteString
x]

parseOnlyLazy :: Lazy.ByteString -> Parser a -> Either ParseError a
parseOnlyLazy :: forall a. ByteString -> Parser a -> Either ParseError a
parseOnlyLazy ByteString
x Parser a
p = forall s a. State s a -> s -> a
evalState (forall (m :: * -> *) a.
Monad m =>
RestorableInput m ByteString -> Parser a -> m (Either ParseError a)
parseAndRestore forall i (m :: * -> *).
(Monoid i, MonadState [i] m) =>
RestorableInput m i
inputState Parser a
p) (ByteString -> [ByteString]
Lazy.toChunks ByteString
x)

parseStream :: Monad m =>
    BufferedInput m ByteString -> Parser a -> m (FinalResult ByteString a)
parseStream :: forall (m :: * -> *) a.
Monad m =>
BufferedInput m ByteString
-> Parser a -> m (FinalResult ByteString a)
parseStream (BufferedInput ByteString
initial m ByteString
get) Parser a
p =
    forall i a. IResult i a -> FinalResult i a
finalizeResult forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) a.
Monad m =>
m ByteString -> Parser a -> ByteString -> m (Result a)
parseWith m ByteString
get Parser a
p ByteString
initial

parseAndRestore :: Monad m =>
    RestorableInput m ByteString -> Parser a -> m (Either ParseError a)
parseAndRestore :: forall (m :: * -> *) a.
Monad m =>
RestorableInput m ByteString -> Parser a -> m (Either ParseError a)
parseAndRestore (RestorableInput m ByteString
get ByteString -> m ()
restore) Parser a
p = do
    FinalResult ByteString
remainder Either ParseError a
value <- forall (m :: * -> *) a.
Monad m =>
BufferedInput m ByteString
-> Parser a -> m (FinalResult ByteString a)
parseStream (forall (m :: * -> *) i. i -> m i -> BufferedInput m i
BufferedInput forall a. Monoid a => a
mempty m ByteString
get) Parser a
p
    forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ByteString -> Bool
null ByteString
remainder) forall a b. (a -> b) -> a -> b
$ ByteString -> m ()
restore ByteString
remainder
    forall (f :: * -> *) a. Applicative f => a -> f a
pure Either ParseError a
value