Created
May 10, 2020 10:16
-
-
Save sorki/de7a9636632b5d32a44e3ce39a3ca801 to your computer and use it in GitHub Desktop.
zreChan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Network.ZRE.Chan ( | |
zreChan | |
) where | |
import Control.Monad.IO.Class (liftIO) | |
import Control.Concurrent.STM (TChan) | |
import Data.Serialize (Serialize) | |
import Data.ZRE (Group) | |
import qualified Control.Concurrent | |
import qualified Control.Concurrent.Async.Lifted | |
import qualified Control.Concurrent.STM | |
import qualified Control.Monad | |
import qualified Data.Serialize | |
import qualified Network.ZRE | |
-- | Typed ZRE channel using two groups | |
-- input -> outputGroup for transfering encoded data | |
-- inputGroup -> output for receiving decoded data | |
zreChan :: (Serialize input, Serialize output) | |
=> Group | |
-> Group | |
-> IO ( TChan input | |
, TChan output) | |
zreChan outputGroup inputGroup = do | |
chanInput <- Control.Concurrent.STM.newTChanIO | |
chanOutput <- Control.Concurrent.STM.newTChanIO | |
_ <- Control.Concurrent.forkIO $ Network.ZRE.runZre $ do | |
-- shout input to outputGroup | |
Control.Monad.void | |
$ Control.Concurrent.Async.Lifted.async | |
$ Control.Monad.forever | |
$ do | |
out <- liftIO | |
$ Control.Concurrent.STM.atomically | |
$ Control.Concurrent.STM.readTChan chanInput | |
Network.ZRE.zshout outputGroup | |
$ Data.Serialize.encode out | |
-- receive on inputGroup and forward to output | |
Network.ZRE.zjoin inputGroup | |
Network.ZRE.zrecvShouts | |
$ Network.ZRE.whenDecodes Data.Serialize.decode | |
$ liftIO | |
. Control.Concurrent.STM.atomically | |
. Control.Concurrent.STM.writeTChan chanOutput | |
return (chanInput, chanOutput) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment