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