module Data.Acquire.Internal
( Acquire (..)
, Allocated (..)
, with
, mkAcquire
) where
import Control.Applicative (Applicative (..))
import Control.Monad.Base (MonadBase (..))
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Trans.Control (MonadBaseControl, control)
import qualified Control.Exception.Lifted as E
import Data.Typeable (Typeable)
import Control.Monad (liftM, ap)
data Allocated a = Allocated !a !(IO ())
newtype Acquire a = Acquire ((forall b. IO b -> IO b) -> IO (Allocated a))
deriving Typeable
instance Functor Acquire where
fmap = liftM
instance Applicative Acquire where
pure = return
(<*>) = ap
instance Monad Acquire where
return a = Acquire (\_ -> return (Allocated a (return ())))
Acquire f >>= g' = Acquire $ \restore -> do
Allocated x free1 <- f restore
let Acquire g = g' x
Allocated y free2 <- g restore `E.onException` free1
return $! Allocated y (free2 `E.finally` free1)
instance MonadIO Acquire where
liftIO f = Acquire $ \restore -> do
x <- restore f
return $! Allocated x (return ())
instance MonadBase IO Acquire where
liftBase = liftIO
mkAcquire :: IO a
-> (a -> IO ())
-> Acquire a
mkAcquire create free = Acquire $ \restore -> do
x <- restore create
return $! Allocated x (free x)
with :: MonadBaseControl IO m
=> Acquire a
-> (a -> m b)
-> m b
with (Acquire f) g = control $ \run -> E.mask $ \restore -> do
Allocated x free <- f restore
run (g x) `E.finally` free