[project @ 2002-07-29 09:54:40 by ross]
[haskell-directory.git] / Foreign / Marshal / Alloc.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Foreign.Marshal.Alloc
5 -- Copyright   :  (c) The FFI task force 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  ffi@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- Marshalling support: basic routines for memory allocation
13 --
14 -----------------------------------------------------------------------------
15
16 module Foreign.Marshal.Alloc (
17   -- * Allocation
18   malloc,       -- :: Storable a =>        IO (Ptr a)
19   mallocBytes,  -- ::               Int -> IO (Ptr a)
20
21   alloca,       -- :: Storable a =>        (Ptr a -> IO b) -> IO b
22   allocaBytes,  -- ::               Int -> (Ptr a -> IO b) -> IO b
23
24   realloc,      -- :: Storable b => Ptr a        -> IO (Ptr b)
25   reallocBytes, -- ::               Ptr a -> Int -> IO (Ptr a)
26
27   free          -- :: Ptr a -> IO ()
28 ) where
29
30 import Data.Maybe
31 import Foreign.Ptr              ( Ptr, nullPtr )
32 import Foreign.C.TypesISO       ( CSize )
33 import Foreign.Storable         ( Storable(sizeOf) )
34
35 #ifdef __GLASGOW_HASKELL__
36 import GHC.Exception            ( bracket )
37 import GHC.IOBase
38 import GHC.Real
39 import GHC.Ptr
40 import GHC.Err
41 import GHC.Base
42 #else
43 import Control.Exception        ( bracket )
44 #endif
45
46
47 -- exported functions
48 -- ------------------
49
50 -- |Allocate space for storable type.  The size of the area allocated
51 -- is determined by the 'sizeOf' method from the instance of
52 -- 'Storable' for the appropriate type.
53 --
54 malloc :: Storable a => IO (Ptr a)
55 malloc  = doMalloc undefined
56   where
57     doMalloc       :: Storable a => a -> IO (Ptr a)
58     doMalloc dummy  = mallocBytes (sizeOf dummy)
59
60 -- |Allocate given number of bytes of storage, equivalent to C\'s @malloc()@.
61 --
62 mallocBytes      :: Int -> IO (Ptr a)
63 mallocBytes size  = failWhenNULL "malloc" (_malloc (fromIntegral size))
64
65 -- |Temporarily allocate space for a storable type.
66 --
67 -- * the pointer passed as an argument to the function must /not/ escape from
68 --   this function; in other words, in @alloca f@ the allocated storage must
69 --   not be used after @f@ returns
70 --
71 alloca :: Storable a => (Ptr a -> IO b) -> IO b
72 alloca  = doAlloca undefined
73   where
74     doAlloca       :: Storable a => a -> (Ptr a -> IO b) -> IO b
75     doAlloca dummy  = allocaBytes (sizeOf dummy)
76
77 -- |Temporarily allocate the given number of bytes of storage.
78 --
79 -- * the pointer passed as an argument to the function must /not/ escape from
80 --   this function; in other words, in @allocaBytes n f@ the allocated storage
81 --   must not be used after @f@ returns
82 --
83 #ifdef __GLASGOW_HASKELL__
84 allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
85 allocaBytes (I# size) action = IO $ \ s ->
86      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
87      case unsafeFreezeByteArray# mbarr# s of { (# s, barr#  #) ->
88      let addr = Ptr (byteArrayContents# barr#) in
89      case action addr    of { IO action ->
90      case action s       of { (# s, r #) ->
91      case touch# barr# s of { s ->
92      (# s, r #)
93   }}}}}
94 #else
95 allocaBytes      :: Int -> (Ptr a -> IO b) -> IO b
96 allocaBytes size  = bracket (mallocBytes size) free
97 #endif
98
99 -- |Adjust a malloc\'ed storage area to the given size of the required type
100 -- (corresponds to C\'s @realloc()@).
101 --
102 realloc :: Storable b => Ptr a -> IO (Ptr b)
103 realloc  = doRealloc undefined
104   where
105     doRealloc           :: Storable b => b -> Ptr a -> IO (Ptr b)
106     doRealloc dummy ptr  = let
107                              size = fromIntegral (sizeOf dummy)
108                            in
109                            failWhenNULL "realloc" (_realloc ptr size)
110
111 -- |Adjust a malloc\'ed storage area to the given size (equivalent to
112 -- C\'s @realloc()@).
113 --
114 reallocBytes          :: Ptr a -> Int -> IO (Ptr a)
115 reallocBytes ptr size  = 
116   failWhenNULL "realloc" (_realloc ptr (fromIntegral size))
117
118 -- |Free malloc\'ed storage (equivalent to
119 -- C\'s @free()@)
120 --
121 free :: Ptr a -> IO ()
122 free  = _free
123
124
125 -- auxilliary routines
126 -- -------------------
127
128 -- asserts that the pointer returned from the action in the second argument is
129 -- non-null
130 --
131 failWhenNULL :: String -> IO (Ptr a) -> IO (Ptr a)
132 failWhenNULL name f = do
133    addr <- f
134    if addr == nullPtr
135 #ifdef __GLASGOW_HASKELL__
136       then ioException (IOError Nothing ResourceExhausted name 
137                                         "out of memory" Nothing)
138 #else
139       then ioError (userError (name++": out of memory"))
140 #endif
141       else return addr
142
143 -- basic C routines needed for memory allocation
144 --
145 foreign import ccall unsafe "stdlib.h malloc"  _malloc  ::          CSize -> IO (Ptr a)
146 foreign import ccall unsafe "stdlib.h realloc" _realloc :: Ptr a -> CSize -> IO (Ptr b)
147 foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()