module Control.Proxy.Safe.Prelude (
withFile,
readFileS,
writeFileD
) where
import Control.Proxy (Proxy(request, respond), Producer)
import Control.Proxy.Safe.Core (SafeIO, ExceptionP, bracket, tryIO)
import qualified System.IO as IO
withFile
:: (Monad m, Proxy p)
=> (forall x . SafeIO x -> m x)
-> FilePath
-> IO.IOMode
-> (IO.Handle -> ExceptionP p a' a b' b m r)
-> ExceptionP p a' a b' b m r
withFile morph file ioMode = bracket morph (IO.openFile file ioMode) IO.hClose
readFileS
:: (Proxy p) => FilePath -> () -> Producer (ExceptionP p) String SafeIO ()
readFileS file () = withFile id file IO.ReadMode $ \handle -> do
let go = do
eof <- tryIO $ IO.hIsEOF handle
if eof
then return ()
else do
str <- tryIO $ IO.hGetLine handle
respond str
go
go
writeFileD
:: (Proxy p) => FilePath -> x -> ExceptionP p x String x String SafeIO r
writeFileD file x0 = do
withFile id file IO.WriteMode $ \handle -> do
let go x = do
str <- request x
tryIO $ IO.hPutStrLn handle str
x2 <- respond str
go x2
go x0