[project @ 2003-05-21 16:31:59 by ross]
[ghc-base.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   finalizerFree -- :: FunPtr (Ptr a -> IO ())
29 ) where
30
31 import Data.Maybe
32 import Foreign.Ptr              ( Ptr, nullPtr, FunPtr )
33 import Foreign.C.Types          ( CSize, CInt(..) )
34 import Foreign.Storable         ( Storable(sizeOf) )
35
36 #ifdef __GLASGOW_HASKELL__
37 import GHC.IOBase
38 import GHC.Real
39 import GHC.Ptr
40 import GHC.Err
41 import GHC.Base
42 #elif defined(__NHC__)
43 import IO                       ( bracket )
44 #else
45 import Control.Exception        ( bracket )
46 #endif
47
48
49 -- exported functions
50 -- ------------------
51
52 -- |Allocate space for storable type.  The size of the area allocated
53 -- is determined by the 'sizeOf' method from the instance of
54 -- 'Storable' for the appropriate type.
55 --
56 malloc :: Storable a => IO (Ptr a)
57 malloc  = doMalloc undefined
58   where
59     doMalloc       :: Storable a => a -> IO (Ptr a)
60     doMalloc dummy  = mallocBytes (sizeOf dummy)
61
62 -- |Allocate given number of bytes of storage, equivalent to C\'s @malloc()@.
63 --
64 mallocBytes      :: Int -> IO (Ptr a)
65 mallocBytes size  = failWhenNULL "malloc" (_malloc (fromIntegral size))
66
67 -- |Temporarily allocate space for a storable type.
68 --
69 -- * the pointer passed as an argument to the function must /not/ escape from
70 --   this function; in other words, in @alloca f@ the allocated storage must
71 --   not be used after @f@ returns
72 --
73 alloca :: Storable a => (Ptr a -> IO b) -> IO b
74 alloca  = doAlloca undefined
75   where
76     doAlloca       :: Storable a => a -> (Ptr a -> IO b) -> IO b
77     doAlloca dummy  = allocaBytes (sizeOf dummy)
78
79 -- |Temporarily allocate the given number of bytes of storage.
80 --
81 -- * the pointer passed as an argument to the function must /not/ escape from
82 --   this function; in other words, in @allocaBytes n f@ the allocated storage
83 --   must not be used after @f@ returns
84 --
85 #ifdef __GLASGOW_HASKELL__
86 allocaBytes :: Int -> (Ptr a -> IO b) -> IO b
87 allocaBytes (I# size) action = IO $ \ s ->
88      case newPinnedByteArray# size s      of { (# s, mbarr# #) ->
89      case unsafeFreezeByteArray# mbarr# s of { (# s, barr#  #) ->
90      let addr = Ptr (byteArrayContents# barr#) in
91      case action addr    of { IO action ->
92      case action s       of { (# s, r #) ->
93      case touch# barr# s of { s ->
94      (# s, r #)
95   }}}}}
96 #else
97 allocaBytes      :: Int -> (Ptr a -> IO b) -> IO b
98 allocaBytes size  = bracket (mallocBytes size) free
99 #endif
100
101 -- |Adjust a malloc\'ed storage area to the given size of the required type
102 -- (corresponds to C\'s @realloc()@).
103 --
104 realloc :: Storable b => Ptr a -> IO (Ptr b)
105 realloc  = doRealloc undefined
106   where
107     doRealloc           :: Storable b => b -> Ptr a -> IO (Ptr b)
108     doRealloc dummy ptr  = let
109                              size = fromIntegral (sizeOf dummy)
110                            in
111                            failWhenNULL "realloc" (_realloc ptr size)
112
113 -- |Adjust a malloc\'ed storage area to the given size (equivalent to
114 -- C\'s @realloc()@).
115 --
116 reallocBytes          :: Ptr a -> Int -> IO (Ptr a)
117 reallocBytes ptr size  = 
118   failWhenNULL "realloc" (_realloc ptr (fromIntegral size))
119
120 -- |Free malloc\'ed storage (equivalent to
121 -- C\'s @free()@)
122 --
123 free :: Ptr a -> IO ()
124 free  = _free
125
126
127 -- auxilliary routines
128 -- -------------------
129
130 -- asserts that the pointer returned from the action in the second argument is
131 -- non-null
132 --
133 failWhenNULL :: String -> IO (Ptr a) -> IO (Ptr a)
134 failWhenNULL name f = do
135    addr <- f
136    if addr == nullPtr
137 #ifdef __GLASGOW_HASKELL__
138       then ioException (IOError Nothing ResourceExhausted name 
139                                         "out of memory" Nothing)
140 #else
141       then ioError (userError (name++": out of memory"))
142 #endif
143       else return addr
144
145 -- basic C routines needed for memory allocation
146 --
147 foreign import ccall unsafe "stdlib.h malloc"  _malloc  ::          CSize -> IO (Ptr a)
148 foreign import ccall unsafe "stdlib.h realloc" _realloc :: Ptr a -> CSize -> IO (Ptr b)
149 foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()
150
151 -- | A pointer to a foreign function equivalent to 'free', which may be used
152 -- as a finalizer for storage allocated with 'malloc' or 'mallocBytes'.
153 foreign import ccall unsafe "stdlib.h &free"
154                         finalizerFree :: FunPtr (Ptr a -> IO ())