0
|
1 |
{-# LANGUAGE BangPatterns #-} |
|
2 |
|
|
3 |
module System.IO.Streams.Concurrent.Unagi |
|
4 |
( -- * Channel conversions |
2
|
5 |
inputToChan |
0
|
6 |
, chanToInput |
|
7 |
, chanToOutput |
|
8 |
, makeChanPipe |
|
9 |
) where |
|
10 |
|
|
11 |
|
|
12 |
------------------------------------------------------------------------------ |
|
13 |
import Control.Applicative ((<$>), (<*>)) |
|
14 |
import Control.Concurrent.Chan.Unagi (InChan, OutChan, newChan, |
|
15 |
readChan, writeChan) |
|
16 |
import Prelude hiding (read) |
|
17 |
import System.IO.Streams.Internal (InputStream, OutputStream, |
|
18 |
makeInputStream, |
|
19 |
makeOutputStream, read) |
|
20 |
|
|
21 |
|
|
22 |
|
|
23 |
------------------------------------------------------------------------------ |
|
24 |
-- | Writes the contents of an input stream to a channel until the input stream |
|
25 |
-- yields end-of-stream. |
|
26 |
inputToChan :: InputStream a -> InChan (Maybe a) -> IO () |
|
27 |
inputToChan is ch = go |
|
28 |
where |
|
29 |
go = do |
|
30 |
mb <- read is |
|
31 |
writeChan ch mb |
|
32 |
maybe (return $! ()) (const go) mb |
|
33 |
|
|
34 |
|
|
35 |
------------------------------------------------------------------------------ |
|
36 |
-- | Turns an 'OutChan' into an input stream. |
|
37 |
-- |
|
38 |
chanToInput :: OutChan (Maybe a) -> IO (InputStream a) |
|
39 |
chanToInput ch = makeInputStream $! readChan ch |
|
40 |
|
|
41 |
|
|
42 |
------------------------------------------------------------------------------ |
|
43 |
-- | Turns an 'InChan' into an output stream. |
|
44 |
-- |
|
45 |
chanToOutput :: InChan (Maybe a) -> IO (OutputStream a) |
|
46 |
chanToOutput = makeOutputStream . writeChan |
|
47 |
|
|
48 |
|
|
49 |
-------------------------------------------------------------------------------- |
|
50 |
-- | Create a new pair of streams using an underlying 'Chan'. Everything written |
|
51 |
-- to the 'OutputStream' will appear as-is on the 'InputStream'. |
|
52 |
-- |
|
53 |
-- Since reading from the 'InputStream' and writing to the 'OutputStream' are |
|
54 |
-- blocking calls, be sure to do so in different threads. |
|
55 |
makeChanPipe :: IO (InputStream a, OutputStream a) |
|
56 |
makeChanPipe = do |
|
57 |
(inChan, outChan) <- newChan |
|
58 |
(,) <$> chanToInput outChan <*> chanToOutput inChan |