io-region-0.1.1: Exception safe resource management with dynamic regions

Safe HaskellSafe
LanguageHaskell2010

Control.IO.Region

Description

Exception safe resource management

Examples:

import Control.IO.Region (region)
import qualified Control.IO.Region as R

...
  region $ \r -> do
    resource <- R.alloc_ r allocate free
    use resource
    -- resource will be automatically freed here

...
  region $ \r -> do
    (resource, key) <- R.alloc r allocate free
    use resource
    if ...
      then R.free key  -- free it earler
      else use resource

...
  region $ \r1 -> do
    resource <- region $ \r2 -> do
      (resource1, key) <- R.alloc r2 allocate free
      use resource
      resource `R.moveTo` r1  -- transfer ownership to region r1
      return resource
    doSomethingElse resource
    -- resource will be freed here

...
  region $ \r1 -> do
    (r2, r2Key) <- R.alloc r1 R.open R.close  -- region is a resource too
    resource <- R.alloc r2 allocate free
    use resource
    r2Key `R.moveTo` r3  -- move region r2 ownership (and also the resource) to other region

Synopsis

Documentation

data Region #

Region owns resources and frees them on close

Instances

Eq Region # 

Methods

(==) :: Region -> Region -> Bool #

(/=) :: Region -> Region -> Bool #

data Key #

Each resource is identified by unique key

Instances

Eq Key # 

Methods

(==) :: Key -> Key -> Bool #

(/=) :: Key -> Key -> Bool #

region :: (Region -> IO a) -> IO a #

Create new region. It will be automatically closed on exit

open :: IO Region #

Open new region. Prefer region function.

close :: Region -> IO () #

Close the region. You probably should called it when async exceptions are masked. Prefer region function. It is error to close region twice.

In case of exception inside any cleanup handler, other handlers will be called anyway. The last exception will be rethrown (that matches the behavior of bracket.)

alloc #

Arguments

:: Region 
-> IO a

action to allocate resource

-> (a -> IO ())

action to cleanup resource

-> IO (a, Key)

the resource and it's key

Allocate resource inside the region

alloc_ :: Region -> IO a -> (a -> IO ()) -> IO a #

The same as alloc, but doesn't return the key

free :: Key -> IO () #

Free the resource earlier then it's region will be closed. It will be removed from the region immediately. It is error to free resource twice

moveToSTM :: Key -> Region -> STM Key #

Move resource to other region. The old key becomes invalid and should not be used

moveTo :: Key -> Region -> IO Key #

Move resource to other region. See also moveToSTM

defer :: Region -> IO () -> IO () #

Defer action until region is closed