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