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