9e8d08287da8174200729c7218dff9936277696b
[ghc-base.git] / Foreign / Marshal / Array.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Foreign.Marshal.Array
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: routines allocating, storing, and retrieving Haskell
13 -- lists that are represented as arrays in the foreign language
14 --
15 -----------------------------------------------------------------------------
16
17 module Foreign.Marshal.Array (
18   -- * Marshalling arrays
19
20   -- ** Allocation
21   --
22   mallocArray,    -- :: Storable a => Int -> IO (Ptr a)
23   mallocArray0,   -- :: Storable a => Int -> IO (Ptr a)
24
25   allocaArray,    -- :: Storable a => Int -> (Ptr a -> IO b) -> IO b
26   allocaArray0,   -- :: Storable a => Int -> (Ptr a -> IO b) -> IO b
27
28   reallocArray,   -- :: Storable a => Ptr a -> Int -> IO (Ptr a)
29   reallocArray0,  -- :: Storable a => Ptr a -> Int -> IO (Ptr a)
30
31   -- ** Marshalling
32   --
33   peekArray,      -- :: Storable a =>         Int -> Ptr a -> IO [a]
34   peekArray0,     -- :: (Storable a, Eq a) => a   -> Ptr a -> IO [a]
35
36   pokeArray,      -- :: Storable a =>      Ptr a -> [a] -> IO ()
37   pokeArray0,     -- :: Storable a => a -> Ptr a -> [a] -> IO ()
38
39   -- ** Combined allocation and marshalling
40   --
41   newArray,       -- :: Storable a =>      [a] -> IO (Ptr a)
42   newArray0,      -- :: Storable a => a -> [a] -> IO (Ptr a)
43
44   withArray,      -- :: Storable a =>      [a] -> (Ptr a -> IO b) -> IO b
45   withArray0,     -- :: Storable a => a -> [a] -> (Ptr a -> IO b) -> IO b
46
47   withArrayLen,   -- :: Storable a =>      [a] -> (Int -> Ptr a -> IO b) -> IO b
48   withArrayLen0,  -- :: Storable a => a -> [a] -> (Int -> Ptr a -> IO b) -> IO b
49
50   -- ** Copying
51
52   -- | (argument order: destination, source)
53   copyArray,      -- :: Storable a => Ptr a -> Ptr a -> Int -> IO ()
54   moveArray,      -- :: Storable a => Ptr a -> Ptr a -> Int -> IO ()
55
56   -- ** Finding the length
57   --
58   lengthArray0,   -- :: (Storable a, Eq a) => a -> Ptr a -> IO Int
59
60   -- ** Indexing
61   --
62   advancePtr,     -- :: Storable a => Ptr a -> Int -> Ptr a
63 ) where
64
65 import Foreign.Ptr      (Ptr, plusPtr)
66 import Foreign.Storable (Storable(alignment,sizeOf,peekElemOff,pokeElemOff))
67 import Foreign.Marshal.Alloc (mallocBytes, allocaBytesAligned, reallocBytes)
68 import Foreign.Marshal.Utils (copyBytes, moveBytes)
69
70 #ifdef __GLASGOW_HASKELL__
71 import GHC.Num
72 import GHC.List
73 import GHC.Err
74 import GHC.Base
75 #else
76 import Control.Monad (zipWithM_)
77 #endif
78
79 -- allocation
80 -- ----------
81
82 -- |Allocate storage for the given number of elements of a storable type
83 -- (like 'Foreign.Marshal.Alloc.malloc', but for multiple elements).
84 --
85 mallocArray :: Storable a => Int -> IO (Ptr a)
86 mallocArray  = doMalloc undefined
87   where
88     doMalloc            :: Storable a' => a' -> Int -> IO (Ptr a')
89     doMalloc dummy size  = mallocBytes (size * sizeOf dummy)
90
91 -- |Like 'mallocArray', but add an extra position to hold a special
92 -- termination element.
93 --
94 mallocArray0      :: Storable a => Int -> IO (Ptr a)
95 mallocArray0 size  = mallocArray (size + 1)
96
97 -- |Temporarily allocate space for the given number of elements
98 -- (like 'Foreign.Marshal.Alloc.alloca', but for multiple elements).
99 --
100 allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b
101 allocaArray  = doAlloca undefined
102   where
103     doAlloca            :: Storable a' => a' -> Int -> (Ptr a' -> IO b') -> IO b'
104     doAlloca dummy size  = allocaBytesAligned (size * sizeOf dummy)
105                                               (alignment dummy)
106
107 -- |Like 'allocaArray', but add an extra position to hold a special
108 -- termination element.
109 --
110 allocaArray0      :: Storable a => Int -> (Ptr a -> IO b) -> IO b
111 allocaArray0 size  = allocaArray (size + 1)
112 {-# INLINE allocaArray0 #-}
113   -- needed to get allocaArray to inline into withCString, for unknown
114   -- reasons --SDM 23/4/2010, see #4004 for benchmark
115
116 -- |Adjust the size of an array
117 --
118 reallocArray :: Storable a => Ptr a -> Int -> IO (Ptr a)
119 reallocArray  = doRealloc undefined
120   where
121     doRealloc                :: Storable a' => a' -> Ptr a' -> Int -> IO (Ptr a')
122     doRealloc dummy ptr size  = reallocBytes ptr (size * sizeOf dummy)
123
124 -- |Adjust the size of an array including an extra position for the end marker.
125 --
126 reallocArray0          :: Storable a => Ptr a -> Int -> IO (Ptr a)
127 reallocArray0 ptr size  = reallocArray ptr (size + 1)
128
129
130 -- marshalling
131 -- -----------
132
133 -- |Convert an array of given length into a Haskell list.  The implementation
134 -- is tail-recursive and so uses constant stack space.
135 --
136 peekArray          :: Storable a => Int -> Ptr a -> IO [a]
137 peekArray size ptr | size <= 0 = return []
138                  | otherwise = f (size-1) []
139   where
140     f 0 acc = do e <- peekElemOff ptr 0; return (e:acc)
141     f n acc = do e <- peekElemOff ptr n; f (n-1) (e:acc)
142   
143 -- |Convert an array terminated by the given end marker into a Haskell list
144 --
145 peekArray0            :: (Storable a, Eq a) => a -> Ptr a -> IO [a]
146 peekArray0 marker ptr  = do
147   size <- lengthArray0 marker ptr
148   peekArray size ptr
149
150 -- |Write the list elements consecutive into memory
151 --
152 pokeArray :: Storable a => Ptr a -> [a] -> IO ()
153 #ifndef __GLASGOW_HASKELL__
154 pokeArray ptr vals =  zipWithM_ (pokeElemOff ptr) [0..] vals
155 #else
156 pokeArray ptr vals0 = go vals0 0#
157   where go [] _          = return ()
158         go (val:vals) n# = do pokeElemOff ptr (I# n#) val; go vals (n# +# 1#)
159 #endif
160
161 -- |Write the list elements consecutive into memory and terminate them with the
162 -- given marker element
163 --
164 pokeArray0 :: Storable a => a -> Ptr a -> [a] -> IO ()
165 #ifndef __GLASGOW_HASKELL__
166 pokeArray0 marker ptr vals  = do
167   pokeArray ptr vals
168   pokeElemOff ptr (length vals) marker
169 #else
170 pokeArray0 marker ptr vals0 = go vals0 0#
171   where go [] n#         = pokeElemOff ptr (I# n#) marker
172         go (val:vals) n# = do pokeElemOff ptr (I# n#) val; go vals (n# +# 1#)
173 #endif
174
175
176 -- combined allocation and marshalling
177 -- -----------------------------------
178
179 -- |Write a list of storable elements into a newly allocated, consecutive
180 -- sequence of storable values
181 -- (like 'Foreign.Marshal.Utils.new', but for multiple elements).
182 --
183 newArray      :: Storable a => [a] -> IO (Ptr a)
184 newArray vals  = do
185   ptr <- mallocArray (length vals)
186   pokeArray ptr vals
187   return ptr
188
189 -- |Write a list of storable elements into a newly allocated, consecutive
190 -- sequence of storable values, where the end is fixed by the given end marker
191 --
192 newArray0             :: Storable a => a -> [a] -> IO (Ptr a)
193 newArray0 marker vals  = do
194   ptr <- mallocArray0 (length vals)
195   pokeArray0 marker ptr vals
196   return ptr
197
198 -- |Temporarily store a list of storable values in memory
199 -- (like 'Foreign.Marshal.Utils.with', but for multiple elements).
200 --
201 withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b
202 withArray vals = withArrayLen vals . const
203
204 -- |Like 'withArray', but the action gets the number of values
205 -- as an additional parameter
206 --
207 withArrayLen :: Storable a => [a] -> (Int -> Ptr a -> IO b) -> IO b
208 withArrayLen vals f  =
209   allocaArray len $ \ptr -> do
210       pokeArray ptr vals
211       res <- f len ptr
212       return res
213   where
214     len = length vals
215
216 -- |Like 'withArray', but a terminator indicates where the array ends
217 --
218 withArray0 :: Storable a => a -> [a] -> (Ptr a -> IO b) -> IO b
219 withArray0 marker vals = withArrayLen0 marker vals . const
220
221 -- |Like 'withArrayLen', but a terminator indicates where the array ends
222 --
223 withArrayLen0 :: Storable a => a -> [a] -> (Int -> Ptr a -> IO b) -> IO b
224 withArrayLen0 marker vals f  =
225   allocaArray0 len $ \ptr -> do
226       pokeArray0 marker ptr vals
227       res <- f len ptr
228       return res
229   where
230     len = length vals
231
232
233 -- copying (argument order: destination, source)
234 -- -------
235
236 -- |Copy the given number of elements from the second array (source) into the
237 -- first array (destination); the copied areas may /not/ overlap
238 --
239 copyArray :: Storable a => Ptr a -> Ptr a -> Int -> IO ()
240 copyArray  = doCopy undefined
241   where
242     doCopy                     :: Storable a' => a' -> Ptr a' -> Ptr a' -> Int -> IO ()
243     doCopy dummy dest src size  = copyBytes dest src (size * sizeOf dummy)
244
245 -- |Copy the given number of elements from the second array (source) into the
246 -- first array (destination); the copied areas /may/ overlap
247 --
248 moveArray :: Storable a => Ptr a -> Ptr a -> Int -> IO ()
249 moveArray  = doMove undefined
250   where
251     doMove                     :: Storable a' => a' -> Ptr a' -> Ptr a' -> Int -> IO ()
252     doMove dummy dest src size  = moveBytes dest src (size * sizeOf dummy)
253
254
255 -- finding the length
256 -- ------------------
257
258 -- |Return the number of elements in an array, excluding the terminator
259 --
260 lengthArray0            :: (Storable a, Eq a) => a -> Ptr a -> IO Int
261 lengthArray0 marker ptr  = loop 0
262   where
263     loop i = do
264         val <- peekElemOff ptr i
265         if val == marker then return i else loop (i+1)
266
267
268 -- indexing
269 -- --------
270
271 -- |Advance a pointer into an array by the given number of elements
272 --
273 advancePtr :: Storable a => Ptr a -> Int -> Ptr a
274 advancePtr  = doAdvance undefined
275   where
276     doAdvance             :: Storable a' => a' -> Ptr a' -> Int -> Ptr a'
277     doAdvance dummy ptr i  = ptr `plusPtr` (i * sizeOf dummy)