43fae6840628e2e3dc59caba2a3f37f3c87fb09a
[ghc-base.git] / Foreign / Storable.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  Foreign.Storable
5 -- Copyright   :  (c) The FFI task force 2001
6 -- License     :  see libraries/base/LICENSE
7 -- 
8 -- Maintainer  :  ffi@haskell.org
9 -- Stability   :  provisional
10 -- Portability :  portable
11 --
12 -- The module "Foreign.Storable" provides most elementary support for
13 -- marshalling and is part of the language-independent portion of the
14 -- Foreign Function Interface (FFI), and will normally be imported via
15 -- the "Foreign" module.
16 --
17 -----------------------------------------------------------------------------
18
19 module Foreign.Storable
20         ( Storable(
21              sizeOf,         -- :: a -> Int
22              alignment,      -- :: a -> Int
23              peekElemOff,    -- :: Ptr a -> Int      -> IO a
24              pokeElemOff,    -- :: Ptr a -> Int -> a -> IO ()
25              peekByteOff,    -- :: Ptr b -> Int      -> IO a
26              pokeByteOff,    -- :: Ptr b -> Int -> a -> IO ()
27              peek,           -- :: Ptr a             -> IO a
28              poke)           -- :: Ptr a        -> a -> IO ()
29         ) where
30
31
32 import Control.Monad            ( liftM )
33
34 #include "MachDeps.h"
35 #include "config.h"
36
37 #ifdef __GLASGOW_HASKELL__
38 import GHC.Storable
39 import GHC.Stable       ( StablePtr )
40 import GHC.Num
41 import GHC.Int
42 import GHC.Word
43 import GHC.Stable
44 import GHC.Ptr
45 import GHC.Float
46 import GHC.Err
47 import GHC.IOBase
48 import GHC.Base
49 #else
50 import Foreign.Ptr
51 #endif
52
53 #ifdef __HUGS__
54 import Hugs.Storable
55 #endif
56
57 {- |
58 The member functions of this class facilitate writing values of
59 primitive types to raw memory (which may have been allocated with the
60 above mentioned routines) and reading values from blocks of raw
61 memory.  The class, furthermore, includes support for computing the
62 storage requirements and alignment restrictions of storable types.
63
64 Memory addresses are represented as values of type @'Ptr' a@, for some
65 @a@ which is an instance of class 'Storable'.  The type argument to
66 'Ptr' helps provide some valuable type safety in FFI code (you can\'t
67 mix pointers of different types without an explicit cast), while
68 helping the Haskell type system figure out which marshalling method is
69 needed for a given pointer.
70
71 All marshalling between Haskell and a foreign language ultimately
72 boils down to translating Haskell data structures into the binary
73 representation of a corresponding data structure of the foreign
74 language and vice versa.  To code this marshalling in Haskell, it is
75 necessary to manipulate primtive data types stored in unstructured
76 memory blocks.  The class 'Storable' facilitates this manipulation on
77 all types for which it is instantiated, which are the standard basic
78 types of Haskell, the fixed size @Int@ types ('Int8', 'Int16',
79 'Int32', 'Int64'), the fixed size @Word@ types ('Word8', 'Word16',
80 'Word32', 'Word64'), 'StablePtr', all types from "CTypes" and
81 "CTypesISO", as well as 'Ptr'.
82
83 Minimal complete definition: 'sizeOf', 'alignment', one of 'peek',
84 'peekElemOff' and 'peekByteOff', and one of 'poke', 'pokeElemOff' and
85 'pokeByteOff'.
86 -}
87
88 class Storable a where
89
90    sizeOf      :: a -> Int
91    -- ^ Computes the storage requirements (in bytes) of the argument.
92    -- The value of the argument is not used.
93
94    alignment   :: a -> Int
95    -- ^ Computes the alignment constraint of the argument.  An
96    -- alignment constraint @x@ is fulfilled by any address divisible
97    -- by @x@.  The value of the argument is not used.
98
99    peekElemOff :: Ptr a -> Int      -> IO a
100    -- ^       Read a value from a memory area regarded as an array
101    --         of values of the same kind.  The first argument specifies
102    --         the start address of the array and the second the index into
103    --         the array (the first element of the array has index
104    --         @0@).  The following equality holds,
105    -- 
106    -- > peekElemOff addr idx = IOExts.fixIO $ \result ->
107    -- >   peek (addr \`plusPtr\` (idx * sizeOf result))
108    --
109    --         Note that this is only a specification, not
110    --         necessarily the concrete implementation of the
111    --         function.
112
113    pokeElemOff :: Ptr a -> Int -> a -> IO ()
114    -- ^       Write a value to a memory area regarded as an array of
115    --         values of the same kind.  The following equality holds:
116    -- 
117    -- > pokeElemOff addr idx x = 
118    -- >   poke (addr \`plusPtr\` (idx * sizeOf x)) x
119
120    peekByteOff :: Ptr b -> Int      -> IO a
121    -- ^       Read a value from a memory location given by a base
122    --         address and offset.  The following equality holds:
123    --
124    -- > peekByteOff addr off = peek (addr \`plusPtr\` off)
125
126    pokeByteOff :: Ptr b -> Int -> a -> IO ()
127    -- ^       Write a value to a memory location given by a base
128    --         address and offset.  The following equality holds:
129    --
130    -- > pokeByteOff addr off x = poke (addr \`plusPtr\` off) x
131   
132    peek        :: Ptr a      -> IO a
133    -- ^ Read a value from the given memory location.
134    --
135    --  Note that the peek and poke functions might require properly
136    --  aligned addresses to function correctly.  This is architecture
137    --  dependent; thus, portable code should ensure that when peeking or
138    --  poking values of some type @a@, the alignment
139    --  constraint for @a@, as given by the function
140    --  'alignment' is fulfilled.
141
142    poke        :: Ptr a -> a -> IO ()
143    -- ^ Write the given value to the given memory location.  Alignment
144    -- restrictions might apply; see 'peek'.
145  
146    -- circular default instances
147 #ifdef __GLASGOW_HASKELL__
148    peekElemOff = peekElemOff_ undefined
149       where peekElemOff_ :: a -> Ptr a -> Int -> IO a
150             peekElemOff_ undef ptr off = peekByteOff ptr (off * sizeOf undef)
151 #else
152    peekElemOff ptr off = peekByteOff ptr (off * sizeOfPtr ptr undefined)
153 #endif
154    pokeElemOff ptr off val = pokeByteOff ptr (off * sizeOf val) val
155
156    peekByteOff ptr off = peek (ptr `plusPtr` off)
157    pokeByteOff ptr off = poke (ptr `plusPtr` off)
158
159    peek ptr = peekElemOff ptr 0
160    poke ptr = pokeElemOff ptr 0
161
162 #ifndef __GLASGOW_HASKELL__
163 sizeOfPtr :: Storable a => Ptr a -> a -> Int
164 sizeOfPtr px x = sizeOf x
165 #endif
166
167 -- System-dependent, but rather obvious instances
168
169 instance Storable Bool where
170    sizeOf _          = sizeOf (undefined::HTYPE_INT)
171    alignment _       = alignment (undefined::HTYPE_INT)
172    peekElemOff p i   = liftM (/= (0::HTYPE_INT)) $ peekElemOff (castPtr p) i
173    pokeElemOff p i x = pokeElemOff (castPtr p) i (if x then 1 else 0::HTYPE_INT)
174
175 #define STORABLE(T,size,align,read,write)       \
176 instance Storable (T) where {                   \
177     sizeOf    _ = size;                         \
178     alignment _ = align;                        \
179     peekElemOff = read;                         \
180     pokeElemOff = write }
181
182 #ifdef __GLASGOW_HASKELL__
183 STORABLE(Char,SIZEOF_INT32,ALIGNMENT_INT32,
184          readWideCharOffPtr,writeWideCharOffPtr)
185 #elif defined(__HUGS__)
186 STORABLE(Char,SIZEOF_CHAR,ALIGNMENT_HSCHAR,
187          readCharOffPtr,writeCharOffPtr)
188 #endif
189
190 STORABLE(Int,SIZEOF_HSINT,ALIGNMENT_HSINT,
191          readIntOffPtr,writeIntOffPtr)
192
193 #ifdef __GLASGOW_HASKELL__
194 STORABLE(Word,SIZEOF_HSWORD,ALIGNMENT_HSWORD,
195          readWordOffPtr,writeWordOffPtr)
196 #endif
197
198 STORABLE((Ptr a),SIZEOF_HSPTR,ALIGNMENT_HSPTR,
199          readPtrOffPtr,writePtrOffPtr)
200
201 STORABLE((FunPtr a),SIZEOF_HSFUNPTR,ALIGNMENT_HSFUNPTR,
202          readFunPtrOffPtr,writeFunPtrOffPtr)
203
204 STORABLE((StablePtr a),SIZEOF_HSSTABLEPTR,ALIGNMENT_HSSTABLEPTR,
205          readStablePtrOffPtr,writeStablePtrOffPtr)
206
207 STORABLE(Float,SIZEOF_HSFLOAT,ALIGNMENT_HSFLOAT,
208          readFloatOffPtr,writeFloatOffPtr)
209
210 STORABLE(Double,SIZEOF_HSDOUBLE,ALIGNMENT_HSDOUBLE,
211          readDoubleOffPtr,writeDoubleOffPtr)
212
213 STORABLE(Word8,SIZEOF_WORD8,ALIGNMENT_WORD8,
214          readWord8OffPtr,writeWord8OffPtr)
215
216 STORABLE(Word16,SIZEOF_WORD16,ALIGNMENT_WORD16,
217          readWord16OffPtr,writeWord16OffPtr)
218
219 STORABLE(Word32,SIZEOF_WORD32,ALIGNMENT_WORD32,
220          readWord32OffPtr,writeWord32OffPtr)
221
222 STORABLE(Word64,SIZEOF_WORD64,ALIGNMENT_WORD64,
223          readWord64OffPtr,writeWord64OffPtr)
224
225 STORABLE(Int8,SIZEOF_INT8,ALIGNMENT_INT8,
226          readInt8OffPtr,writeInt8OffPtr)
227
228 STORABLE(Int16,SIZEOF_INT16,ALIGNMENT_INT16,
229          readInt16OffPtr,writeInt16OffPtr)
230
231 STORABLE(Int32,SIZEOF_INT32,ALIGNMENT_INT32,
232          readInt32OffPtr,writeInt32OffPtr)
233
234 STORABLE(Int64,SIZEOF_INT64,ALIGNMENT_INT64,
235          readInt64OffPtr,writeInt64OffPtr)