{- |
Files with text content.
-}
module System.IO.Exception.TextFile where

import System.IO.Exception.File (EIO, close, )
import qualified Control.Monad.Exception.Synchronous  as Sync
import qualified Control.Monad.Exception.Asynchronous as Async
import Control.Monad.Exception.Synchronous (bracketT, )
import System.IO.Straight (SIO, ioToExceptionalSIO, unsafeInterleaveSIO, )
import System.IO (Handle, IOMode, )
import qualified System.IO as IO

import System.IO.Error (isEOFError, )
import Control.Exception (IOException)

import Prelude hiding (getChar)


open :: FilePath -> IOMode -> EIO Handle
open :: FilePath -> IOMode -> EIO Handle
open FilePath
name IOMode
mode =
   forall a. IO a -> ExceptionalT IOException SIO a
ioToExceptionalSIO forall a b. (a -> b) -> a -> b
$ FilePath -> IOMode -> IO Handle
IO.openFile FilePath
name IOMode
mode

with ::
   FilePath -> IOMode -> (Handle -> EIO r) -> EIO r
with :: forall r. FilePath -> IOMode -> (Handle -> EIO r) -> EIO r
with FilePath
name IOMode
mode =
   forall (m :: * -> *) e h a.
Monad m =>
ExceptionalT e m h
-> (h -> ExceptionalT e m ())
-> (h -> ExceptionalT e m a)
-> ExceptionalT e m a
bracketT (FilePath -> IOMode -> EIO Handle
open FilePath
name IOMode
mode) Handle -> EIO ()
close

getChar :: Handle -> EIO Char
getChar :: Handle -> EIO Char
getChar Handle
h =
   forall a. IO a -> ExceptionalT IOException SIO a
ioToExceptionalSIO forall a b. (a -> b) -> a -> b
$ Handle -> IO Char
IO.hGetChar Handle
h

getContentsSynchronous :: Handle -> EIO String
getContentsSynchronous :: Handle -> EIO FilePath
getContentsSynchronous Handle
h =
   forall (m :: * -> *) e0 e1 a b.
Monad m =>
(e0 -> Maybe e1)
-> (a -> b -> b) -> b -> ExceptionalT e0 m a -> ExceptionalT e1 m b
Sync.manyT
      -- candidate for toMaybe from utility-ht
      (\IOException
e -> if IOException -> Bool
isEOFError IOException
e then forall a. Maybe a
Nothing else forall a. a -> Maybe a
Just IOException
e)
      (:) [] (Handle -> EIO Char
getChar Handle
h)

{- |
This calls 'unsafeInterleaveIO'.
Maybe we should also attach 'unsafe' to this function name?
We should use the LazyIO type and manyT here.
-}
getContentsAsynchronous :: Handle -> SIO (Async.Exceptional IOException String)
getContentsAsynchronous :: Handle -> SIO (Exceptional IOException FilePath)
getContentsAsynchronous Handle
h =
   forall (m :: * -> *) e b a.
Monad m =>
(m (Exceptional e b) -> m (Exceptional e b))
-> (a -> b -> b) -> b -> ExceptionalT e m a -> m (Exceptional e b)
Async.manySynchronousT forall a. SIO a -> SIO a
unsafeInterleaveSIO (:) [] (Handle -> EIO Char
getChar Handle
h)

putChar :: Handle -> Char -> EIO ()
putChar :: Handle -> Char -> EIO ()
putChar Handle
h Char
c =
   forall a. IO a -> ExceptionalT IOException SIO a
ioToExceptionalSIO forall a b. (a -> b) -> a -> b
$ Handle -> Char -> IO ()
IO.hPutChar Handle
h Char
c