@@ -18,6 +18,9 @@ module Streamly.Internal.Data.Parser.ParserD
1818 , Initial (..)
1919 , rmapM
2020
21+ -- * Downgrade to Fold
22+ , toFold
23+
2124 -- First order parsers
2225 -- * Accumulators
2326 , fromFold
@@ -162,7 +165,7 @@ module Streamly.Internal.Data.Parser.ParserD
162165 )
163166where
164167
165−import Control.Exception (assert)
168+import Control.Exception (assert, Exception)
166169import Control.Monad.Catch (MonadCatch, MonadThrow(..))
167170import Fusion.Plugin.Types (Fuse(..))
168171import Streamly.Internal.Data.Fold.Type (Fold(..))
@@ -184,6 +187,48 @@ import Streamly.Internal.Data.Parser.ParserD.Type
184187-- >>> import qualified Streamly.Data.Fold as Fold
185188-- >>> import qualified Streamly.Internal.Data.Parser as Parser
186189
190+-------------------------------------------------------------------------------
191+-- Downgrade a parser to a Fold
192+-------------------------------------------------------------------------------
193+
194+data ParserToFoldError =
195+ InitialError String
196+ | PartialError Int
197+ | ContinueError Int
198+ | DoneError Int
199+ | ErrorError String
200+ deriving Show
201+
202+instance Exception ParserToFoldError
203+
204+-- | See 'Streamly.Internal.Data.Parser.toFold'.
205+--
206+-- /Internal/
207+--
208+{-# INLINE toFold #-}
209+toFold :: MonadThrow m => Parser m a b -> Fold m a b
210+toFold (Parser pstep pinitial pextract) = Fold step initial pextract
211+
212+ where
213+
214+ initial = do
215+ r <- pinitial
216+ case r of
217+ IPartial s -> return $ FL.Partial s
218+ IDone b -> return $ FL.Done b
219+ IError err -> throwM $ InitialError err
220+
221+ step st a = do
222+ r <- pstep st a
223+ case r of
224+ Partial 0 s -> return $ FL.Partial s
225+ Continue 0 s -> return $ FL.Partial s
226+ Done 0 b -> return $ FL.Done b
227+ Partial n _ -> throwM $ PartialError n
228+ Continue n _ -> throwM $ ContinueError n
229+ Done n _ -> throwM $ DoneError n
230+ Error err -> throwM $ ErrorError err
231+
187232-------------------------------------------------------------------------------
188233-- Upgrade folds to parses
189234-------------------------------------------------------------------------------