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

Safe HaskellSafe-Inferred
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 Source

Region owns resources and frees them on close

Instances

data Key Source

Each resource is identified by unique key

Instances

data AlreadyFreed Source

Resource already freed

Constructors

AlreadyFreed 

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

Create new region. It will be automatically closed on exit

open :: IO Region Source

Open new region. Prefer region function.

close :: Region -> IO () Source

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 Source

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 Source

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

free :: Key -> IO () Source

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 Source

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

moveTo :: Key -> Region -> IO Key Source

Move resource to other region. See also moveToSTM

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

Defer action until region is closed