{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE LinearTypes #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE QualifiedDo #-}
{-# LANGUAGE RecordWildCards #-}

-- | This module contains functions for interoperating with other
-- streaming libraries.
module Streaming.Internal.Interop
  ( -- * Interoperating with other streaming libraries
    reread
  ) where

import Streaming.Internal.Type
import Streaming.Internal.Produce
import Data.Unrestricted.Linear
import Prelude.Linear (($))
import Prelude (Maybe(..))
import qualified Control.Functor.Linear as Control

{-| Read an @IORef (Maybe a)@ or a similar device until it reads @Nothing@.
    @reread@ provides convenient exit from the @io-streams@ library

> reread readIORef    :: IORef (Maybe a) -> Stream (Of a) IO ()
> reread Streams.read :: System.IO.Streams.InputStream a -> Stream (Of a) IO ()
-}
reread :: Control.Monad m =>
  (s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
reread :: forall (m :: * -> *) s a.
Monad m =>
(s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
reread s -> m (Ur (Maybe a))
f s
s = (s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
forall (m :: * -> *) s a.
Monad m =>
(s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
reread' s -> m (Ur (Maybe a))
f s
s
  where
    reread' :: Control.Monad m =>
      (s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
    reread' :: forall (m :: * -> *) s a.
Monad m =>
(s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
reread' s -> m (Ur (Maybe a))
f s
s = m (Stream (Of a) m ()) %1 -> Stream (Of a) m ()
forall (m :: * -> *) (f :: * -> *) r.
m (Stream f m r) -> Stream f m r
Effect (m (Stream (Of a) m ()) %1 -> Stream (Of a) m ())
%1 -> m (Stream (Of a) m ()) %1 -> Stream (Of a) m ()
forall a b. (a %1 -> b) %1 -> a %1 -> b
$ Control.do
      Ur Maybe a
maybeA <- s -> m (Ur (Maybe a))
f s
s
      case Maybe a
maybeA of
        Maybe a
Nothing -> Stream (Of a) m () %1 -> m (Stream (Of a) m ())
forall (m :: * -> *) a. Monad m => a %1 -> m a
Control.return (Stream (Of a) m () %1 -> m (Stream (Of a) m ()))
%1 -> Stream (Of a) m () %1 -> m (Stream (Of a) m ())
forall a b. (a %1 -> b) %1 -> a %1 -> b
$ () -> Stream (Of a) m ()
forall r (f :: * -> *) (m :: * -> *). r -> Stream f m r
Return ()
        Just a
a -> Stream (Of a) m () %1 -> m (Stream (Of a) m ())
forall (m :: * -> *) a. Monad m => a %1 -> m a
Control.return (Stream (Of a) m () %1 -> m (Stream (Of a) m ()))
%1 -> Stream (Of a) m () %1 -> m (Stream (Of a) m ())
forall a b. (a %1 -> b) %1 -> a %1 -> b
$ (a -> Stream (Of a) m ()
forall (m :: * -> *) a. Monad m => a -> Stream (Of a) m ()
yield a
a Stream (Of a) m ()
%1 -> Stream (Of a) m () %1 -> Stream (Of a) m ()
forall (m :: * -> *) a. Monad m => m () %1 -> m a %1 -> m a
Control.>> (s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
forall (m :: * -> *) s a.
Monad m =>
(s -> m (Ur (Maybe a))) -> s -> Stream (Of a) m ()
reread s -> m (Ur (Maybe a))
f s
s)
{-# INLINABLE reread #-}