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