src/System/IO/Streams/Concurrent/Unagi.hs
author Luke Hoersten <luke@hoersten.org>
Thu, 18 Dec 2014 10:56:53 -0600
changeset 3 400d49213290
parent 2 1760b7d150cf
child 4 1baf8e3b8ef2
permissions -rw-r--r--
Removed opaque type for chan dupping.

{-# LANGUAGE BangPatterns #-}

module System.IO.Streams.Concurrent.Unagi
       ( -- * Channel conversions
         inputToChan
       , chanToInput
       , chanToOutput
       , makeChanPipe
       ) where


------------------------------------------------------------------------------
import           Control.Applicative           ((<$>), (<*>))
import           Control.Concurrent.Chan.Unagi (InChan, OutChan, newChan,
                                                readChan, writeChan)
import           Prelude                       hiding (read)
import           System.IO.Streams.Internal    (InputStream, OutputStream,
                                                makeInputStream,
                                                makeOutputStream, read)



------------------------------------------------------------------------------
-- | Writes the contents of an input stream to a channel until the input stream
-- yields end-of-stream.
inputToChan :: InputStream a -> InChan (Maybe a) -> IO ()
inputToChan is ch = go
  where
    go = do
        mb <- read is
        writeChan ch mb
        maybe (return $! ()) (const go) mb


------------------------------------------------------------------------------
-- | Turns an 'OutChan' into an input stream.
--
chanToInput :: OutChan (Maybe a) -> IO (InputStream a)
chanToInput ch = makeInputStream $! readChan ch


------------------------------------------------------------------------------
-- | Turns an 'InChan' into an output stream.
--
chanToOutput :: InChan (Maybe a) -> IO (OutputStream a)
chanToOutput = makeOutputStream . writeChan


--------------------------------------------------------------------------------
-- | Create a new pair of streams using an underlying 'Chan'. Everything written
-- to the 'OutputStream' will appear as-is on the 'InputStream'.
--
-- Since reading from the 'InputStream' and writing to the 'OutputStream' are
-- blocking calls, be sure to do so in different threads.
makeChanPipe :: IO (InputStream a, OutputStream a)
makeChanPipe = do
    (inChan, outChan) <- newChan
    (,) <$> chanToInput outChan <*> chanToOutput inChan